2 // System.Net.HttpListenerRequest
5 // Gonzalo Paniagua Javier (gonzalo@novell.com)
7 // Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 #if NET_2_0 && SECURITY_DEP
31 using System.Collections;
32 using System.Collections.Specialized;
33 using System.Globalization;
35 using System.Security.Cryptography.X509Certificates;
37 namespace System.Net {
38 public sealed class HttpListenerRequest
40 string [] accept_types;
41 // int client_cert_error;
42 // bool no_get_certificate;
43 Encoding content_encoding;
46 CookieCollection cookies;
47 WebHeaderCollection headers;
51 NameValueCollection query_string; // check if null is ok, check if read-only, check case-sensitiveness
55 string [] user_languages;
56 HttpListenerContext context;
60 static byte [] _100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n");
62 internal HttpListenerRequest (HttpListenerContext context)
64 this.context = context;
65 headers = new WebHeaderCollection ();
66 version = HttpVersion.Version10;
69 static char [] separators = new char [] { ' ' };
71 internal void SetRequestLine (string req)
73 string [] parts = req.Split (separators, 3);
74 if (parts.Length != 3) {
75 context.ErrorMessage = "Invalid request line (parts).";
80 foreach (char c in method){
83 if ((ic >= 'A' && ic <= 'Z') ||
84 (ic > 32 && c < 127 && c != '(' && c != ')' && c != '<' &&
85 c != '<' && c != '>' && c != '@' && c != ',' && c != ';' &&
86 c != ':' && c != '\\' && c != '"' && c != '/' && c != '[' &&
87 c != ']' && c != '?' && c != '=' && c != '{' && c != '}'))
90 context.ErrorMessage = "(Invalid verb)";
95 if (parts [2].Length != 8 || !parts [2].StartsWith ("HTTP/")) {
96 context.ErrorMessage = "Invalid request line (version).";
101 version = new Version (parts [2].Substring (5));
102 if (version.Major < 1)
103 throw new Exception ();
105 context.ErrorMessage = "Invalid request line (version).";
110 void CreateQueryString (string query)
112 if (query == null || query.Length == 0) {
113 query_string = new NameValueCollection (1);
117 query_string = new NameValueCollection ();
118 if (query [0] == '?')
119 query = query.Substring (1);
120 string [] components = query.Split ('&');
121 foreach (string kv in components) {
122 int pos = kv.IndexOf ('=');
124 query_string.Add (null, HttpUtility.UrlDecode (kv));
126 string key = HttpUtility.UrlDecode (kv.Substring (0, pos));
127 string val = HttpUtility.UrlDecode (kv.Substring (pos + 1));
129 query_string.Add (key, val);
134 internal void FinishInitialization ()
136 string host = UserHostName;
137 if (version > HttpVersion.Version10 && (host == null || host.Length == 0)) {
138 context.ErrorMessage = "Invalid host name";
144 if (Uri.MaybeUri (raw_url) && Uri.TryCreate (raw_url, UriKind.Absolute, out raw_uri))
145 path = raw_uri.PathAndQuery;
149 if ((host == null || host.Length == 0))
150 host = UserHostAddress;
155 int colon = host.IndexOf (':');
157 host = host.Substring (0, colon);
159 string base_uri = String.Format ("{0}://{1}:{2}",
160 (IsSecureConnection) ? "https" : "http",
161 host, LocalEndPoint.Port);
163 if (!Uri.TryCreate (base_uri + path, UriKind.Absolute, out url)){
164 context.ErrorMessage = "Invalid url: " + base_uri + path;
168 CreateQueryString (url.Query);
170 if (version >= HttpVersion.Version11) {
171 string t_encoding = Headers ["Transfer-Encoding"];
172 is_chunked = (t_encoding != null && String.Compare (t_encoding, "chunked", StringComparison.OrdinalIgnoreCase) == 0);
173 // 'identity' is not valid!
174 if (t_encoding != null && !is_chunked) {
175 context.Connection.SendError (null, 501);
180 if (!is_chunked && !cl_set) {
181 if (String.Compare (method, "POST", StringComparison.OrdinalIgnoreCase) == 0 ||
182 String.Compare (method, "PUT", StringComparison.OrdinalIgnoreCase) == 0) {
183 context.Connection.SendError (null, 411);
188 if (String.Compare (Headers ["Expect"], "100-continue", StringComparison.OrdinalIgnoreCase) == 0) {
189 ResponseStream output = context.Connection.GetResponseStream ();
190 output.InternalWrite (_100continue, 0, _100continue.Length);
194 internal static string Unquote (String str) {
195 int start = str.IndexOf ('\"');
196 int end = str.LastIndexOf ('\"');
197 if (start >= 0 && end >=0)
198 str = str.Substring (start + 1, end - 1);
202 internal void AddHeader (string header)
204 int colon = header.IndexOf (':');
205 if (colon == -1 || colon == 0) {
206 context.ErrorMessage = "Bad Request";
207 context.ErrorStatus = 400;
211 string name = header.Substring (0, colon).Trim ();
212 string val = header.Substring (colon + 1).Trim ();
213 string lower = name.ToLower (CultureInfo.InvariantCulture);
214 headers.SetInternal (name, val);
216 case "accept-language":
217 user_languages = val.Split (','); // yes, only split with a ','
220 accept_types = val.Split (','); // yes, only split with a ','
222 case "content-length":
224 //TODO: max. content_length?
225 content_length = Int64.Parse (val.Trim ());
226 if (content_length < 0)
227 context.ErrorMessage = "Invalid Content-Length.";
230 context.ErrorMessage = "Invalid Content-Length.";
236 referrer = new Uri (val);
238 referrer = new Uri ("http://someone.is.screwing.with.the.headers.com/");
243 cookies = new CookieCollection();
245 string[] cookieStrings = val.Split(new char[] {',', ';'});
246 Cookie current = null;
248 foreach (string cookieString in cookieStrings) {
249 string str = cookieString.Trim ();
252 if (str.StartsWith ("$Version")) {
253 version = Int32.Parse (Unquote (str.Substring (str.IndexOf ('=') + 1)));
254 } else if (str.StartsWith ("$Path")) {
256 current.Path = str.Substring (str.IndexOf ('=') + 1).Trim ();
257 } else if (str.StartsWith ("$Domain")) {
259 current.Domain = str.Substring (str.IndexOf ('=') + 1).Trim ();
260 } else if (str.StartsWith ("$Port")) {
262 current.Port = str.Substring (str.IndexOf ('=') + 1).Trim ();
264 if (current != null) {
265 cookies.Add (current);
267 current = new Cookie ();
268 int idx = str.IndexOf ('=');
270 current.Name = str.Substring (0, idx).Trim ();
271 current.Value = str.Substring (idx + 1).Trim ();
273 current.Name = str.Trim ();
274 current.Value = String.Empty;
276 current.Version = version;
279 if (current != null) {
280 cookies.Add (current);
286 // returns true is the stream could be reused.
287 internal bool FlushInput ()
293 if (content_length > 0)
294 length = (int) Math.Min (content_length, (long) length);
296 byte [] bytes = new byte [length];
298 // TODO: test if MS has a timeout when doing this
300 IAsyncResult ares = InputStream.BeginRead (bytes, 0, length, null, null);
301 if (!ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne (100))
303 if (InputStream.EndRead (ares) <= 0)
311 public string [] AcceptTypes {
312 get { return accept_types; }
315 [MonoTODO ("Always returns 0")]
316 public int ClientCertificateError {
319 if (no_get_certificate)
320 throw new InvalidOperationException (
321 "Call GetClientCertificate() before calling this method.");
322 return client_cert_error;
328 public Encoding ContentEncoding {
330 if (content_encoding == null)
331 content_encoding = Encoding.Default;
332 return content_encoding;
336 public long ContentLength64 {
337 get { return content_length; }
340 public string ContentType {
341 get { return headers ["content-type"]; }
344 public CookieCollection Cookies {
346 // TODO: check if the collection is read-only
348 cookies = new CookieCollection ();
353 public bool HasEntityBody {
354 get { return (content_length > 0 || is_chunked); }
357 public NameValueCollection Headers {
358 get { return headers; }
361 public string HttpMethod {
362 get { return method; }
365 public Stream InputStream {
367 if (input_stream == null) {
368 if (is_chunked || content_length > 0)
369 input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
371 input_stream = Stream.Null;
378 [MonoTODO ("Always returns false")]
379 public bool IsAuthenticated {
380 get { return false; }
383 public bool IsLocal {
384 get { return IPAddress.IsLoopback (RemoteEndPoint.Address); }
387 public bool IsSecureConnection {
388 get { return context.Connection.IsSecure; }
391 public bool KeepAlive {
397 // 1. Connection header
398 // 2. Protocol (1.1 == keep-alive by default)
399 // 3. Keep-Alive header
400 string cnc = headers ["Connection"];
401 if (!String.IsNullOrEmpty (cnc)) {
402 keep_alive = (0 == String.Compare (cnc, "keep-alive", StringComparison.OrdinalIgnoreCase));
403 } else if (version == HttpVersion.Version11) {
406 cnc = headers ["keep-alive"];
407 if (!String.IsNullOrEmpty (cnc))
408 keep_alive = (0 != String.Compare (cnc, "closed", StringComparison.OrdinalIgnoreCase));
414 public IPEndPoint LocalEndPoint {
415 get { return context.Connection.LocalEndPoint; }
418 public Version ProtocolVersion {
419 get { return version; }
422 public NameValueCollection QueryString {
423 get { return query_string; }
426 public string RawUrl {
427 get { return raw_url; }
430 public IPEndPoint RemoteEndPoint {
431 get { return context.Connection.RemoteEndPoint; }
434 [MonoTODO ("Always returns Guid.Empty")]
435 public Guid RequestTraceIdentifier {
436 get { return Guid.Empty; }
443 public Uri UrlReferrer {
444 get { return referrer; }
447 public string UserAgent {
448 get { return headers ["user-agent"]; }
451 public string UserHostAddress {
452 get { return LocalEndPoint.ToString (); }
455 public string UserHostName {
456 get { return headers ["host"]; }
459 public string [] UserLanguages {
460 get { return user_languages; }
463 public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, Object state)
468 public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
471 // set no_client_certificate once done.
474 public X509Certificate2 GetClientCertificate ()
476 // set no_client_certificate once done.
478 // InvalidOp if call in progress.