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;
70 version = HttpVersion.Version10;
73 static char [] separators = new char [] { ' ' };
75 internal void SetRequestLine (string req)
77 string [] parts = req.Split (separators, 3);
78 if (parts.Length != 3) {
79 context.ErrorMessage = "Invalid request line (parts).";
84 foreach (char c in method){
87 if ((ic >= 'A' && ic <= 'Z') ||
88 (ic > 32 && c < 127 && c != '(' && c != ')' && c != '<' &&
89 c != '<' && c != '>' && c != '@' && c != ',' && c != ';' &&
90 c != ':' && c != '\\' && c != '"' && c != '/' && c != '[' &&
91 c != ']' && c != '?' && c != '=' && c != '{' && c != '}'))
94 context.ErrorMessage = "(Invalid verb)";
99 if (parts [2].Length != 8 || !parts [2].StartsWith ("HTTP/")) {
100 context.ErrorMessage = "Invalid request line (version).";
105 version = new Version (parts [2].Substring (5));
106 if (version.Major < 1)
107 throw new Exception ();
109 context.ErrorMessage = "Invalid request line (version).";
114 void CreateQueryString (string query)
116 query_string = new NameValueCollection ();
117 if (query == null || query.Length == 0)
120 if (query [0] == '?')
121 query = query.Substring (1);
122 string [] components = query.Split ('&');
123 foreach (string kv in components) {
124 int pos = kv.IndexOf ('=');
126 query_string.Add (null, HttpUtility.UrlDecode (kv));
128 string key = HttpUtility.UrlDecode (kv.Substring (0, pos));
129 string val = HttpUtility.UrlDecode (kv.Substring (pos + 1));
131 query_string.Add (key, val);
136 internal void FinishInitialization ()
138 string host = UserHostName;
139 if (version > HttpVersion.Version10 && (host == null || host.Length == 0)) {
140 context.ErrorMessage = "Invalid host name";
147 if (MonoHttp.Utility.MaybeUri (raw_url) && Uri.TryCreate (raw_url, UriKind.Absolute, out raw_uri))
149 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)
152 path = raw_uri.PathAndQuery;
156 if ((host == null || host.Length == 0))
157 host = UserHostAddress;
162 int colon = host.IndexOf (':');
164 host = host.Substring (0, colon);
166 string base_uri = String.Format ("{0}://{1}:{2}",
167 (IsSecureConnection) ? "https" : "http",
172 if (!Uri.TryCreate (base_uri + path, UriKind.Absolute, out url)){
174 try { url = new Uri (base_uri + path); } catch {}; if (url != null && (url.Host == null || url.Host.Length == 0)) url = null; if (url == null) {
177 context.ErrorMessage = "Invalid url: " + base_uri + path;
181 CreateQueryString (url.Query);
183 string t_encoding = null;
184 if (version >= HttpVersion.Version11) {
185 t_encoding = Headers ["Transfer-Encoding"];
186 // 'identity' is not valid!
187 if (t_encoding != null && t_encoding != "chunked") {
188 context.Connection.SendError (null, 501);
193 is_chunked = (t_encoding == "chunked");
195 foreach (string m in no_body_methods)
196 if (string.Compare (method, m, true, System.Globalization.CultureInfo.InvariantCulture) == 0)
199 if (!is_chunked && !cl_set) {
200 context.Connection.SendError (null, 411);
204 if (is_chunked || content_length > 0) {
205 input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
208 if (Headers ["Expect"] == "100-continue") {
209 ResponseStream output = context.Connection.GetResponseStream ();
210 output.InternalWrite (_100continue, 0, _100continue.Length);
214 internal static string Unquote (String str) {
215 int start = str.IndexOf ('\"');
216 int end = str.LastIndexOf ('\"');
217 if (start >= 0 && end >=0)
218 str = str.Substring (start + 1, end - 1);
222 internal void AddHeader (string header)
224 int colon = header.IndexOf (':');
225 if (colon == -1 || colon == 0) {
226 context.ErrorMessage = "Bad Request";
230 string name = header.Substring (0, colon).Trim ();
231 string val = header.Substring (colon + 1).Trim ();
232 string lower = name.ToLower (CultureInfo.InvariantCulture);
233 headers.SetInternal (name, val);
235 case "accept-language":
236 user_languages = val.Split (','); // yes, only split with a ','
239 accept_types = val.Split (','); // yes, only split with a ','
241 case "content-length":
243 //TODO: max. content_length?
244 content_length = Int64.Parse (val.Trim ());
245 if (content_length < 0)
246 context.ErrorMessage = "Invalid Content-Length.";
249 context.ErrorMessage = "Invalid Content-Length.";
255 referrer = new Uri (val);
257 referrer = new Uri ("http://someone.is.screwing.with.the.headers.com/");
262 cookies = new CookieCollection();
264 string[] cookieStrings = val.Split(new char[] {',', ';'});
265 Cookie current = null;
267 foreach (string cookieString in cookieStrings) {
268 string str = cookieString.Trim ();
271 if (str.StartsWith ("$Version")) {
272 version = Int32.Parse (Unquote (str.Substring (str.IndexOf ("=") + 1)));
273 } else if (str.StartsWith ("$Path")) {
275 current.Path = str.Substring (str.IndexOf ("=") + 1).Trim ();
276 } else if (str.StartsWith ("$Domain")) {
278 current.Domain = str.Substring (str.IndexOf ("=") + 1).Trim ();
279 } else if (str.StartsWith ("$Port")) {
281 current.Port = str.Substring (str.IndexOf ("=") + 1).Trim ();
283 if (current != null) {
284 cookies.Add (current);
286 current = new Cookie ();
287 int idx = str.IndexOf ("=");
289 current.Name = str.Substring (0, idx).Trim ();
290 current.Value = str.Substring (idx + 1).Trim ();
292 current.Name = str.Trim ();
293 current.Value = String.Empty;
295 current.Version = version;
298 if (current != null) {
299 cookies.Add (current);
305 public string [] AcceptTypes {
306 get { return accept_types; }
309 [MonoTODO ("Always returns 0")]
310 public int ClientCertificateError {
313 if (no_get_certificate)
314 throw new InvalidOperationException (
315 "Call GetClientCertificate() before calling this method.");
316 return client_cert_error;
322 public Encoding ContentEncoding {
324 if (content_encoding == null)
325 content_encoding = Encoding.Default;
326 return content_encoding;
330 public long ContentLength64 {
331 get { return content_length; }
334 public string ContentType {
335 get { return headers ["content-type"]; }
338 public CookieCollection Cookies {
340 // TODO: check if the collection is read-only
342 cookies = new CookieCollection ();
347 public bool HasEntityBody {
348 get { return (content_length > 0 || is_chunked); }
351 public NameValueCollection Headers {
352 get { return headers; }
355 public string HttpMethod {
356 get { return method; }
359 public Stream InputStream {
360 get { return input_stream; }
363 [MonoTODO ("Always returns false")]
364 public bool IsAuthenticated {
365 get { return false; }
368 public bool IsLocal {
369 get { return IPAddress.IsLoopback (RemoteEndPoint.Address); }
372 public bool IsSecureConnection {
373 get { return context.Connection.IsSecure; }
376 public bool KeepAlive {
377 get { return false; }
380 public IPEndPoint LocalEndPoint {
381 get { return context.Connection.LocalEndPoint; }
384 public Version ProtocolVersion {
385 get { return version; }
388 public NameValueCollection QueryString {
389 get { return query_string; }
392 public string RawUrl {
393 get { return raw_url; }
396 public IPEndPoint RemoteEndPoint {
397 get { return context.Connection.RemoteEndPoint; }
400 public Guid RequestTraceIdentifier {
401 get { return identifier; }
408 public Uri UrlReferrer {
409 get { return referrer; }
412 public string UserAgent {
413 get { return headers ["user-agent"]; }
416 public string UserHostAddress {
417 get { return LocalEndPoint.ToString (); }
420 public string UserHostName {
421 get { return headers ["host"]; }
424 public string [] UserLanguages {
425 get { return user_languages; }
428 public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, Object state)
433 public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
436 // set no_client_certificate once done.
439 public X509Certificate2 GetClientCertificate ()
441 // set no_client_certificate once done.
443 // InvalidOp if call in progress.