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;
47 using System.Security.Authentication.ExtendedProtection;
50 using System.Threading.Tasks;
53 namespace System.Net {
54 public sealed class HttpListenerRequest
57 class Context : TransportContext
59 public override ChannelBinding GetChannelBinding (ChannelBindingKind kind)
61 throw new NotImplementedException ();
66 string [] accept_types;
67 Encoding content_encoding;
70 CookieCollection cookies;
71 WebHeaderCollection headers;
75 NameValueCollection query_string; // check if null is ok, check if read-only, check case-sensitiveness
79 string [] user_languages;
80 HttpListenerContext context;
84 delegate X509Certificate2 GCCDelegate ();
85 GCCDelegate gcc_delegate;
87 static byte [] _100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n");
89 internal HttpListenerRequest (HttpListenerContext context)
91 this.context = context;
92 headers = new WebHeaderCollection ();
93 version = HttpVersion.Version10;
96 static char [] separators = new char [] { ' ' };
98 internal void SetRequestLine (string req)
100 string [] parts = req.Split (separators, 3);
101 if (parts.Length != 3) {
102 context.ErrorMessage = "Invalid request line (parts).";
107 foreach (char c in method){
110 if ((ic >= 'A' && ic <= 'Z') ||
111 (ic > 32 && c < 127 && c != '(' && c != ')' && c != '<' &&
112 c != '<' && c != '>' && c != '@' && c != ',' && c != ';' &&
113 c != ':' && c != '\\' && c != '"' && c != '/' && c != '[' &&
114 c != ']' && c != '?' && c != '=' && c != '{' && c != '}'))
117 context.ErrorMessage = "(Invalid verb)";
122 if (parts [2].Length != 8 || !parts [2].StartsWith ("HTTP/")) {
123 context.ErrorMessage = "Invalid request line (version).";
128 version = new Version (parts [2].Substring (5));
129 if (version.Major < 1)
130 throw new Exception ();
132 context.ErrorMessage = "Invalid request line (version).";
137 void CreateQueryString (string query)
139 if (query == null || query.Length == 0) {
140 query_string = new NameValueCollection (1);
144 query_string = new NameValueCollection ();
145 if (query [0] == '?')
146 query = query.Substring (1);
147 string [] components = query.Split ('&');
148 foreach (string kv in components) {
149 int pos = kv.IndexOf ('=');
151 query_string.Add (null, HttpUtility.UrlDecode (kv));
153 string key = HttpUtility.UrlDecode (kv.Substring (0, pos));
154 string val = HttpUtility.UrlDecode (kv.Substring (pos + 1));
156 query_string.Add (key, val);
161 internal void FinishInitialization ()
163 string host = UserHostName;
164 if (version > HttpVersion.Version10 && (host == null || host.Length == 0)) {
165 context.ErrorMessage = "Invalid host name";
171 if (Uri.MaybeUri (raw_url) && Uri.TryCreate (raw_url, UriKind.Absolute, out raw_uri))
172 path = raw_uri.PathAndQuery;
176 if ((host == null || host.Length == 0))
177 host = UserHostAddress;
182 int colon = host.IndexOf (':');
184 host = host.Substring (0, colon);
186 string base_uri = String.Format ("{0}://{1}:{2}",
187 (IsSecureConnection) ? "https" : "http",
188 host, LocalEndPoint.Port);
190 if (!Uri.TryCreate (base_uri + path, UriKind.Absolute, out url)){
191 context.ErrorMessage = "Invalid url: " + base_uri + path;
195 CreateQueryString (url.Query);
197 if (version >= HttpVersion.Version11) {
198 string t_encoding = Headers ["Transfer-Encoding"];
199 is_chunked = (t_encoding != null && String.Compare (t_encoding, "chunked", StringComparison.OrdinalIgnoreCase) == 0);
200 // 'identity' is not valid!
201 if (t_encoding != null && !is_chunked) {
202 context.Connection.SendError (null, 501);
207 if (!is_chunked && !cl_set) {
208 if (String.Compare (method, "POST", StringComparison.OrdinalIgnoreCase) == 0 ||
209 String.Compare (method, "PUT", StringComparison.OrdinalIgnoreCase) == 0) {
210 context.Connection.SendError (null, 411);
215 if (String.Compare (Headers ["Expect"], "100-continue", StringComparison.OrdinalIgnoreCase) == 0) {
216 ResponseStream output = context.Connection.GetResponseStream ();
217 output.InternalWrite (_100continue, 0, _100continue.Length);
221 internal static string Unquote (String str) {
222 int start = str.IndexOf ('\"');
223 int end = str.LastIndexOf ('\"');
224 if (start >= 0 && end >=0)
225 str = str.Substring (start + 1, end - 1);
229 internal void AddHeader (string header)
231 int colon = header.IndexOf (':');
232 if (colon == -1 || colon == 0) {
233 context.ErrorMessage = "Bad Request";
234 context.ErrorStatus = 400;
238 string name = header.Substring (0, colon).Trim ();
239 string val = header.Substring (colon + 1).Trim ();
240 string lower = name.ToLower (CultureInfo.InvariantCulture);
241 headers.SetInternal (name, val);
243 case "accept-language":
244 user_languages = val.Split (','); // yes, only split with a ','
247 accept_types = val.Split (','); // yes, only split with a ','
249 case "content-length":
251 //TODO: max. content_length?
252 content_length = Int64.Parse (val.Trim ());
253 if (content_length < 0)
254 context.ErrorMessage = "Invalid Content-Length.";
257 context.ErrorMessage = "Invalid Content-Length.";
263 referrer = new Uri (val);
265 referrer = new Uri ("http://someone.is.screwing.with.the.headers.com/");
270 cookies = new CookieCollection();
272 string[] cookieStrings = val.Split(new char[] {',', ';'});
273 Cookie current = null;
275 foreach (string cookieString in cookieStrings) {
276 string str = cookieString.Trim ();
279 if (str.StartsWith ("$Version")) {
280 version = Int32.Parse (Unquote (str.Substring (str.IndexOf ('=') + 1)));
281 } else if (str.StartsWith ("$Path")) {
283 current.Path = str.Substring (str.IndexOf ('=') + 1).Trim ();
284 } else if (str.StartsWith ("$Domain")) {
286 current.Domain = str.Substring (str.IndexOf ('=') + 1).Trim ();
287 } else if (str.StartsWith ("$Port")) {
289 current.Port = str.Substring (str.IndexOf ('=') + 1).Trim ();
291 if (current != null) {
292 cookies.Add (current);
294 current = new Cookie ();
295 int idx = str.IndexOf ('=');
297 current.Name = str.Substring (0, idx).Trim ();
298 current.Value = str.Substring (idx + 1).Trim ();
300 current.Name = str.Trim ();
301 current.Value = String.Empty;
303 current.Version = version;
306 if (current != null) {
307 cookies.Add (current);
313 // returns true is the stream could be reused.
314 internal bool FlushInput ()
320 if (content_length > 0)
321 length = (int) Math.Min (content_length, (long) length);
323 byte [] bytes = new byte [length];
325 // TODO: test if MS has a timeout when doing this
327 IAsyncResult ares = InputStream.BeginRead (bytes, 0, length, null, null);
328 if (!ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne (1000))
330 if (InputStream.EndRead (ares) <= 0)
332 } catch (ObjectDisposedException e) {
341 public string [] AcceptTypes {
342 get { return accept_types; }
345 public int ClientCertificateError {
347 HttpConnection cnc = context.Connection;
348 if (cnc.ClientCertificate == null)
349 throw new InvalidOperationException ("No client certificate");
350 int [] errors = cnc.ClientCertificateErrors;
351 if (errors != null && errors.Length > 0)
357 public Encoding ContentEncoding {
359 if (content_encoding == null)
360 content_encoding = Encoding.Default;
361 return content_encoding;
365 public long ContentLength64 {
366 get { return content_length; }
369 public string ContentType {
370 get { return headers ["content-type"]; }
373 public CookieCollection Cookies {
375 // TODO: check if the collection is read-only
377 cookies = new CookieCollection ();
382 public bool HasEntityBody {
383 get { return (content_length > 0 || is_chunked); }
386 public NameValueCollection Headers {
387 get { return headers; }
390 public string HttpMethod {
391 get { return method; }
394 public Stream InputStream {
396 if (input_stream == null) {
397 if (is_chunked || content_length > 0)
398 input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
400 input_stream = Stream.Null;
407 [MonoTODO ("Always returns false")]
408 public bool IsAuthenticated {
409 get { return false; }
412 public bool IsLocal {
413 get { return IPAddress.IsLoopback (RemoteEndPoint.Address); }
416 public bool IsSecureConnection {
417 get { return context.Connection.IsSecure; }
420 public bool KeepAlive {
426 // 1. Connection header
427 // 2. Protocol (1.1 == keep-alive by default)
428 // 3. Keep-Alive header
429 string cnc = headers ["Connection"];
430 if (!String.IsNullOrEmpty (cnc)) {
431 keep_alive = (0 == String.Compare (cnc, "keep-alive", StringComparison.OrdinalIgnoreCase));
432 } else if (version == HttpVersion.Version11) {
435 cnc = headers ["keep-alive"];
436 if (!String.IsNullOrEmpty (cnc))
437 keep_alive = (0 != String.Compare (cnc, "closed", StringComparison.OrdinalIgnoreCase));
443 public IPEndPoint LocalEndPoint {
444 get { return context.Connection.LocalEndPoint; }
447 public Version ProtocolVersion {
448 get { return version; }
451 public NameValueCollection QueryString {
452 get { return query_string; }
455 public string RawUrl {
456 get { return raw_url; }
459 public IPEndPoint RemoteEndPoint {
460 get { return context.Connection.RemoteEndPoint; }
463 [MonoTODO ("Always returns Guid.Empty")]
464 public Guid RequestTraceIdentifier {
465 get { return Guid.Empty; }
472 public Uri UrlReferrer {
473 get { return referrer; }
476 public string UserAgent {
477 get { return headers ["user-agent"]; }
480 public string UserHostAddress {
481 get { return LocalEndPoint.ToString (); }
484 public string UserHostName {
485 get { return headers ["host"]; }
488 public string [] UserLanguages {
489 get { return user_languages; }
492 public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, object state)
494 if (gcc_delegate == null)
495 gcc_delegate = new GCCDelegate (GetClientCertificate);
496 return gcc_delegate.BeginInvoke (requestCallback, state);
499 public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
501 if (asyncResult == null)
502 throw new ArgumentNullException ("asyncResult");
504 if (gcc_delegate == null)
505 throw new InvalidOperationException ();
507 return gcc_delegate.EndInvoke (asyncResult);
510 public X509Certificate2 GetClientCertificate ()
512 return context.Connection.ClientCertificate;
517 public string ServiceName {
523 public TransportContext TransportContext {
525 return new Context ();
532 public bool IsWebSocketRequest {
538 public Task<X509Certificate2> GetClientCertificateAsync ()
540 return Task<X509Certificate2>.Factory.FromAsync (BeginGetClientCertificate, EndGetClientCertificate, null);