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 using System.Collections;
34 using System.Collections.Specialized;
35 using System.Globalization;
37 using System.Security.Cryptography.X509Certificates;
39 using System.Security.Authentication.ExtendedProtection;
40 using System.Threading.Tasks;
42 namespace System.Net {
43 public sealed class HttpListenerRequest
45 class Context : TransportContext
47 public override ChannelBinding GetChannelBinding (ChannelBindingKind kind)
49 throw new NotImplementedException ();
53 string [] accept_types;
54 Encoding content_encoding;
57 CookieCollection cookies;
58 WebHeaderCollection headers;
62 NameValueCollection query_string; // check if null is ok, check if read-only, check case-sensitiveness
66 string [] user_languages;
67 HttpListenerContext context;
71 delegate X509Certificate2 GCCDelegate ();
72 GCCDelegate gcc_delegate;
74 static byte [] _100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n");
76 internal HttpListenerRequest (HttpListenerContext context)
78 this.context = context;
79 headers = new WebHeaderCollection ();
80 version = HttpVersion.Version10;
83 static char [] separators = new char [] { ' ' };
85 internal void SetRequestLine (string req)
87 string [] parts = req.Split (separators, 3);
88 if (parts.Length != 3) {
89 context.ErrorMessage = "Invalid request line (parts).";
94 foreach (char c in method){
97 if ((ic >= 'A' && ic <= 'Z') ||
98 (ic > 32 && c < 127 && c != '(' && c != ')' && c != '<' &&
99 c != '<' && c != '>' && c != '@' && c != ',' && c != ';' &&
100 c != ':' && c != '\\' && c != '"' && c != '/' && c != '[' &&
101 c != ']' && c != '?' && c != '=' && c != '{' && c != '}'))
104 context.ErrorMessage = "(Invalid verb)";
109 if (parts [2].Length != 8 || !parts [2].StartsWith ("HTTP/")) {
110 context.ErrorMessage = "Invalid request line (version).";
115 version = new Version (parts [2].Substring (5));
116 if (version.Major < 1)
117 throw new Exception ();
119 context.ErrorMessage = "Invalid request line (version).";
124 void CreateQueryString (string query)
126 if (query == null || query.Length == 0) {
127 query_string = new NameValueCollection (1);
131 query_string = new NameValueCollection ();
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, WebUtility.UrlDecode (kv));
140 string key = WebUtility.UrlDecode (kv.Substring (0, pos));
141 string val = WebUtility.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.Length == 0)) {
152 context.ErrorMessage = "Invalid host name";
158 if (Uri.MaybeUri (raw_url.ToLowerInvariant ()) && Uri.TryCreate (raw_url, UriKind.Absolute, out raw_uri))
159 path = raw_uri.PathAndQuery;
163 if ((host == null || host.Length == 0))
164 host = UserHostAddress;
169 int colon = host.IndexOf (':');
171 host = host.Substring (0, colon);
173 string base_uri = String.Format ("{0}://{1}:{2}",
174 (IsSecureConnection) ? "https" : "http",
175 host, LocalEndPoint.Port);
177 if (!Uri.TryCreate (base_uri + path, UriKind.Absolute, out url)){
178 context.ErrorMessage = "Invalid url: " + base_uri + path;
182 CreateQueryString (url.Query);
184 // Use reference source HttpListenerRequestUriBuilder to process url.
186 url = HttpListenerRequestUriBuilder.GetRequestUri (raw_url, url.Scheme,
187 url.Authority, url.LocalPath, url.Query);
189 if (version >= HttpVersion.Version11) {
190 string t_encoding = Headers ["Transfer-Encoding"];
191 is_chunked = (t_encoding != null && String.Compare (t_encoding, "chunked", StringComparison.OrdinalIgnoreCase) == 0);
192 // 'identity' is not valid!
193 if (t_encoding != null && !is_chunked) {
194 context.Connection.SendError (null, 501);
199 if (!is_chunked && !cl_set) {
200 if (String.Compare (method, "POST", StringComparison.OrdinalIgnoreCase) == 0 ||
201 String.Compare (method, "PUT", StringComparison.OrdinalIgnoreCase) == 0) {
202 context.Connection.SendError (null, 411);
207 if (String.Compare (Headers ["Expect"], "100-continue", StringComparison.OrdinalIgnoreCase) == 0) {
208 ResponseStream output = context.Connection.GetResponseStream ();
209 output.InternalWrite (_100continue, 0, _100continue.Length);
213 internal static string Unquote (String str) {
214 int start = str.IndexOf ('\"');
215 int end = str.LastIndexOf ('\"');
216 if (start >= 0 && end >=0)
217 str = str.Substring (start + 1, end - 1);
221 internal void AddHeader (string header)
223 int colon = header.IndexOf (':');
224 if (colon == -1 || colon == 0) {
225 context.ErrorMessage = "Bad Request";
226 context.ErrorStatus = 400;
230 string name = header.Substring (0, colon).Trim ();
231 string val = header.Substring (colon + 1).Trim ();
232 string lower = name.ToLower (CultureInfo.InvariantCulture);
233 headers.SetInternal (name, val);
235 case "accept-language":
236 user_languages = val.Split (','); // yes, only split with a ','
239 accept_types = val.Split (','); // yes, only split with a ','
241 case "content-length":
243 //TODO: max. content_length?
244 content_length = Int64.Parse (val.Trim ());
245 if (content_length < 0)
246 context.ErrorMessage = "Invalid Content-Length.";
249 context.ErrorMessage = "Invalid Content-Length.";
255 referrer = new Uri (val);
257 referrer = new Uri ("http://someone.is.screwing.with.the.headers.com/");
262 cookies = new CookieCollection();
264 string[] cookieStrings = val.Split(new char[] {',', ';'});
265 Cookie current = null;
267 foreach (string cookieString in cookieStrings) {
268 string str = cookieString.Trim ();
271 if (str.StartsWith ("$Version")) {
272 version = Int32.Parse (Unquote (str.Substring (str.IndexOf ('=') + 1)));
273 } else if (str.StartsWith ("$Path")) {
275 current.Path = str.Substring (str.IndexOf ('=') + 1).Trim ();
276 } else if (str.StartsWith ("$Domain")) {
278 current.Domain = str.Substring (str.IndexOf ('=') + 1).Trim ();
279 } else if (str.StartsWith ("$Port")) {
281 current.Port = str.Substring (str.IndexOf ('=') + 1).Trim ();
283 if (current != null) {
284 cookies.Add (current);
286 current = new Cookie ();
287 int idx = str.IndexOf ('=');
289 current.Name = str.Substring (0, idx).Trim ();
290 current.Value = str.Substring (idx + 1).Trim ();
292 current.Name = str.Trim ();
293 current.Value = String.Empty;
295 current.Version = version;
298 if (current != null) {
299 cookies.Add (current);
305 // returns true is the stream could be reused.
306 internal bool FlushInput ()
312 if (content_length > 0)
313 length = (int) Math.Min (content_length, (long) length);
315 byte [] bytes = new byte [length];
317 // TODO: test if MS has a timeout when doing this
319 IAsyncResult ares = InputStream.BeginRead (bytes, 0, length, null, null);
320 if (!ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne (1000))
322 if (InputStream.EndRead (ares) <= 0)
324 } catch (ObjectDisposedException e) {
333 public string [] AcceptTypes {
334 get { return accept_types; }
337 public int ClientCertificateError {
339 HttpConnection cnc = context.Connection;
340 if (cnc.ClientCertificate == null)
341 throw new InvalidOperationException ("No client certificate");
342 int [] errors = cnc.ClientCertificateErrors;
343 if (errors != null && errors.Length > 0)
349 public Encoding ContentEncoding {
351 if (content_encoding == null)
352 content_encoding = Encoding.Default;
353 return content_encoding;
357 public long ContentLength64 {
358 get { return content_length; }
361 public string ContentType {
362 get { return headers ["content-type"]; }
365 public CookieCollection Cookies {
367 // TODO: check if the collection is read-only
369 cookies = new CookieCollection ();
374 public bool HasEntityBody {
375 get { return (content_length > 0 || is_chunked); }
378 public NameValueCollection Headers {
379 get { return headers; }
382 public string HttpMethod {
383 get { return method; }
386 public Stream InputStream {
388 if (input_stream == null) {
389 if (is_chunked || content_length > 0)
390 input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
392 input_stream = Stream.Null;
399 [MonoTODO ("Always returns false")]
400 public bool IsAuthenticated {
401 get { return false; }
404 public bool IsLocal {
405 get { return IPAddress.IsLoopback (RemoteEndPoint.Address); }
408 public bool IsSecureConnection {
409 get { return context.Connection.IsSecure; }
412 public bool KeepAlive {
418 // 1. Connection header
419 // 2. Protocol (1.1 == keep-alive by default)
420 // 3. Keep-Alive header
421 string cnc = headers ["Connection"];
422 if (!String.IsNullOrEmpty (cnc)) {
423 keep_alive = (0 == String.Compare (cnc, "keep-alive", StringComparison.OrdinalIgnoreCase));
424 } else if (version == HttpVersion.Version11) {
427 cnc = headers ["keep-alive"];
428 if (!String.IsNullOrEmpty (cnc))
429 keep_alive = (0 != String.Compare (cnc, "closed", StringComparison.OrdinalIgnoreCase));
435 public IPEndPoint LocalEndPoint {
436 get { return context.Connection.LocalEndPoint; }
439 public Version ProtocolVersion {
440 get { return version; }
443 public NameValueCollection QueryString {
444 get { return query_string; }
447 public string RawUrl {
448 get { return raw_url; }
451 public IPEndPoint RemoteEndPoint {
452 get { return context.Connection.RemoteEndPoint; }
455 [MonoTODO ("Always returns Guid.Empty")]
456 public Guid RequestTraceIdentifier {
457 get { return Guid.Empty; }
464 public Uri UrlReferrer {
465 get { return referrer; }
468 public string UserAgent {
469 get { return headers ["user-agent"]; }
472 public string UserHostAddress {
473 get { return LocalEndPoint.ToString (); }
476 public string UserHostName {
477 get { return headers ["host"]; }
480 public string [] UserLanguages {
481 get { return user_languages; }
484 public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, object state)
486 if (gcc_delegate == null)
487 gcc_delegate = new GCCDelegate (GetClientCertificate);
488 return gcc_delegate.BeginInvoke (requestCallback, state);
491 public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
493 if (asyncResult == null)
494 throw new ArgumentNullException ("asyncResult");
496 if (gcc_delegate == null)
497 throw new InvalidOperationException ();
499 return gcc_delegate.EndInvoke (asyncResult);
502 public X509Certificate2 GetClientCertificate ()
504 return context.Connection.ClientCertificate;
508 public string ServiceName {
514 public TransportContext TransportContext {
516 return new Context ();
521 public bool IsWebSocketRequest {
527 public Task<X509Certificate2> GetClientCertificateAsync ()
529 return Task<X509Certificate2>.Factory.FromAsync (BeginGetClientCertificate, EndGetClientCertificate, null);