2 // System.Net.HttpListenerRequest
5 // Gonzalo Paniagua Javier (gonzalo@novell.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
9 // Copyright 2011 Xamarin Inc.
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.Threading.Tasks;
41 using System.Security.Authentication.ExtendedProtection;
44 namespace System.Net {
45 public sealed class HttpListenerRequest
48 class Context : TransportContext
50 public override ChannelBinding GetChannelBinding (ChannelBindingKind kind)
52 throw new NotImplementedException ();
57 string [] accept_types;
58 // int client_cert_error;
59 // bool no_get_certificate;
60 Encoding content_encoding;
63 CookieCollection cookies;
64 WebHeaderCollection headers;
68 NameValueCollection query_string; // check if null is ok, check if read-only, check case-sensitiveness
72 string [] user_languages;
73 HttpListenerContext context;
77 static byte [] _100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n");
79 internal HttpListenerRequest (HttpListenerContext context)
81 this.context = context;
82 headers = new WebHeaderCollection ();
83 version = HttpVersion.Version10;
86 static char [] separators = new char [] { ' ' };
88 internal void SetRequestLine (string req)
90 string [] parts = req.Split (separators, 3);
91 if (parts.Length != 3) {
92 context.ErrorMessage = "Invalid request line (parts).";
97 foreach (char c in method){
100 if ((ic >= 'A' && ic <= 'Z') ||
101 (ic > 32 && c < 127 && c != '(' && c != ')' && c != '<' &&
102 c != '<' && c != '>' && c != '@' && c != ',' && c != ';' &&
103 c != ':' && c != '\\' && c != '"' && c != '/' && c != '[' &&
104 c != ']' && c != '?' && c != '=' && c != '{' && c != '}'))
107 context.ErrorMessage = "(Invalid verb)";
112 if (parts [2].Length != 8 || !parts [2].StartsWith ("HTTP/")) {
113 context.ErrorMessage = "Invalid request line (version).";
118 version = new Version (parts [2].Substring (5));
119 if (version.Major < 1)
120 throw new Exception ();
122 context.ErrorMessage = "Invalid request line (version).";
127 void CreateQueryString (string query)
129 if (query == null || query.Length == 0) {
130 query_string = new NameValueCollection (1);
134 query_string = new NameValueCollection ();
135 if (query [0] == '?')
136 query = query.Substring (1);
137 string [] components = query.Split ('&');
138 foreach (string kv in components) {
139 int pos = kv.IndexOf ('=');
141 query_string.Add (null, HttpUtility.UrlDecode (kv));
143 string key = HttpUtility.UrlDecode (kv.Substring (0, pos));
144 string val = HttpUtility.UrlDecode (kv.Substring (pos + 1));
146 query_string.Add (key, val);
151 internal void FinishInitialization ()
153 string host = UserHostName;
154 if (version > HttpVersion.Version10 && (host == null || host.Length == 0)) {
155 context.ErrorMessage = "Invalid host name";
161 if (Uri.MaybeUri (raw_url) && Uri.TryCreate (raw_url, UriKind.Absolute, out raw_uri))
162 path = raw_uri.PathAndQuery;
164 path = HttpUtility.UrlDecode (raw_url);
166 if ((host == null || host.Length == 0))
167 host = UserHostAddress;
172 int colon = host.IndexOf (':');
174 host = host.Substring (0, colon);
176 string base_uri = String.Format ("{0}://{1}:{2}",
177 (IsSecureConnection) ? "https" : "http",
178 host, LocalEndPoint.Port);
180 if (!Uri.TryCreate (base_uri + path, UriKind.Absolute, out url)){
181 context.ErrorMessage = "Invalid url: " + base_uri + path;
185 CreateQueryString (url.Query);
187 if (version >= HttpVersion.Version11) {
188 string t_encoding = Headers ["Transfer-Encoding"];
189 is_chunked = (t_encoding != null && String.Compare (t_encoding, "chunked", StringComparison.OrdinalIgnoreCase) == 0);
190 // 'identity' is not valid!
191 if (t_encoding != null && !is_chunked) {
192 context.Connection.SendError (null, 501);
197 if (!is_chunked && !cl_set) {
198 if (String.Compare (method, "POST", StringComparison.OrdinalIgnoreCase) == 0 ||
199 String.Compare (method, "PUT", StringComparison.OrdinalIgnoreCase) == 0) {
200 context.Connection.SendError (null, 411);
205 if (String.Compare (Headers ["Expect"], "100-continue", StringComparison.OrdinalIgnoreCase) == 0) {
206 ResponseStream output = context.Connection.GetResponseStream ();
207 output.InternalWrite (_100continue, 0, _100continue.Length);
211 internal static string Unquote (String str) {
212 int start = str.IndexOf ('\"');
213 int end = str.LastIndexOf ('\"');
214 if (start >= 0 && end >=0)
215 str = str.Substring (start + 1, end - 1);
219 internal void AddHeader (string header)
221 int colon = header.IndexOf (':');
222 if (colon == -1 || colon == 0) {
223 context.ErrorMessage = "Bad Request";
224 context.ErrorStatus = 400;
228 string name = header.Substring (0, colon).Trim ();
229 string val = header.Substring (colon + 1).Trim ();
230 string lower = name.ToLower (CultureInfo.InvariantCulture);
231 headers.SetInternal (name, val);
233 case "accept-language":
234 user_languages = val.Split (','); // yes, only split with a ','
237 accept_types = val.Split (','); // yes, only split with a ','
239 case "content-length":
241 //TODO: max. content_length?
242 content_length = Int64.Parse (val.Trim ());
243 if (content_length < 0)
244 context.ErrorMessage = "Invalid Content-Length.";
247 context.ErrorMessage = "Invalid Content-Length.";
253 referrer = new Uri (val);
255 referrer = new Uri ("http://someone.is.screwing.with.the.headers.com/");
260 cookies = new CookieCollection();
262 string[] cookieStrings = val.Split(new char[] {',', ';'});
263 Cookie current = null;
265 foreach (string cookieString in cookieStrings) {
266 string str = cookieString.Trim ();
269 if (str.StartsWith ("$Version")) {
270 version = Int32.Parse (Unquote (str.Substring (str.IndexOf ('=') + 1)));
271 } else if (str.StartsWith ("$Path")) {
273 current.Path = str.Substring (str.IndexOf ('=') + 1).Trim ();
274 } else if (str.StartsWith ("$Domain")) {
276 current.Domain = str.Substring (str.IndexOf ('=') + 1).Trim ();
277 } else if (str.StartsWith ("$Port")) {
279 current.Port = str.Substring (str.IndexOf ('=') + 1).Trim ();
281 if (current != null) {
282 cookies.Add (current);
284 current = new Cookie ();
285 int idx = str.IndexOf ('=');
287 current.Name = str.Substring (0, idx).Trim ();
288 current.Value = str.Substring (idx + 1).Trim ();
290 current.Name = str.Trim ();
291 current.Value = String.Empty;
293 current.Version = version;
296 if (current != null) {
297 cookies.Add (current);
303 // returns true is the stream could be reused.
304 internal bool FlushInput ()
310 if (content_length > 0)
311 length = (int) Math.Min (content_length, (long) length);
313 byte [] bytes = new byte [length];
315 // TODO: test if MS has a timeout when doing this
317 IAsyncResult ares = InputStream.BeginRead (bytes, 0, length, null, null);
318 if (!ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne (100))
320 if (InputStream.EndRead (ares) <= 0)
328 public string [] AcceptTypes {
329 get { return accept_types; }
332 [MonoTODO ("Always returns 0")]
333 public int ClientCertificateError {
336 if (no_get_certificate)
337 throw new InvalidOperationException (
338 "Call GetClientCertificate() before calling this method.");
339 return client_cert_error;
345 public Encoding ContentEncoding {
347 if (content_encoding == null)
348 content_encoding = Encoding.Default;
349 return content_encoding;
353 public long ContentLength64 {
354 get { return content_length; }
357 public string ContentType {
358 get { return headers ["content-type"]; }
361 public CookieCollection Cookies {
363 // TODO: check if the collection is read-only
365 cookies = new CookieCollection ();
370 public bool HasEntityBody {
371 get { return (content_length > 0 || is_chunked); }
374 public NameValueCollection Headers {
375 get { return headers; }
378 public string HttpMethod {
379 get { return method; }
382 public Stream InputStream {
384 if (input_stream == null) {
385 if (is_chunked || content_length > 0)
386 input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
388 input_stream = Stream.Null;
395 [MonoTODO ("Always returns false")]
396 public bool IsAuthenticated {
397 get { return false; }
400 public bool IsLocal {
401 get { return IPAddress.IsLoopback (RemoteEndPoint.Address); }
404 public bool IsSecureConnection {
405 get { return context.Connection.IsSecure; }
408 public bool KeepAlive {
414 // 1. Connection header
415 // 2. Protocol (1.1 == keep-alive by default)
416 // 3. Keep-Alive header
417 string cnc = headers ["Connection"];
418 if (!String.IsNullOrEmpty (cnc)) {
419 keep_alive = (0 == String.Compare (cnc, "keep-alive", StringComparison.OrdinalIgnoreCase));
420 } else if (version == HttpVersion.Version11) {
423 cnc = headers ["keep-alive"];
424 if (!String.IsNullOrEmpty (cnc))
425 keep_alive = (0 != String.Compare (cnc, "closed", StringComparison.OrdinalIgnoreCase));
431 public IPEndPoint LocalEndPoint {
432 get { return context.Connection.LocalEndPoint; }
435 public Version ProtocolVersion {
436 get { return version; }
439 public NameValueCollection QueryString {
440 get { return query_string; }
443 public string RawUrl {
444 get { return raw_url; }
447 public IPEndPoint RemoteEndPoint {
448 get { return context.Connection.RemoteEndPoint; }
451 [MonoTODO ("Always returns Guid.Empty")]
452 public Guid RequestTraceIdentifier {
453 get { return Guid.Empty; }
460 public Uri UrlReferrer {
461 get { return referrer; }
464 public string UserAgent {
465 get { return headers ["user-agent"]; }
468 public string UserHostAddress {
469 get { return LocalEndPoint.ToString (); }
472 public string UserHostName {
473 get { return headers ["host"]; }
476 public string [] UserLanguages {
477 get { return user_languages; }
481 public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, object state)
483 throw new NotImplementedException ();
487 public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
489 throw new NotImplementedException ();
492 public X509Certificate2 GetClientCertificate ()
494 // set no_client_certificate once done.
496 // InvalidOp if call in progress.
502 public bool IsWebSocketRequest {
509 public string ServiceName {
515 public TransportContext TransportContext {
517 return new Context ();
521 public Task<X509Certificate2> GetClientCertificateAsync ()
523 return Task<X509Certificate2>.Factory.FromAsync (BeginGetClientCertificate, EndGetClientCertificate, null);