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
56 string [] user_languages;
57 HttpListenerContext context;
59 static byte [] _100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n");
60 static readonly string [] no_body_methods = new string [] {
61 "GET", "HEAD", "DELETE" };
63 internal HttpListenerRequest (HttpListenerContext context)
65 this.context = context;
66 headers = new WebHeaderCollection ();
67 input_stream = Stream.Null;
68 version = HttpVersion.Version10;
71 static char [] separators = new char [] { ' ' };
73 internal void SetRequestLine (string req)
75 string [] parts = req.Split (separators, 3);
76 if (parts.Length != 3) {
77 context.ErrorMessage = "Invalid request line (parts).";
82 foreach (char c in method){
85 if ((ic >= 'A' && ic <= 'Z') ||
86 (ic > 32 && c < 127 && c != '(' && c != ')' && c != '<' &&
87 c != '<' && c != '>' && c != '@' && c != ',' && c != ';' &&
88 c != ':' && c != '\\' && c != '"' && c != '/' && c != '[' &&
89 c != ']' && c != '?' && c != '=' && c != '{' && c != '}'))
92 context.ErrorMessage = "(Invalid verb)";
97 if (parts [2].Length != 8 || !parts [2].StartsWith ("HTTP/")) {
98 context.ErrorMessage = "Invalid request line (version).";
103 version = new Version (parts [2].Substring (5));
104 if (version.Major < 1)
105 throw new Exception ();
107 context.ErrorMessage = "Invalid request line (version).";
112 void CreateQueryString (string query)
114 query_string = new NameValueCollection ();
115 if (query == null || query.Length == 0)
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",
164 if (!Uri.TryCreate (base_uri + path, UriKind.Absolute, out url)){
165 context.ErrorMessage = "Invalid url: " + base_uri + path;
169 CreateQueryString (url.Query);
171 string t_encoding = null;
172 if (version >= HttpVersion.Version11) {
173 t_encoding = Headers ["Transfer-Encoding"];
174 // 'identity' is not valid!
175 if (t_encoding != null && t_encoding != "chunked") {
176 context.Connection.SendError (null, 501);
181 is_chunked = (t_encoding == "chunked");
183 foreach (string m in no_body_methods)
184 if (string.Compare (method, m, StringComparison.InvariantCultureIgnoreCase) == 0)
187 if (!is_chunked && !cl_set) {
188 context.Connection.SendError (null, 411);
192 if (is_chunked || content_length > 0) {
193 input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
196 if (Headers ["Expect"] == "100-continue") {
197 ResponseStream output = context.Connection.GetResponseStream ();
198 output.InternalWrite (_100continue, 0, _100continue.Length);
202 internal static string Unquote (String str) {
203 int start = str.IndexOf ('\"');
204 int end = str.LastIndexOf ('\"');
205 if (start >= 0 && end >=0)
206 str = str.Substring (start + 1, end - 1);
210 internal void AddHeader (string header)
212 int colon = header.IndexOf (':');
213 if (colon == -1 || colon == 0) {
214 context.ErrorMessage = "Bad Request";
215 context.ErrorStatus = 400;
219 string name = header.Substring (0, colon).Trim ();
220 string val = header.Substring (colon + 1).Trim ();
221 string lower = name.ToLower (CultureInfo.InvariantCulture);
222 headers.SetInternal (name, val);
224 case "accept-language":
225 user_languages = val.Split (','); // yes, only split with a ','
228 accept_types = val.Split (','); // yes, only split with a ','
230 case "content-length":
232 //TODO: max. content_length?
233 content_length = Int64.Parse (val.Trim ());
234 if (content_length < 0)
235 context.ErrorMessage = "Invalid Content-Length.";
238 context.ErrorMessage = "Invalid Content-Length.";
244 referrer = new Uri (val);
246 referrer = new Uri ("http://someone.is.screwing.with.the.headers.com/");
251 cookies = new CookieCollection();
253 string[] cookieStrings = val.Split(new char[] {',', ';'});
254 Cookie current = null;
256 foreach (string cookieString in cookieStrings) {
257 string str = cookieString.Trim ();
260 if (str.StartsWith ("$Version")) {
261 version = Int32.Parse (Unquote (str.Substring (str.IndexOf ("=") + 1)));
262 } else if (str.StartsWith ("$Path")) {
264 current.Path = str.Substring (str.IndexOf ("=") + 1).Trim ();
265 } else if (str.StartsWith ("$Domain")) {
267 current.Domain = str.Substring (str.IndexOf ("=") + 1).Trim ();
268 } else if (str.StartsWith ("$Port")) {
270 current.Port = str.Substring (str.IndexOf ("=") + 1).Trim ();
272 if (current != null) {
273 cookies.Add (current);
275 current = new Cookie ();
276 int idx = str.IndexOf ("=");
278 current.Name = str.Substring (0, idx).Trim ();
279 current.Value = str.Substring (idx + 1).Trim ();
281 current.Name = str.Trim ();
282 current.Value = String.Empty;
284 current.Version = version;
287 if (current != null) {
288 cookies.Add (current);
294 // returns true is the stream could be reused.
295 internal bool FlushInput ()
301 if (content_length > 0)
302 length = (int) Math.Min (content_length, (long) length);
304 byte [] bytes = new byte [length];
306 // TODO: test if MS has a timeout when doing this
308 if (InputStream.Read (bytes, 0, length) <= 0)
316 public string [] AcceptTypes {
317 get { return accept_types; }
320 [MonoTODO ("Always returns 0")]
321 public int ClientCertificateError {
324 if (no_get_certificate)
325 throw new InvalidOperationException (
326 "Call GetClientCertificate() before calling this method.");
327 return client_cert_error;
333 public Encoding ContentEncoding {
335 if (content_encoding == null)
336 content_encoding = Encoding.Default;
337 return content_encoding;
341 public long ContentLength64 {
342 get { return content_length; }
345 public string ContentType {
346 get { return headers ["content-type"]; }
349 public CookieCollection Cookies {
351 // TODO: check if the collection is read-only
353 cookies = new CookieCollection ();
358 public bool HasEntityBody {
359 get { return (content_length > 0 || is_chunked); }
362 public NameValueCollection Headers {
363 get { return headers; }
366 public string HttpMethod {
367 get { return method; }
370 public Stream InputStream {
371 get { return input_stream; }
374 [MonoTODO ("Always returns false")]
375 public bool IsAuthenticated {
376 get { return false; }
379 public bool IsLocal {
380 get { return IPAddress.IsLoopback (RemoteEndPoint.Address); }
383 public bool IsSecureConnection {
384 get { return context.Connection.IsSecure; }
387 public bool KeepAlive {
388 get { return false; }
391 public IPEndPoint LocalEndPoint {
392 get { return context.Connection.LocalEndPoint; }
395 public Version ProtocolVersion {
396 get { return version; }
399 public NameValueCollection QueryString {
400 get { return query_string; }
403 public string RawUrl {
404 get { return raw_url; }
407 public IPEndPoint RemoteEndPoint {
408 get { return context.Connection.RemoteEndPoint; }
411 public Guid RequestTraceIdentifier {
412 get { return identifier; }
419 public Uri UrlReferrer {
420 get { return referrer; }
423 public string UserAgent {
424 get { return headers ["user-agent"]; }
427 public string UserHostAddress {
428 get { return LocalEndPoint.ToString (); }
431 public string UserHostName {
432 get { return headers ["host"]; }
435 public string [] UserLanguages {
436 get { return user_languages; }
439 public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, Object state)
444 public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
447 // set no_client_certificate once done.
450 public X509Certificate2 GetClientCertificate ()
452 // set no_client_certificate once done.
454 // InvalidOp if call in progress.