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.
33 extern alias MonoSecurity;
35 using System.Collections;
36 using System.Collections.Specialized;
37 using System.Globalization;
39 using System.Security.Cryptography.X509Certificates;
42 using System.Security.Authentication.ExtendedProtection;
45 using System.Threading.Tasks;
47 using MonoSecurity::Mono.Security.Protocol.Tls;
49 namespace System.Net {
50 public sealed class HttpListenerRequest
53 class Context : TransportContext
55 public override ChannelBinding GetChannelBinding (ChannelBindingKind kind)
57 throw new NotImplementedException ();
62 string [] accept_types;
63 Encoding content_encoding;
66 CookieCollection cookies;
67 WebHeaderCollection headers;
71 NameValueCollection query_string; // check if null is ok, check if read-only, check case-sensitiveness
75 string [] user_languages;
76 HttpListenerContext context;
80 delegate X509Certificate2 GCCDelegate ();
81 GCCDelegate gcc_delegate;
83 static byte [] _100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n");
85 internal HttpListenerRequest (HttpListenerContext context)
87 this.context = context;
88 headers = new WebHeaderCollection ();
89 version = HttpVersion.Version10;
92 static char [] separators = new char [] { ' ' };
94 internal void SetRequestLine (string req)
96 string [] parts = req.Split (separators, 3);
97 if (parts.Length != 3) {
98 context.ErrorMessage = "Invalid request line (parts).";
103 foreach (char c in method){
106 if ((ic >= 'A' && ic <= 'Z') ||
107 (ic > 32 && c < 127 && c != '(' && c != ')' && c != '<' &&
108 c != '<' && c != '>' && c != '@' && c != ',' && c != ';' &&
109 c != ':' && c != '\\' && c != '"' && c != '/' && c != '[' &&
110 c != ']' && c != '?' && c != '=' && c != '{' && c != '}'))
113 context.ErrorMessage = "(Invalid verb)";
118 if (parts [2].Length != 8 || !parts [2].StartsWith ("HTTP/")) {
119 context.ErrorMessage = "Invalid request line (version).";
124 version = new Version (parts [2].Substring (5));
125 if (version.Major < 1)
126 throw new Exception ();
128 context.ErrorMessage = "Invalid request line (version).";
133 void CreateQueryString (string query)
135 if (query == null || query.Length == 0) {
136 query_string = new NameValueCollection (1);
140 query_string = new NameValueCollection ();
141 if (query [0] == '?')
142 query = query.Substring (1);
143 string [] components = query.Split ('&');
144 foreach (string kv in components) {
145 int pos = kv.IndexOf ('=');
147 query_string.Add (null, HttpUtility.UrlDecode (kv));
149 string key = HttpUtility.UrlDecode (kv.Substring (0, pos));
150 string val = HttpUtility.UrlDecode (kv.Substring (pos + 1));
152 query_string.Add (key, val);
157 internal void FinishInitialization ()
159 string host = UserHostName;
160 if (version > HttpVersion.Version10 && (host == null || host.Length == 0)) {
161 context.ErrorMessage = "Invalid host name";
167 if (Uri.MaybeUri (raw_url) && Uri.TryCreate (raw_url, UriKind.Absolute, out raw_uri))
168 path = raw_uri.PathAndQuery;
172 if ((host == null || host.Length == 0))
173 host = UserHostAddress;
178 int colon = host.IndexOf (':');
180 host = host.Substring (0, colon);
182 string base_uri = String.Format ("{0}://{1}:{2}",
183 (IsSecureConnection) ? "https" : "http",
184 host, LocalEndPoint.Port);
186 if (!Uri.TryCreate (base_uri + path, UriKind.Absolute, out url)){
187 context.ErrorMessage = "Invalid url: " + base_uri + path;
191 CreateQueryString (url.Query);
193 if (version >= HttpVersion.Version11) {
194 string t_encoding = Headers ["Transfer-Encoding"];
195 is_chunked = (t_encoding != null && String.Compare (t_encoding, "chunked", StringComparison.OrdinalIgnoreCase) == 0);
196 // 'identity' is not valid!
197 if (t_encoding != null && !is_chunked) {
198 context.Connection.SendError (null, 501);
203 if (!is_chunked && !cl_set) {
204 if (String.Compare (method, "POST", StringComparison.OrdinalIgnoreCase) == 0 ||
205 String.Compare (method, "PUT", StringComparison.OrdinalIgnoreCase) == 0) {
206 context.Connection.SendError (null, 411);
211 if (String.Compare (Headers ["Expect"], "100-continue", StringComparison.OrdinalIgnoreCase) == 0) {
212 ResponseStream output = context.Connection.GetResponseStream ();
213 output.InternalWrite (_100continue, 0, _100continue.Length);
217 internal static string Unquote (String str) {
218 int start = str.IndexOf ('\"');
219 int end = str.LastIndexOf ('\"');
220 if (start >= 0 && end >=0)
221 str = str.Substring (start + 1, end - 1);
225 internal void AddHeader (string header)
227 int colon = header.IndexOf (':');
228 if (colon == -1 || colon == 0) {
229 context.ErrorMessage = "Bad Request";
230 context.ErrorStatus = 400;
234 string name = header.Substring (0, colon).Trim ();
235 string val = header.Substring (colon + 1).Trim ();
236 string lower = name.ToLower (CultureInfo.InvariantCulture);
237 headers.SetInternal (name, val);
239 case "accept-language":
240 user_languages = val.Split (','); // yes, only split with a ','
243 accept_types = val.Split (','); // yes, only split with a ','
245 case "content-length":
247 //TODO: max. content_length?
248 content_length = Int64.Parse (val.Trim ());
249 if (content_length < 0)
250 context.ErrorMessage = "Invalid Content-Length.";
253 context.ErrorMessage = "Invalid Content-Length.";
259 referrer = new Uri (val);
261 referrer = new Uri ("http://someone.is.screwing.with.the.headers.com/");
266 cookies = new CookieCollection();
268 string[] cookieStrings = val.Split(new char[] {',', ';'});
269 Cookie current = null;
271 foreach (string cookieString in cookieStrings) {
272 string str = cookieString.Trim ();
275 if (str.StartsWith ("$Version")) {
276 version = Int32.Parse (Unquote (str.Substring (str.IndexOf ('=') + 1)));
277 } else if (str.StartsWith ("$Path")) {
279 current.Path = str.Substring (str.IndexOf ('=') + 1).Trim ();
280 } else if (str.StartsWith ("$Domain")) {
282 current.Domain = str.Substring (str.IndexOf ('=') + 1).Trim ();
283 } else if (str.StartsWith ("$Port")) {
285 current.Port = str.Substring (str.IndexOf ('=') + 1).Trim ();
287 if (current != null) {
288 cookies.Add (current);
290 current = new Cookie ();
291 int idx = str.IndexOf ('=');
293 current.Name = str.Substring (0, idx).Trim ();
294 current.Value = str.Substring (idx + 1).Trim ();
296 current.Name = str.Trim ();
297 current.Value = String.Empty;
299 current.Version = version;
302 if (current != null) {
303 cookies.Add (current);
309 // returns true is the stream could be reused.
310 internal bool FlushInput ()
316 if (content_length > 0)
317 length = (int) Math.Min (content_length, (long) length);
319 byte [] bytes = new byte [length];
321 // TODO: test if MS has a timeout when doing this
323 IAsyncResult ares = InputStream.BeginRead (bytes, 0, length, null, null);
324 if (!ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne (1000))
326 if (InputStream.EndRead (ares) <= 0)
334 public string [] AcceptTypes {
335 get { return accept_types; }
338 public int ClientCertificateError {
340 HttpConnection cnc = context.Connection;
341 if (cnc.ClientCertificate == null)
342 throw new InvalidOperationException ("No client certificate");
343 int [] errors = cnc.ClientCertificateErrors;
344 if (errors != null && errors.Length > 0)
350 public Encoding ContentEncoding {
352 if (content_encoding == null)
353 content_encoding = Encoding.Default;
354 return content_encoding;
358 public long ContentLength64 {
359 get { return content_length; }
362 public string ContentType {
363 get { return headers ["content-type"]; }
366 public CookieCollection Cookies {
368 // TODO: check if the collection is read-only
370 cookies = new CookieCollection ();
375 public bool HasEntityBody {
376 get { return (content_length > 0 || is_chunked); }
379 public NameValueCollection Headers {
380 get { return headers; }
383 public string HttpMethod {
384 get { return method; }
387 public Stream InputStream {
389 if (input_stream == null) {
390 if (is_chunked || content_length > 0)
391 input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
393 input_stream = Stream.Null;
400 [MonoTODO ("Always returns false")]
401 public bool IsAuthenticated {
402 get { return false; }
405 public bool IsLocal {
406 get { return IPAddress.IsLoopback (RemoteEndPoint.Address); }
409 public bool IsSecureConnection {
410 get { return context.Connection.IsSecure; }
413 public bool KeepAlive {
419 // 1. Connection header
420 // 2. Protocol (1.1 == keep-alive by default)
421 // 3. Keep-Alive header
422 string cnc = headers ["Connection"];
423 if (!String.IsNullOrEmpty (cnc)) {
424 keep_alive = (0 == String.Compare (cnc, "keep-alive", StringComparison.OrdinalIgnoreCase));
425 } else if (version == HttpVersion.Version11) {
428 cnc = headers ["keep-alive"];
429 if (!String.IsNullOrEmpty (cnc))
430 keep_alive = (0 != String.Compare (cnc, "closed", StringComparison.OrdinalIgnoreCase));
436 public IPEndPoint LocalEndPoint {
437 get { return context.Connection.LocalEndPoint; }
440 public Version ProtocolVersion {
441 get { return version; }
444 public NameValueCollection QueryString {
445 get { return query_string; }
448 public string RawUrl {
449 get { return raw_url; }
452 public IPEndPoint RemoteEndPoint {
453 get { return context.Connection.RemoteEndPoint; }
456 [MonoTODO ("Always returns Guid.Empty")]
457 public Guid RequestTraceIdentifier {
458 get { return Guid.Empty; }
465 public Uri UrlReferrer {
466 get { return referrer; }
469 public string UserAgent {
470 get { return headers ["user-agent"]; }
473 public string UserHostAddress {
474 get { return LocalEndPoint.ToString (); }
477 public string UserHostName {
478 get { return headers ["host"]; }
481 public string [] UserLanguages {
482 get { return user_languages; }
485 public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, object state)
487 if (gcc_delegate == null)
488 gcc_delegate = new GCCDelegate (GetClientCertificate);
489 return gcc_delegate.BeginInvoke (requestCallback, state);
492 public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
494 if (asyncResult == null)
495 throw new ArgumentNullException ("asyncResult");
497 if (gcc_delegate == null)
498 throw new InvalidOperationException ();
500 return gcc_delegate.EndInvoke (asyncResult);
503 public X509Certificate2 GetClientCertificate ()
505 return context.Connection.ClientCertificate;
510 public string ServiceName {
516 public TransportContext TransportContext {
518 return new Context ();
525 public bool IsWebSocketRequest {
531 public Task<X509Certificate2> GetClientCertificateAsync ()
533 return Task<X509Certificate2>.Factory.FromAsync (BeginGetClientCertificate, EndGetClientCertificate, null);