2 // System.Net.HttpListenerRequest
5 // Gonzalo Paniagua Javier (gonzalo@novell.com)
7 // Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 #if NET_2_0 && SECURITY_DEP
31 using System.Collections;
32 using System.Collections.Specialized;
33 using System.Globalization;
35 using System.Security.Cryptography.X509Certificates;
37 namespace System.Net {
38 public sealed class HttpListenerRequest
40 string [] accept_types;
41 int client_cert_error;
42 Encoding content_encoding;
45 CookieCollection cookies;
46 WebHeaderCollection headers;
49 bool is_authenticated;
51 NameValueCollection query_string; // check if null is ok, check if read-only, check case-sensitiveness
56 string [] user_languages;
57 bool no_get_certificate;
58 HttpListenerContext context;
60 static byte [] _100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n");
62 internal HttpListenerRequest (HttpListenerContext context)
64 this.context = context;
65 headers = new WebHeaderCollection ();
66 input_stream = Stream.Null;
69 static char [] separators = new char [] { ' ' };
72 static readonly string [] methods = new string [] { "GET", "POST", "HEAD",
73 "PUT", "CONNECT", "MKCOL" };
75 internal void SetRequestLine (string req)
77 string [] parts = req.Split (separators, 3);
78 if (parts.Length != 3) {
79 context.ErrorMessage = "Invalid request line (parts).";
84 foreach (char c in method){
87 if ((ic >= 'A' && ic <= 'Z') ||
88 (ic >= 'a' && ic <= 'z') ||
89 (ic > 32 && c < 127 && c != '(' && c != ')' && c != '<' &&
90 c != '<' && c != '>' && c != '@' && c != ',' && c != ';' &&
91 c != ':' && c != '\\' && c != '"' && c != '/' && c != '[' &&
92 c != ']' && c != '?' && c != '=' && c != '{' && c != '}'))
95 context.ErrorMessage = "(Invalid verb)";
101 // According to bug #80504 we should allow any verbs to go
104 if (Array.IndexOf (methods, method) == -1) {
105 context.ErrorMessage = "Invalid request line (verb).";
111 if (parts [2].Length != 8 || !parts [2].StartsWith ("HTTP/")) {
112 context.ErrorMessage = "Invalid request line (version).";
117 version = new Version (parts [2].Substring (5));
118 if (version.Major < 1)
119 throw new Exception ();
121 context.ErrorMessage = "Invalid request line (version).";
126 void CreateQueryString (string query)
128 query_string = new NameValueCollection ();
129 if (query == null || query.Length == 0)
132 if (query [0] == '?')
133 query = query.Substring (1);
134 string [] components = query.Split ('&');
135 foreach (string kv in components) {
136 int pos = kv.IndexOf ('=');
138 query_string.Add (null, HttpUtility.UrlDecode (kv));
140 string key = HttpUtility.UrlDecode (kv.Substring (0, pos));
141 string val = HttpUtility.UrlDecode (kv.Substring (pos + 1));
143 query_string.Add (key, val);
148 internal void FinishInitialization ()
150 string host = UserHostName;
151 if (version > HttpVersion.Version10 && (host == null || host == "")) {
152 context.ErrorMessage = "Invalid host name";
156 if (host == null || host == "")
157 host = UserHostAddress;
159 int colon = host.IndexOf (':');
161 host = host.Substring (0, colon);
163 string base_uri = String.Format ("{0}://{1}:{2}",
164 (IsSecureConnection) ? "https" : "http",
168 url = new Uri (base_uri + raw_url);
170 context.ErrorMessage = "Invalid url";
174 CreateQueryString (url.Query);
176 if (method == "GET" || method == "HEAD")
179 string t_encoding = null;
180 if (version >= HttpVersion.Version11) {
181 t_encoding = Headers ["Transfer-Encoding"];
182 // 'identity' is not valid!
183 if (t_encoding != null && t_encoding != "chunked") {
184 context.Connection.SendError (null, 501);
189 bool is_chunked = (t_encoding == "chunked");
190 if (!is_chunked && !cl_set) {
191 context.Connection.SendError (null, 411);
195 if (is_chunked || content_length > 0) {
196 input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
199 if (Headers ["Expect"] == "100-continue") {
200 ResponseStream output = context.Connection.GetResponseStream ();
201 output.InternalWrite (_100continue, 0, _100continue.Length);
205 internal void AddHeader (string header)
207 int colon = header.IndexOf (':');
208 if (colon == -1 || colon == 0) {
209 context.ErrorMessage = "Bad Request";
213 string name = header.Substring (0, colon).Trim ();
214 string val = header.Substring (colon + 1).Trim ();
215 string lower = name.ToLower (CultureInfo.InvariantCulture);
216 headers.SetInternal (name, val);
218 case "accept-language":
219 user_languages = val.Split (','); // yes, only split with a ','
222 accept_types = val.Split (','); // yes, only split with a ','
224 case "content-length":
226 //TODO: max. content_length?
227 content_length = Int64.Parse (val.Trim ());
228 if (content_length < 0)
229 context.ErrorMessage = "Invalid Content-Length.";
232 context.ErrorMessage = "Invalid Content-Length.";
238 referrer = new Uri (val);
240 referrer = new Uri ("http://someone.is.screwing.with.the.headers.com/");
243 //TODO: cookie headers
247 public string [] AcceptTypes {
248 get { return accept_types; }
251 public int ClientCertificateError {
253 if (no_get_certificate)
254 throw new InvalidOperationException (
255 "Call GetClientCertificate() before calling this method.");
256 return client_cert_error;
260 public Encoding ContentEncoding {
262 if (content_encoding == null)
263 content_encoding = Encoding.Default;
264 return content_encoding;
268 public long ContentLength64 {
269 get { return content_length; }
272 public string ContentType {
273 get { return headers ["content-type"]; }
276 public CookieCollection Cookies {
278 // TODO: check if the collection is read-only
280 cookies = new CookieCollection ();
285 public bool HasEntityBody {
286 get { return (method == "GET" || method == "HEAD" || content_length <= 0 || is_chunked); }
289 public NameValueCollection Headers {
290 get { return headers; }
293 public string HttpMethod {
294 get { return method; }
297 public Stream InputStream {
298 get { return input_stream; }
301 public bool IsAuthenticated {
302 get { return is_authenticated; }
305 public bool IsLocal {
306 get { return IPAddress.IsLoopback (RemoteEndPoint.Address); }
309 public bool IsSecureConnection {
310 get { return context.Connection.IsSecure; }
313 public bool KeepAlive {
314 get { return false; }
317 public IPEndPoint LocalEndPoint {
318 get { return context.Connection.LocalEndPoint; }
321 public Version ProtocolVersion {
322 get { return version; }
325 public NameValueCollection QueryString {
326 get { return query_string; }
329 public string RawUrl {
330 get { return raw_url; }
333 public IPEndPoint RemoteEndPoint {
334 get { return context.Connection.RemoteEndPoint; }
337 public Guid RequestTraceIdentifier {
338 get { return identifier; }
345 public Uri UrlReferrer {
346 get { return referrer; }
349 public string UserAgent {
350 get { return headers ["user-agent"]; }
353 public string UserHostAddress {
354 get { return LocalEndPoint.ToString (); }
357 public string UserHostName {
358 get { return headers ["host"]; }
361 public string [] UserLanguages {
362 get { return user_languages; }
365 public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, Object state)
370 public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
373 // set no_client_certificate once done.
376 public X509Certificate2 GetClientCertificate ()
378 // set no_client_certificate once done.
380 // InvalidOp if call in progress.