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 #if MONOTOUCH || MONODROID
34 using Mono.Security.Protocol.Tls;
36 extern alias MonoSecurity;
37 using MonoSecurity::Mono.Security.Protocol.Tls;
40 using System.Collections;
41 using System.Collections.Specialized;
42 using System.Globalization;
44 using System.Security.Cryptography.X509Certificates;
46 using System.Security.Authentication.ExtendedProtection;
47 using System.Threading.Tasks;
49 namespace System.Net {
50 public sealed class HttpListenerRequest
52 class Context : TransportContext
54 public override ChannelBinding GetChannelBinding (ChannelBindingKind kind)
56 throw new NotImplementedException ();
60 string [] accept_types;
61 Encoding content_encoding;
64 CookieCollection cookies;
65 WebHeaderCollection headers;
69 NameValueCollection query_string; // check if null is ok, check if read-only, check case-sensitiveness
73 string [] user_languages;
74 HttpListenerContext context;
78 delegate X509Certificate2 GCCDelegate ();
79 GCCDelegate gcc_delegate;
81 static byte [] _100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n");
83 internal HttpListenerRequest (HttpListenerContext context)
85 this.context = context;
86 headers = new WebHeaderCollection ();
87 version = HttpVersion.Version10;
90 static char [] separators = new char [] { ' ' };
92 internal void SetRequestLine (string req)
94 string [] parts = req.Split (separators, 3);
95 if (parts.Length != 3) {
96 context.ErrorMessage = "Invalid request line (parts).";
101 foreach (char c in method){
104 if ((ic >= 'A' && ic <= 'Z') ||
105 (ic > 32 && c < 127 && c != '(' && c != ')' && c != '<' &&
106 c != '<' && c != '>' && c != '@' && c != ',' && c != ';' &&
107 c != ':' && c != '\\' && c != '"' && c != '/' && c != '[' &&
108 c != ']' && c != '?' && c != '=' && c != '{' && c != '}'))
111 context.ErrorMessage = "(Invalid verb)";
116 if (parts [2].Length != 8 || !parts [2].StartsWith ("HTTP/")) {
117 context.ErrorMessage = "Invalid request line (version).";
122 version = new Version (parts [2].Substring (5));
123 if (version.Major < 1)
124 throw new Exception ();
126 context.ErrorMessage = "Invalid request line (version).";
131 void CreateQueryString (string query)
133 if (query == null || query.Length == 0) {
134 query_string = new NameValueCollection (1);
138 query_string = new NameValueCollection ();
139 if (query [0] == '?')
140 query = query.Substring (1);
141 string [] components = query.Split ('&');
142 foreach (string kv in components) {
143 int pos = kv.IndexOf ('=');
145 query_string.Add (null, HttpUtility.UrlDecode (kv));
147 string key = HttpUtility.UrlDecode (kv.Substring (0, pos));
148 string val = HttpUtility.UrlDecode (kv.Substring (pos + 1));
150 query_string.Add (key, val);
155 internal void FinishInitialization ()
157 string host = UserHostName;
158 if (version > HttpVersion.Version10 && (host == null || host.Length == 0)) {
159 context.ErrorMessage = "Invalid host name";
165 if (Uri.MaybeUri (raw_url.ToLowerInvariant ()) && Uri.TryCreate (raw_url, UriKind.Absolute, out raw_uri))
166 path = raw_uri.PathAndQuery;
170 if ((host == null || host.Length == 0))
171 host = UserHostAddress;
176 int colon = host.IndexOf (':');
178 host = host.Substring (0, colon);
180 string base_uri = String.Format ("{0}://{1}:{2}",
181 (IsSecureConnection) ? "https" : "http",
182 host, LocalEndPoint.Port);
184 if (!Uri.TryCreate (base_uri + path, UriKind.Absolute, out url)){
185 context.ErrorMessage = "Invalid url: " + base_uri + path;
189 CreateQueryString (url.Query);
191 // Use reference source HttpListenerRequestUriBuilder to process url.
193 url = HttpListenerRequestUriBuilder.GetRequestUri (raw_url, url.Scheme,
194 url.Authority, url.LocalPath, url.Query);
196 if (version >= HttpVersion.Version11) {
197 string t_encoding = Headers ["Transfer-Encoding"];
198 is_chunked = (t_encoding != null && String.Compare (t_encoding, "chunked", StringComparison.OrdinalIgnoreCase) == 0);
199 // 'identity' is not valid!
200 if (t_encoding != null && !is_chunked) {
201 context.Connection.SendError (null, 501);
206 if (!is_chunked && !cl_set) {
207 if (String.Compare (method, "POST", StringComparison.OrdinalIgnoreCase) == 0 ||
208 String.Compare (method, "PUT", StringComparison.OrdinalIgnoreCase) == 0) {
209 context.Connection.SendError (null, 411);
214 if (String.Compare (Headers ["Expect"], "100-continue", StringComparison.OrdinalIgnoreCase) == 0) {
215 ResponseStream output = context.Connection.GetResponseStream ();
216 output.InternalWrite (_100continue, 0, _100continue.Length);
220 internal static string Unquote (String str) {
221 int start = str.IndexOf ('\"');
222 int end = str.LastIndexOf ('\"');
223 if (start >= 0 && end >=0)
224 str = str.Substring (start + 1, end - 1);
228 internal void AddHeader (string header)
230 int colon = header.IndexOf (':');
231 if (colon == -1 || colon == 0) {
232 context.ErrorMessage = "Bad Request";
233 context.ErrorStatus = 400;
237 string name = header.Substring (0, colon).Trim ();
238 string val = header.Substring (colon + 1).Trim ();
239 string lower = name.ToLower (CultureInfo.InvariantCulture);
240 headers.SetInternal (name, val);
242 case "accept-language":
243 user_languages = val.Split (','); // yes, only split with a ','
246 accept_types = val.Split (','); // yes, only split with a ','
248 case "content-length":
250 //TODO: max. content_length?
251 content_length = Int64.Parse (val.Trim ());
252 if (content_length < 0)
253 context.ErrorMessage = "Invalid Content-Length.";
256 context.ErrorMessage = "Invalid Content-Length.";
262 referrer = new Uri (val);
264 referrer = new Uri ("http://someone.is.screwing.with.the.headers.com/");
269 cookies = new CookieCollection();
271 string[] cookieStrings = val.Split(new char[] {',', ';'});
272 Cookie current = null;
274 foreach (string cookieString in cookieStrings) {
275 string str = cookieString.Trim ();
278 if (str.StartsWith ("$Version")) {
279 version = Int32.Parse (Unquote (str.Substring (str.IndexOf ('=') + 1)));
280 } else if (str.StartsWith ("$Path")) {
282 current.Path = str.Substring (str.IndexOf ('=') + 1).Trim ();
283 } else if (str.StartsWith ("$Domain")) {
285 current.Domain = str.Substring (str.IndexOf ('=') + 1).Trim ();
286 } else if (str.StartsWith ("$Port")) {
288 current.Port = str.Substring (str.IndexOf ('=') + 1).Trim ();
290 if (current != null) {
291 cookies.Add (current);
293 current = new Cookie ();
294 int idx = str.IndexOf ('=');
296 current.Name = str.Substring (0, idx).Trim ();
297 current.Value = str.Substring (idx + 1).Trim ();
299 current.Name = str.Trim ();
300 current.Value = String.Empty;
302 current.Version = version;
305 if (current != null) {
306 cookies.Add (current);
312 // returns true is the stream could be reused.
313 internal bool FlushInput ()
319 if (content_length > 0)
320 length = (int) Math.Min (content_length, (long) length);
322 byte [] bytes = new byte [length];
324 // TODO: test if MS has a timeout when doing this
326 IAsyncResult ares = InputStream.BeginRead (bytes, 0, length, null, null);
327 if (!ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne (1000))
329 if (InputStream.EndRead (ares) <= 0)
331 } catch (ObjectDisposedException e) {
340 public string [] AcceptTypes {
341 get { return accept_types; }
344 public int ClientCertificateError {
346 HttpConnection cnc = context.Connection;
347 if (cnc.ClientCertificate == null)
348 throw new InvalidOperationException ("No client certificate");
349 int [] errors = cnc.ClientCertificateErrors;
350 if (errors != null && errors.Length > 0)
356 public Encoding ContentEncoding {
358 if (content_encoding == null)
359 content_encoding = Encoding.Default;
360 return content_encoding;
364 public long ContentLength64 {
365 get { return content_length; }
368 public string ContentType {
369 get { return headers ["content-type"]; }
372 public CookieCollection Cookies {
374 // TODO: check if the collection is read-only
376 cookies = new CookieCollection ();
381 public bool HasEntityBody {
382 get { return (content_length > 0 || is_chunked); }
385 public NameValueCollection Headers {
386 get { return headers; }
389 public string HttpMethod {
390 get { return method; }
393 public Stream InputStream {
395 if (input_stream == null) {
396 if (is_chunked || content_length > 0)
397 input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
399 input_stream = Stream.Null;
406 [MonoTODO ("Always returns false")]
407 public bool IsAuthenticated {
408 get { return false; }
411 public bool IsLocal {
412 get { return IPAddress.IsLoopback (RemoteEndPoint.Address); }
415 public bool IsSecureConnection {
416 get { return context.Connection.IsSecure; }
419 public bool KeepAlive {
425 // 1. Connection header
426 // 2. Protocol (1.1 == keep-alive by default)
427 // 3. Keep-Alive header
428 string cnc = headers ["Connection"];
429 if (!String.IsNullOrEmpty (cnc)) {
430 keep_alive = (0 == String.Compare (cnc, "keep-alive", StringComparison.OrdinalIgnoreCase));
431 } else if (version == HttpVersion.Version11) {
434 cnc = headers ["keep-alive"];
435 if (!String.IsNullOrEmpty (cnc))
436 keep_alive = (0 != String.Compare (cnc, "closed", StringComparison.OrdinalIgnoreCase));
442 public IPEndPoint LocalEndPoint {
443 get { return context.Connection.LocalEndPoint; }
446 public Version ProtocolVersion {
447 get { return version; }
450 public NameValueCollection QueryString {
451 get { return query_string; }
454 public string RawUrl {
455 get { return raw_url; }
458 public IPEndPoint RemoteEndPoint {
459 get { return context.Connection.RemoteEndPoint; }
462 [MonoTODO ("Always returns Guid.Empty")]
463 public Guid RequestTraceIdentifier {
464 get { return Guid.Empty; }
471 public Uri UrlReferrer {
472 get { return referrer; }
475 public string UserAgent {
476 get { return headers ["user-agent"]; }
479 public string UserHostAddress {
480 get { return LocalEndPoint.ToString (); }
483 public string UserHostName {
484 get { return headers ["host"]; }
487 public string [] UserLanguages {
488 get { return user_languages; }
491 public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, object state)
493 if (gcc_delegate == null)
494 gcc_delegate = new GCCDelegate (GetClientCertificate);
495 return gcc_delegate.BeginInvoke (requestCallback, state);
498 public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
500 if (asyncResult == null)
501 throw new ArgumentNullException ("asyncResult");
503 if (gcc_delegate == null)
504 throw new InvalidOperationException ();
506 return gcc_delegate.EndInvoke (asyncResult);
509 public X509Certificate2 GetClientCertificate ()
511 return context.Connection.ClientCertificate;
515 public string ServiceName {
521 public TransportContext TransportContext {
523 return new Context ();
528 public bool IsWebSocketRequest {
534 public Task<X509Certificate2> GetClientCertificateAsync ()
536 return Task<X509Certificate2>.Factory.FromAsync (BeginGetClientCertificate, EndGetClientCertificate, null);