1 #define EMBEDDED_IN_1_0
4 // System.Net.HttpListenerRequest
7 // Gonzalo Paniagua Javier (gonzalo@novell.com)
9 // Copyright (c) 2005 Novell, Inc. (http://www.novell.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;
39 using System; using System.Net; namespace MonoHttp {
40 internal class HttpListenerRequest
42 string [] accept_types;
43 // int client_cert_error;
44 // bool no_get_certificate;
45 Encoding content_encoding;
48 CookieCollection cookies;
49 WebHeaderCollection headers;
53 NameValueCollection query_string; // check if null is ok, check if read-only, check case-sensitiveness
58 string [] user_languages;
59 HttpListenerContext context;
61 static byte [] _100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n");
62 static readonly string [] no_body_methods = new string [] {
63 "GET", "HEAD", "DELETE" };
65 internal HttpListenerRequest (HttpListenerContext context)
67 this.context = context;
68 headers = new WebHeaderCollection ();
69 input_stream = Stream.Null;
72 static char [] separators = new char [] { ' ' };
74 internal void SetRequestLine (string req)
76 string [] parts = req.Split (separators, 3);
77 if (parts.Length != 3) {
78 context.ErrorMessage = "Invalid request line (parts).";
83 foreach (char c in method){
86 if ((ic >= 'A' && ic <= 'Z') ||
87 (ic > 32 && c < 127 && c != '(' && c != ')' && c != '<' &&
88 c != '<' && c != '>' && c != '@' && c != ',' && c != ';' &&
89 c != ':' && c != '\\' && c != '"' && c != '/' && c != '[' &&
90 c != ']' && c != '?' && c != '=' && c != '{' && c != '}'))
93 context.ErrorMessage = "(Invalid verb)";
98 if (parts [2].Length != 8 || !parts [2].StartsWith ("HTTP/")) {
99 context.ErrorMessage = "Invalid request line (version).";
104 version = new Version (parts [2].Substring (5));
105 if (version.Major < 1)
106 throw new Exception ();
108 context.ErrorMessage = "Invalid request line (version).";
113 void CreateQueryString (string query)
115 query_string = new NameValueCollection ();
116 if (query == null || query.Length == 0)
119 if (query [0] == '?')
120 query = query.Substring (1);
121 string [] components = query.Split ('&');
122 foreach (string kv in components) {
123 int pos = kv.IndexOf ('=');
125 query_string.Add (null, HttpUtility.UrlDecode (kv));
127 string key = HttpUtility.UrlDecode (kv.Substring (0, pos));
128 string val = HttpUtility.UrlDecode (kv.Substring (pos + 1));
130 query_string.Add (key, val);
135 internal void FinishInitialization ()
137 string host = UserHostName;
138 if (version > HttpVersion.Version10 && (host == null || host.Length == 0)) {
139 context.ErrorMessage = "Invalid host name";
146 if (MonoHttp.Utility.MaybeUri (raw_url) && Uri.TryCreate (raw_url, UriKind.Absolute, out raw_uri))
148 try { raw_uri = new Uri (raw_url); } catch { raw_uri = null; } if (url != raw_uri && (raw_uri.Host == null || raw_uri.Host.Length == 0)) raw_uri = null; if (raw_uri != null)
151 path = raw_uri.PathAndQuery;
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",
171 if (!Uri.TryCreate (base_uri + path, UriKind.Absolute, out url)){
173 try { url = new Uri (base_uri + path); } catch {}; if (url != null && (url.Host == null || url.Host.Length == 0)) url = null; if (url == null) {
176 context.ErrorMessage = "Invalid url: " + base_uri + path;
180 CreateQueryString (url.Query);
182 string t_encoding = null;
183 if (version >= HttpVersion.Version11) {
184 t_encoding = Headers ["Transfer-Encoding"];
185 // 'identity' is not valid!
186 if (t_encoding != null && t_encoding != "chunked") {
187 context.Connection.SendError (null, 501);
192 is_chunked = (t_encoding == "chunked");
194 foreach (string m in no_body_methods)
195 if (string.Compare (method, m, true, System.Globalization.CultureInfo.InvariantCulture) == 0)
198 if (!is_chunked && !cl_set) {
199 context.Connection.SendError (null, 411);
203 if (is_chunked || content_length > 0) {
204 input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
207 if (Headers ["Expect"] == "100-continue") {
208 ResponseStream output = context.Connection.GetResponseStream ();
209 output.InternalWrite (_100continue, 0, _100continue.Length);
213 internal static string Unquote (String str) {
214 int start = str.IndexOf ('\"');
215 int end = str.LastIndexOf ('\"');
216 if (start >= 0 && end >=0)
217 str = str.Substring (start + 1, end - 1);
221 internal void AddHeader (string header)
223 int colon = header.IndexOf (':');
224 if (colon == -1 || colon == 0) {
225 context.ErrorMessage = "Bad Request";
229 string name = header.Substring (0, colon).Trim ();
230 string val = header.Substring (colon + 1).Trim ();
231 string lower = name.ToLower (CultureInfo.InvariantCulture);
232 headers.SetInternal (name, val);
234 case "accept-language":
235 user_languages = val.Split (','); // yes, only split with a ','
238 accept_types = val.Split (','); // yes, only split with a ','
240 case "content-length":
242 //TODO: max. content_length?
243 content_length = Int64.Parse (val.Trim ());
244 if (content_length < 0)
245 context.ErrorMessage = "Invalid Content-Length.";
248 context.ErrorMessage = "Invalid Content-Length.";
254 referrer = new Uri (val);
256 referrer = new Uri ("http://someone.is.screwing.with.the.headers.com/");
261 cookies = new CookieCollection();
263 string[] cookieStrings = val.Split(new char[] {',', ';'});
264 Cookie current = null;
266 foreach (string cookieString in cookieStrings) {
267 string str = cookieString.Trim ();
270 if (str.StartsWith ("$Version")) {
271 version = Int32.Parse (Unquote (str.Substring (str.IndexOf ("=") + 1)));
272 } else if (str.StartsWith ("$Path")) {
274 current.Path = str.Substring (str.IndexOf ("=") + 1).Trim ();
275 } else if (str.StartsWith ("$Domain")) {
277 current.Domain = str.Substring (str.IndexOf ("=") + 1).Trim ();
278 } else if (str.StartsWith ("$Port")) {
280 current.Port = str.Substring (str.IndexOf ("=") + 1).Trim ();
282 if (current != null) {
283 cookies.Add (current);
285 current = new Cookie ();
286 int idx = str.IndexOf ("=");
288 current.Name = str.Substring (0, idx).Trim ();
289 current.Value = str.Substring (idx + 1).Trim ();
291 current.Name = str.Trim ();
292 current.Value = String.Empty;
294 current.Version = version;
297 if (current != null) {
298 cookies.Add (current);
304 public string [] AcceptTypes {
305 get { return accept_types; }
308 [MonoTODO ("Always returns 0")]
309 public int ClientCertificateError {
312 if (no_get_certificate)
313 throw new InvalidOperationException (
314 "Call GetClientCertificate() before calling this method.");
315 return client_cert_error;
321 public Encoding ContentEncoding {
323 if (content_encoding == null)
324 content_encoding = Encoding.Default;
325 return content_encoding;
329 public long ContentLength64 {
330 get { return content_length; }
333 public string ContentType {
334 get { return headers ["content-type"]; }
337 public CookieCollection Cookies {
339 // TODO: check if the collection is read-only
341 cookies = new CookieCollection ();
346 public bool HasEntityBody {
347 get { return (content_length > 0 || is_chunked); }
350 public NameValueCollection Headers {
351 get { return headers; }
354 public string HttpMethod {
355 get { return method; }
358 public Stream InputStream {
359 get { return input_stream; }
362 [MonoTODO ("Always returns false")]
363 public bool IsAuthenticated {
364 get { return false; }
367 public bool IsLocal {
368 get { return IPAddress.IsLoopback (RemoteEndPoint.Address); }
371 public bool IsSecureConnection {
372 get { return context.Connection.IsSecure; }
375 public bool KeepAlive {
376 get { return false; }
379 public IPEndPoint LocalEndPoint {
380 get { return context.Connection.LocalEndPoint; }
383 public Version ProtocolVersion {
384 get { return version; }
387 public NameValueCollection QueryString {
388 get { return query_string; }
391 public string RawUrl {
392 get { return raw_url; }
395 public IPEndPoint RemoteEndPoint {
396 get { return context.Connection.RemoteEndPoint; }
399 public Guid RequestTraceIdentifier {
400 get { return identifier; }
407 public Uri UrlReferrer {
408 get { return referrer; }
411 public string UserAgent {
412 get { return headers ["user-agent"]; }
415 public string UserHostAddress {
416 get { return LocalEndPoint.ToString (); }
419 public string UserHostName {
420 get { return headers ["host"]; }
423 public string [] UserLanguages {
424 get { return user_languages; }
427 public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, Object state)
432 public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
435 // set no_client_certificate once done.
438 public X509Certificate2 GetClientCertificate ()
440 // set no_client_certificate once done.
442 // InvalidOp if call in progress.