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;
40 using System.Security.Authentication.ExtendedProtection;
43 using System.Threading.Tasks;
45 using Mono.Security.Protocol.Tls;
47 namespace System.Net {
48 public sealed class HttpListenerRequest
51 class Context : TransportContext
53 public override ChannelBinding GetChannelBinding (ChannelBindingKind kind)
55 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) && 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 if (version >= HttpVersion.Version11) {
192 string t_encoding = Headers ["Transfer-Encoding"];
193 is_chunked = (t_encoding != null && String.Compare (t_encoding, "chunked", StringComparison.OrdinalIgnoreCase) == 0);
194 // 'identity' is not valid!
195 if (t_encoding != null && !is_chunked) {
196 context.Connection.SendError (null, 501);
201 if (!is_chunked && !cl_set) {
202 if (String.Compare (method, "POST", StringComparison.OrdinalIgnoreCase) == 0 ||
203 String.Compare (method, "PUT", StringComparison.OrdinalIgnoreCase) == 0) {
204 context.Connection.SendError (null, 411);
209 if (String.Compare (Headers ["Expect"], "100-continue", StringComparison.OrdinalIgnoreCase) == 0) {
210 ResponseStream output = context.Connection.GetResponseStream ();
211 output.InternalWrite (_100continue, 0, _100continue.Length);
215 internal static string Unquote (String str) {
216 int start = str.IndexOf ('\"');
217 int end = str.LastIndexOf ('\"');
218 if (start >= 0 && end >=0)
219 str = str.Substring (start + 1, end - 1);
223 internal void AddHeader (string header)
225 int colon = header.IndexOf (':');
226 if (colon == -1 || colon == 0) {
227 context.ErrorMessage = "Bad Request";
228 context.ErrorStatus = 400;
232 string name = header.Substring (0, colon).Trim ();
233 string val = header.Substring (colon + 1).Trim ();
234 string lower = name.ToLower (CultureInfo.InvariantCulture);
235 headers.SetInternal (name, val);
237 case "accept-language":
238 user_languages = val.Split (','); // yes, only split with a ','
241 accept_types = val.Split (','); // yes, only split with a ','
243 case "content-length":
245 //TODO: max. content_length?
246 content_length = Int64.Parse (val.Trim ());
247 if (content_length < 0)
248 context.ErrorMessage = "Invalid Content-Length.";
251 context.ErrorMessage = "Invalid Content-Length.";
257 referrer = new Uri (val);
259 referrer = new Uri ("http://someone.is.screwing.with.the.headers.com/");
264 cookies = new CookieCollection();
266 string[] cookieStrings = val.Split(new char[] {',', ';'});
267 Cookie current = null;
269 foreach (string cookieString in cookieStrings) {
270 string str = cookieString.Trim ();
273 if (str.StartsWith ("$Version")) {
274 version = Int32.Parse (Unquote (str.Substring (str.IndexOf ('=') + 1)));
275 } else if (str.StartsWith ("$Path")) {
277 current.Path = str.Substring (str.IndexOf ('=') + 1).Trim ();
278 } else if (str.StartsWith ("$Domain")) {
280 current.Domain = str.Substring (str.IndexOf ('=') + 1).Trim ();
281 } else if (str.StartsWith ("$Port")) {
283 current.Port = str.Substring (str.IndexOf ('=') + 1).Trim ();
285 if (current != null) {
286 cookies.Add (current);
288 current = new Cookie ();
289 int idx = str.IndexOf ('=');
291 current.Name = str.Substring (0, idx).Trim ();
292 current.Value = str.Substring (idx + 1).Trim ();
294 current.Name = str.Trim ();
295 current.Value = String.Empty;
297 current.Version = version;
300 if (current != null) {
301 cookies.Add (current);
307 // returns true is the stream could be reused.
308 internal bool FlushInput ()
314 if (content_length > 0)
315 length = (int) Math.Min (content_length, (long) length);
317 byte [] bytes = new byte [length];
319 // TODO: test if MS has a timeout when doing this
321 IAsyncResult ares = InputStream.BeginRead (bytes, 0, length, null, null);
322 if (!ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne (100))
324 if (InputStream.EndRead (ares) <= 0)
332 public string [] AcceptTypes {
333 get { return accept_types; }
336 public int ClientCertificateError {
338 HttpConnection cnc = context.Connection;
339 if (cnc.ClientCertificate == null)
340 throw new InvalidOperationException ("No client certificate");
341 int [] errors = cnc.ClientCertificateErrors;
342 if (errors != null && errors.Length > 0)
348 public Encoding ContentEncoding {
350 if (content_encoding == null)
351 content_encoding = Encoding.Default;
352 return content_encoding;
356 public long ContentLength64 {
357 get { return content_length; }
360 public string ContentType {
361 get { return headers ["content-type"]; }
364 public CookieCollection Cookies {
366 // TODO: check if the collection is read-only
368 cookies = new CookieCollection ();
373 public bool HasEntityBody {
374 get { return (content_length > 0 || is_chunked); }
377 public NameValueCollection Headers {
378 get { return headers; }
381 public string HttpMethod {
382 get { return method; }
385 public Stream InputStream {
387 if (input_stream == null) {
388 if (is_chunked || content_length > 0)
389 input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
391 input_stream = Stream.Null;
398 [MonoTODO ("Always returns false")]
399 public bool IsAuthenticated {
400 get { return false; }
403 public bool IsLocal {
404 get { return IPAddress.IsLoopback (RemoteEndPoint.Address); }
407 public bool IsSecureConnection {
408 get { return context.Connection.IsSecure; }
411 public bool KeepAlive {
417 // 1. Connection header
418 // 2. Protocol (1.1 == keep-alive by default)
419 // 3. Keep-Alive header
420 string cnc = headers ["Connection"];
421 if (!String.IsNullOrEmpty (cnc)) {
422 keep_alive = (0 == String.Compare (cnc, "keep-alive", StringComparison.OrdinalIgnoreCase));
423 } else if (version == HttpVersion.Version11) {
426 cnc = headers ["keep-alive"];
427 if (!String.IsNullOrEmpty (cnc))
428 keep_alive = (0 != String.Compare (cnc, "closed", StringComparison.OrdinalIgnoreCase));
434 public IPEndPoint LocalEndPoint {
435 get { return context.Connection.LocalEndPoint; }
438 public Version ProtocolVersion {
439 get { return version; }
442 public NameValueCollection QueryString {
443 get { return query_string; }
446 public string RawUrl {
447 get { return raw_url; }
450 public IPEndPoint RemoteEndPoint {
451 get { return context.Connection.RemoteEndPoint; }
454 [MonoTODO ("Always returns Guid.Empty")]
455 public Guid RequestTraceIdentifier {
456 get { return Guid.Empty; }
463 public Uri UrlReferrer {
464 get { return referrer; }
467 public string UserAgent {
468 get { return headers ["user-agent"]; }
471 public string UserHostAddress {
472 get { return LocalEndPoint.ToString (); }
475 public string UserHostName {
476 get { return headers ["host"]; }
479 public string [] UserLanguages {
480 get { return user_languages; }
483 public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, object state)
485 if (gcc_delegate == null)
486 gcc_delegate = new GCCDelegate (GetClientCertificate);
487 return gcc_delegate.BeginInvoke (requestCallback, state);
490 public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
492 if (asyncResult == null)
493 throw new ArgumentNullException ("asyncResult");
495 if (gcc_delegate == null)
496 throw new InvalidOperationException ();
498 return gcc_delegate.EndInvoke (asyncResult);
501 public X509Certificate2 GetClientCertificate ()
503 return context.Connection.ClientCertificate;
508 public string ServiceName {
514 public TransportContext TransportContext {
516 return new Context ();
523 public bool IsWebSocketRequest {
529 public Task<X509Certificate2> GetClientCertificateAsync ()
531 return Task<X509Certificate2>.Factory.FromAsync (BeginGetClientCertificate, EndGetClientCertificate, null);