2 // System.Net.HttpListenerRequest
5 // Gonzalo Paniagua Javier (gonzalo.mono@gmail.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
9 // Copyright (c) 2011-2012 Xamarin, Inc. (http://xamarin.com)
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 using System.Collections;
32 using System.Collections.Specialized;
33 using System.Globalization;
35 using System.Security.Cryptography.X509Certificates;
37 using System.Security.Authentication.ExtendedProtection;
38 using System.Threading.Tasks;
41 namespace System.Net {
42 public sealed class HttpListenerRequest
44 class Context : TransportContext
46 public override ChannelBinding GetChannelBinding (ChannelBindingKind kind)
48 throw new NotImplementedException ();
52 string [] accept_types;
53 Encoding content_encoding;
56 CookieCollection cookies;
57 WebHeaderCollection headers;
61 NameValueCollection query_string; // check if null is ok, check if read-only, check case-sensitiveness
65 string [] user_languages;
66 HttpListenerContext context;
70 delegate X509Certificate2 GCCDelegate ();
71 GCCDelegate gcc_delegate;
73 static byte [] _100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n");
75 internal HttpListenerRequest (HttpListenerContext context)
77 this.context = context;
78 headers = new WebHeaderCollection ();
79 version = HttpVersion.Version10;
82 static char [] separators = new char [] { ' ' };
84 internal void SetRequestLine (string req)
86 string [] parts = req.Split (separators, 3);
87 if (parts.Length != 3) {
88 context.ErrorMessage = "Invalid request line (parts).";
93 foreach (char c in method){
96 if ((ic >= 'A' && ic <= 'Z') ||
97 (ic > 32 && c < 127 && c != '(' && c != ')' && c != '<' &&
98 c != '<' && c != '>' && c != '@' && c != ',' && c != ';' &&
99 c != ':' && c != '\\' && c != '"' && c != '/' && c != '[' &&
100 c != ']' && c != '?' && c != '=' && c != '{' && c != '}'))
103 context.ErrorMessage = "(Invalid verb)";
108 if (parts [2].Length != 8 || !parts [2].StartsWith ("HTTP/")) {
109 context.ErrorMessage = "Invalid request line (version).";
114 version = new Version (parts [2].Substring (5));
115 if (version.Major < 1)
116 throw new Exception ();
118 context.ErrorMessage = "Invalid request line (version).";
123 void CreateQueryString (string query)
125 if (query == null || query.Length == 0) {
126 query_string = new NameValueCollection (1);
130 query_string = new NameValueCollection ();
131 if (query [0] == '?')
132 query = query.Substring (1);
133 string [] components = query.Split ('&');
134 foreach (string kv in components) {
135 int pos = kv.IndexOf ('=');
137 query_string.Add (null, WebUtility.UrlDecode (kv));
139 string key = WebUtility.UrlDecode (kv.Substring (0, pos));
140 string val = WebUtility.UrlDecode (kv.Substring (pos + 1));
142 query_string.Add (key, val);
147 static bool MaybeUri (string s)
149 int p = s.IndexOf (':');
156 return IsPredefinedScheme (s.Substring (0, p));
160 // Using a simple block of if's is twice as slow as the compiler generated
161 // switch statement. But using this tuned code is faster than the
162 // compiler generated code, with a million loops on x86-64:
164 // With "http": .10 vs .51 (first check)
165 // with "https": .16 vs .51 (second check)
166 // with "foo": .22 vs .31 (never found)
167 // with "mailto": .12 vs .51 (last check)
170 static bool IsPredefinedScheme (string scheme)
172 if (scheme == null || scheme.Length < 3)
177 return (scheme == "http" || scheme == "https");
179 return (scheme == "file" || scheme == "ftp");
184 return (scheme == "news" || scheme == "net.pipe" || scheme == "net.tcp");
185 if (scheme == "nntp")
189 if ((c == 'g' && scheme == "gopher") || (c == 'm' && scheme == "mailto"))
195 internal void FinishInitialization ()
197 string host = UserHostName;
198 if (version > HttpVersion.Version10 && (host == null || host.Length == 0)) {
199 context.ErrorMessage = "Invalid host name";
205 if (MaybeUri (raw_url.ToLowerInvariant ()) && Uri.TryCreate (raw_url, UriKind.Absolute, out raw_uri))
206 path = raw_uri.PathAndQuery;
210 if ((host == null || host.Length == 0))
211 host = UserHostAddress;
216 int colon = host.IndexOf (':');
218 host = host.Substring (0, colon);
220 string base_uri = String.Format ("{0}://{1}:{2}",
221 (IsSecureConnection) ? "https" : "http",
222 host, LocalEndPoint.Port);
224 if (!Uri.TryCreate (base_uri + path, UriKind.Absolute, out url)){
225 context.ErrorMessage = WebUtility.HtmlEncode ("Invalid url: " + base_uri + path);
229 CreateQueryString (url.Query);
231 // Use reference source HttpListenerRequestUriBuilder to process url.
233 url = HttpListenerRequestUriBuilder.GetRequestUri (raw_url, url.Scheme,
234 url.Authority, url.LocalPath, url.Query);
236 if (version >= HttpVersion.Version11) {
237 string t_encoding = Headers ["Transfer-Encoding"];
238 is_chunked = (t_encoding != null && String.Compare (t_encoding, "chunked", StringComparison.OrdinalIgnoreCase) == 0);
239 // 'identity' is not valid!
240 if (t_encoding != null && !is_chunked) {
241 context.Connection.SendError (null, 501);
246 if (!is_chunked && !cl_set) {
247 if (String.Compare (method, "POST", StringComparison.OrdinalIgnoreCase) == 0 ||
248 String.Compare (method, "PUT", StringComparison.OrdinalIgnoreCase) == 0) {
249 context.Connection.SendError (null, 411);
254 if (String.Compare (Headers ["Expect"], "100-continue", StringComparison.OrdinalIgnoreCase) == 0) {
255 ResponseStream output = context.Connection.GetResponseStream ();
256 output.InternalWrite (_100continue, 0, _100continue.Length);
260 internal static string Unquote (String str) {
261 int start = str.IndexOf ('\"');
262 int end = str.LastIndexOf ('\"');
263 if (start >= 0 && end >=0)
264 str = str.Substring (start + 1, end - 1);
268 internal void AddHeader (string header)
270 int colon = header.IndexOf (':');
271 if (colon == -1 || colon == 0) {
272 context.ErrorMessage = "Bad Request";
273 context.ErrorStatus = 400;
277 string name = header.Substring (0, colon).Trim ();
278 string val = header.Substring (colon + 1).Trim ();
279 string lower = name.ToLower (CultureInfo.InvariantCulture);
280 headers.SetInternal (name, val);
282 case "accept-language":
283 user_languages = val.Split (','); // yes, only split with a ','
286 accept_types = val.Split (','); // yes, only split with a ','
288 case "content-length":
290 //TODO: max. content_length?
291 content_length = Int64.Parse (val.Trim ());
292 if (content_length < 0)
293 context.ErrorMessage = "Invalid Content-Length.";
296 context.ErrorMessage = "Invalid Content-Length.";
302 referrer = new Uri (val);
304 referrer = new Uri ("http://someone.is.screwing.with.the.headers.com/");
309 cookies = new CookieCollection();
311 string[] cookieStrings = val.Split(new char[] {',', ';'});
312 Cookie current = null;
314 foreach (string cookieString in cookieStrings) {
315 string str = cookieString.Trim ();
318 if (str.StartsWith ("$Version")) {
319 version = Int32.Parse (Unquote (str.Substring (str.IndexOf ('=') + 1)));
320 } else if (str.StartsWith ("$Path")) {
322 current.Path = str.Substring (str.IndexOf ('=') + 1).Trim ();
323 } else if (str.StartsWith ("$Domain")) {
325 current.Domain = str.Substring (str.IndexOf ('=') + 1).Trim ();
326 } else if (str.StartsWith ("$Port")) {
328 current.Port = str.Substring (str.IndexOf ('=') + 1).Trim ();
330 if (current != null) {
331 cookies.Add (current);
334 current = new Cookie ();
335 int idx = str.IndexOf ('=');
337 current.Name = str.Substring (0, idx).Trim ();
338 current.Value = str.Substring (idx + 1).Trim ();
340 current.Name = str.Trim ();
341 current.Value = String.Empty;
343 current.Version = version;
344 } catch (CookieException) {
349 if (current != null) {
350 cookies.Add (current);
356 // returns true is the stream could be reused.
357 internal bool FlushInput ()
363 if (content_length > 0)
364 length = (int) Math.Min (content_length, (long) length);
366 byte [] bytes = new byte [length];
368 // TODO: test if MS has a timeout when doing this
370 IAsyncResult ares = InputStream.BeginRead (bytes, 0, length, null, null);
371 if (!ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne (1000))
373 if (InputStream.EndRead (ares) <= 0)
375 } catch (ObjectDisposedException) {
384 public string [] AcceptTypes {
385 get { return accept_types; }
388 public int ClientCertificateError {
390 HttpConnection cnc = context.Connection;
391 if (cnc.ClientCertificate == null)
392 throw new InvalidOperationException ("No client certificate");
393 int [] errors = cnc.ClientCertificateErrors;
394 if (errors != null && errors.Length > 0)
400 public Encoding ContentEncoding {
402 if (content_encoding == null)
403 content_encoding = Encoding.Default;
404 return content_encoding;
408 public long ContentLength64 {
409 get { return is_chunked ? -1 : content_length; }
412 public string ContentType {
413 get { return headers ["content-type"]; }
416 public CookieCollection Cookies {
418 // TODO: check if the collection is read-only
420 cookies = new CookieCollection ();
425 public bool HasEntityBody {
426 get { return (content_length > 0 || is_chunked); }
429 public NameValueCollection Headers {
430 get { return headers; }
433 public string HttpMethod {
434 get { return method; }
437 public Stream InputStream {
439 if (input_stream == null) {
440 if (is_chunked || content_length > 0)
441 input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
443 input_stream = Stream.Null;
450 [MonoTODO ("Always returns false")]
451 public bool IsAuthenticated {
452 get { return false; }
455 public bool IsLocal {
456 get { return LocalEndPoint.Address.Equals (RemoteEndPoint.Address); }
459 public bool IsSecureConnection {
460 get { return context.Connection.IsSecure; }
463 public bool KeepAlive {
469 // 1. Connection header
470 // 2. Protocol (1.1 == keep-alive by default)
471 // 3. Keep-Alive header
472 string cnc = headers ["Connection"];
473 if (!String.IsNullOrEmpty (cnc)) {
474 keep_alive = (0 == String.Compare (cnc, "keep-alive", StringComparison.OrdinalIgnoreCase));
475 } else if (version == HttpVersion.Version11) {
478 cnc = headers ["keep-alive"];
479 if (!String.IsNullOrEmpty (cnc))
480 keep_alive = (0 != String.Compare (cnc, "closed", StringComparison.OrdinalIgnoreCase));
486 public IPEndPoint LocalEndPoint {
487 get { return context.Connection.LocalEndPoint; }
490 public Version ProtocolVersion {
491 get { return version; }
494 public NameValueCollection QueryString {
495 get { return query_string; }
498 public string RawUrl {
499 get { return raw_url; }
502 public IPEndPoint RemoteEndPoint {
503 get { return context.Connection.RemoteEndPoint; }
506 [MonoTODO ("Always returns Guid.Empty")]
507 public Guid RequestTraceIdentifier {
508 get { return Guid.Empty; }
515 public Uri UrlReferrer {
516 get { return referrer; }
519 public string UserAgent {
520 get { return headers ["user-agent"]; }
523 public string UserHostAddress {
524 get { return LocalEndPoint.ToString (); }
527 public string UserHostName {
528 get { return headers ["host"]; }
531 public string [] UserLanguages {
532 get { return user_languages; }
535 public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, object state)
537 if (gcc_delegate == null)
538 gcc_delegate = new GCCDelegate (GetClientCertificate);
539 return gcc_delegate.BeginInvoke (requestCallback, state);
542 public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
544 if (asyncResult == null)
545 throw new ArgumentNullException ("asyncResult");
547 if (gcc_delegate == null)
548 throw new InvalidOperationException ();
550 return gcc_delegate.EndInvoke (asyncResult);
553 public X509Certificate2 GetClientCertificate ()
555 return context.Connection.ClientCertificate;
559 public string ServiceName {
565 public TransportContext TransportContext {
567 return new Context ();
572 public bool IsWebSocketRequest {
578 public Task<X509Certificate2> GetClientCertificateAsync ()
580 return Task<X509Certificate2>.Factory.FromAsync (BeginGetClientCertificate, EndGetClientCertificate, null);