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;
43 namespace System.Net {
44 public sealed class HttpListenerRequest
46 string [] accept_types;
47 // int client_cert_error;
48 // bool no_get_certificate;
49 Encoding content_encoding;
52 CookieCollection cookies;
53 WebHeaderCollection headers;
57 NameValueCollection query_string; // check if null is ok, check if read-only, check case-sensitiveness
61 string [] user_languages;
62 HttpListenerContext context;
66 static byte [] _100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n");
68 internal HttpListenerRequest (HttpListenerContext context)
70 this.context = context;
71 headers = new WebHeaderCollection ();
72 version = HttpVersion.Version10;
75 static char [] separators = new char [] { ' ' };
77 internal void SetRequestLine (string req)
79 string [] parts = req.Split (separators, 3);
80 if (parts.Length != 3) {
81 context.ErrorMessage = "Invalid request line (parts).";
86 foreach (char c in method){
89 if ((ic >= 'A' && ic <= 'Z') ||
90 (ic > 32 && c < 127 && c != '(' && c != ')' && c != '<' &&
91 c != '<' && c != '>' && c != '@' && c != ',' && c != ';' &&
92 c != ':' && c != '\\' && c != '"' && c != '/' && c != '[' &&
93 c != ']' && c != '?' && c != '=' && c != '{' && c != '}'))
96 context.ErrorMessage = "(Invalid verb)";
101 if (parts [2].Length != 8 || !parts [2].StartsWith ("HTTP/")) {
102 context.ErrorMessage = "Invalid request line (version).";
107 version = new Version (parts [2].Substring (5));
108 if (version.Major < 1)
109 throw new Exception ();
111 context.ErrorMessage = "Invalid request line (version).";
116 void CreateQueryString (string query)
118 if (query == null || query.Length == 0) {
119 query_string = new NameValueCollection (1);
123 query_string = new NameValueCollection ();
124 if (query [0] == '?')
125 query = query.Substring (1);
126 string [] components = query.Split ('&');
127 foreach (string kv in components) {
128 int pos = kv.IndexOf ('=');
130 query_string.Add (null, HttpUtility.UrlDecode (kv));
132 string key = HttpUtility.UrlDecode (kv.Substring (0, pos));
133 string val = HttpUtility.UrlDecode (kv.Substring (pos + 1));
135 query_string.Add (key, val);
140 internal void FinishInitialization ()
142 string host = UserHostName;
143 if (version > HttpVersion.Version10 && (host == null || host.Length == 0)) {
144 context.ErrorMessage = "Invalid host name";
150 if (Uri.MaybeUri (raw_url) && Uri.TryCreate (raw_url, UriKind.Absolute, out raw_uri))
151 path = raw_uri.PathAndQuery;
153 path = HttpUtility.UrlDecode (raw_url);
155 if ((host == null || host.Length == 0))
156 host = UserHostAddress;
161 int colon = host.IndexOf (':');
163 host = host.Substring (0, colon);
165 string base_uri = String.Format ("{0}://{1}:{2}",
166 (IsSecureConnection) ? "https" : "http",
167 host, LocalEndPoint.Port);
169 if (!Uri.TryCreate (base_uri + path, UriKind.Absolute, out url)){
170 context.ErrorMessage = "Invalid url: " + base_uri + path;
174 CreateQueryString (url.Query);
176 if (version >= HttpVersion.Version11) {
177 string t_encoding = Headers ["Transfer-Encoding"];
178 is_chunked = (t_encoding != null && String.Compare (t_encoding, "chunked", StringComparison.OrdinalIgnoreCase) == 0);
179 // 'identity' is not valid!
180 if (t_encoding != null && !is_chunked) {
181 context.Connection.SendError (null, 501);
186 if (!is_chunked && !cl_set) {
187 if (String.Compare (method, "POST", StringComparison.OrdinalIgnoreCase) == 0 ||
188 String.Compare (method, "PUT", StringComparison.OrdinalIgnoreCase) == 0) {
189 context.Connection.SendError (null, 411);
194 if (String.Compare (Headers ["Expect"], "100-continue", StringComparison.OrdinalIgnoreCase) == 0) {
195 ResponseStream output = context.Connection.GetResponseStream ();
196 output.InternalWrite (_100continue, 0, _100continue.Length);
200 internal static string Unquote (String str) {
201 int start = str.IndexOf ('\"');
202 int end = str.LastIndexOf ('\"');
203 if (start >= 0 && end >=0)
204 str = str.Substring (start + 1, end - 1);
208 internal void AddHeader (string header)
210 int colon = header.IndexOf (':');
211 if (colon == -1 || colon == 0) {
212 context.ErrorMessage = "Bad Request";
213 context.ErrorStatus = 400;
217 string name = header.Substring (0, colon).Trim ();
218 string val = header.Substring (colon + 1).Trim ();
219 string lower = name.ToLower (CultureInfo.InvariantCulture);
220 headers.SetInternal (name, val);
222 case "accept-language":
223 user_languages = val.Split (','); // yes, only split with a ','
226 accept_types = val.Split (','); // yes, only split with a ','
228 case "content-length":
230 //TODO: max. content_length?
231 content_length = Int64.Parse (val.Trim ());
232 if (content_length < 0)
233 context.ErrorMessage = "Invalid Content-Length.";
236 context.ErrorMessage = "Invalid Content-Length.";
242 referrer = new Uri (val);
244 referrer = new Uri ("http://someone.is.screwing.with.the.headers.com/");
249 cookies = new CookieCollection();
251 string[] cookieStrings = val.Split(new char[] {',', ';'});
252 Cookie current = null;
254 foreach (string cookieString in cookieStrings) {
255 string str = cookieString.Trim ();
258 if (str.StartsWith ("$Version")) {
259 version = Int32.Parse (Unquote (str.Substring (str.IndexOf ('=') + 1)));
260 } else if (str.StartsWith ("$Path")) {
262 current.Path = str.Substring (str.IndexOf ('=') + 1).Trim ();
263 } else if (str.StartsWith ("$Domain")) {
265 current.Domain = str.Substring (str.IndexOf ('=') + 1).Trim ();
266 } else if (str.StartsWith ("$Port")) {
268 current.Port = str.Substring (str.IndexOf ('=') + 1).Trim ();
270 if (current != null) {
271 cookies.Add (current);
273 current = new Cookie ();
274 int idx = str.IndexOf ('=');
276 current.Name = str.Substring (0, idx).Trim ();
277 current.Value = str.Substring (idx + 1).Trim ();
279 current.Name = str.Trim ();
280 current.Value = String.Empty;
282 current.Version = version;
285 if (current != null) {
286 cookies.Add (current);
292 // returns true is the stream could be reused.
293 internal bool FlushInput ()
299 if (content_length > 0)
300 length = (int) Math.Min (content_length, (long) length);
302 byte [] bytes = new byte [length];
304 // TODO: test if MS has a timeout when doing this
306 IAsyncResult ares = InputStream.BeginRead (bytes, 0, length, null, null);
307 if (!ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne (100))
309 if (InputStream.EndRead (ares) <= 0)
317 public string [] AcceptTypes {
318 get { return accept_types; }
321 [MonoTODO ("Always returns 0")]
322 public int ClientCertificateError {
325 if (no_get_certificate)
326 throw new InvalidOperationException (
327 "Call GetClientCertificate() before calling this method.");
328 return client_cert_error;
334 public Encoding ContentEncoding {
336 if (content_encoding == null)
337 content_encoding = Encoding.Default;
338 return content_encoding;
342 public long ContentLength64 {
343 get { return content_length; }
346 public string ContentType {
347 get { return headers ["content-type"]; }
350 public CookieCollection Cookies {
352 // TODO: check if the collection is read-only
354 cookies = new CookieCollection ();
359 public bool HasEntityBody {
360 get { return (content_length > 0 || is_chunked); }
363 public NameValueCollection Headers {
364 get { return headers; }
367 public string HttpMethod {
368 get { return method; }
371 public Stream InputStream {
373 if (input_stream == null) {
374 if (is_chunked || content_length > 0)
375 input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
377 input_stream = Stream.Null;
384 [MonoTODO ("Always returns false")]
385 public bool IsAuthenticated {
386 get { return false; }
389 public bool IsLocal {
390 get { return IPAddress.IsLoopback (RemoteEndPoint.Address); }
393 public bool IsSecureConnection {
394 get { return context.Connection.IsSecure; }
397 public bool KeepAlive {
403 // 1. Connection header
404 // 2. Protocol (1.1 == keep-alive by default)
405 // 3. Keep-Alive header
406 string cnc = headers ["Connection"];
407 if (!String.IsNullOrEmpty (cnc)) {
408 keep_alive = (0 == String.Compare (cnc, "keep-alive", StringComparison.OrdinalIgnoreCase));
409 } else if (version == HttpVersion.Version11) {
412 cnc = headers ["keep-alive"];
413 if (!String.IsNullOrEmpty (cnc))
414 keep_alive = (0 != String.Compare (cnc, "closed", StringComparison.OrdinalIgnoreCase));
420 public IPEndPoint LocalEndPoint {
421 get { return context.Connection.LocalEndPoint; }
424 public Version ProtocolVersion {
425 get { return version; }
428 public NameValueCollection QueryString {
429 get { return query_string; }
432 public string RawUrl {
433 get { return raw_url; }
436 public IPEndPoint RemoteEndPoint {
437 get { return context.Connection.RemoteEndPoint; }
440 [MonoTODO ("Always returns Guid.Empty")]
441 public Guid RequestTraceIdentifier {
442 get { return Guid.Empty; }
449 public Uri UrlReferrer {
450 get { return referrer; }
453 public string UserAgent {
454 get { return headers ["user-agent"]; }
457 public string UserHostAddress {
458 get { return LocalEndPoint.ToString (); }
461 public string UserHostName {
462 get { return headers ["host"]; }
465 public string [] UserLanguages {
466 get { return user_languages; }
470 public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, object state)
472 throw new NotImplementedException ();
476 public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
478 throw new NotImplementedException ();
481 public X509Certificate2 GetClientCertificate ()
483 // set no_client_certificate once done.
485 // InvalidOp if call in progress.
490 public Task<X509Certificate2> GetClientCertificateAsync ()
492 return Task<X509Certificate2>.Factory.FromAsync (BeginGetClientCertificate, EndGetClientCertificate, null);