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 Encoding content_encoding;
45 CookieCollection cookies;
46 WebHeaderCollection headers;
49 bool is_authenticated;
51 NameValueCollection query_string; // check if null is ok, check if read-only, check case-sensitiveness
56 string [] user_languages;
57 bool no_get_certificate;
58 HttpListenerContext context;
60 static byte [] _100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n");
61 static readonly string [] no_body_methods = new string [] {
62 "GET", "HEAD", "DELETE" };
64 internal HttpListenerRequest (HttpListenerContext context)
66 this.context = context;
67 headers = new WebHeaderCollection ();
68 input_stream = Stream.Null;
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";
142 if (host == null || host.Length == 0)
143 host = UserHostAddress;
145 int colon = host.IndexOf (':');
147 host = host.Substring (0, colon);
149 string base_uri = String.Format ("{0}://{1}:{2}",
150 (IsSecureConnection) ? "https" : "http",
154 url = new Uri (base_uri + raw_url);
156 context.ErrorMessage = "Invalid url";
160 CreateQueryString (url.Query);
162 string t_encoding = null;
163 if (version >= HttpVersion.Version11) {
164 t_encoding = Headers ["Transfer-Encoding"];
165 // 'identity' is not valid!
166 if (t_encoding != null && t_encoding != "chunked") {
167 context.Connection.SendError (null, 501);
172 is_chunked = (t_encoding == "chunked");
174 foreach (string m in no_body_methods)
175 if (string.Compare (method, m, StringComparison.InvariantCultureIgnoreCase) == 0)
178 if (!is_chunked && !cl_set) {
179 context.Connection.SendError (null, 411);
183 if (is_chunked || content_length > 0) {
184 input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
187 if (Headers ["Expect"] == "100-continue") {
188 ResponseStream output = context.Connection.GetResponseStream ();
189 output.InternalWrite (_100continue, 0, _100continue.Length);
193 internal static string Unquote (String str) {
194 int start = str.IndexOf ('\"');
195 int end = str.LastIndexOf ('\"');
196 if (start >= 0 && end >=0)
197 str = str.Substring (start + 1, end - 1);
201 internal void AddHeader (string header)
203 int colon = header.IndexOf (':');
204 if (colon == -1 || colon == 0) {
205 context.ErrorMessage = "Bad Request";
209 string name = header.Substring (0, colon).Trim ();
210 string val = header.Substring (colon + 1).Trim ();
211 string lower = name.ToLower (CultureInfo.InvariantCulture);
212 headers.SetInternal (name, val);
214 case "accept-language":
215 user_languages = val.Split (','); // yes, only split with a ','
218 accept_types = val.Split (','); // yes, only split with a ','
220 case "content-length":
222 //TODO: max. content_length?
223 content_length = Int64.Parse (val.Trim ());
224 if (content_length < 0)
225 context.ErrorMessage = "Invalid Content-Length.";
228 context.ErrorMessage = "Invalid Content-Length.";
234 referrer = new Uri (val);
236 referrer = new Uri ("http://someone.is.screwing.with.the.headers.com/");
241 cookies = new CookieCollection();
243 string[] cookieStrings = val.Split(new char[] {',', ';'});
244 Cookie current = null;
246 foreach (string cookieString in cookieStrings) {
247 string str = cookieString.Trim ();
250 if (str.StartsWith ("$Version")) {
251 version = Int32.Parse (Unquote (str.Substring (str.IndexOf ("=") + 1)));
252 } else if (str.StartsWith ("$Path")) {
254 current.Path = str.Substring (str.IndexOf ("=") + 1).Trim ();
255 } else if (str.StartsWith ("$Domain")) {
257 current.Domain = str.Substring (str.IndexOf ("=") + 1).Trim ();
258 } else if (str.StartsWith ("$Port")) {
260 current.Port = str.Substring (str.IndexOf ("=") + 1).Trim ();
262 if (current != null) {
263 cookies.Add (current);
265 current = new Cookie ();
266 int idx = str.IndexOf ("=");
268 current.Name = str.Substring (0, idx).Trim ();
269 current.Value = str.Substring (idx + 1).Trim ();
271 current.Name = str.Trim ();
272 current.Value = String.Empty;
274 current.Version = version;
277 if (current != null) {
278 cookies.Add (current);
284 public string [] AcceptTypes {
285 get { return accept_types; }
288 public int ClientCertificateError {
290 if (no_get_certificate)
291 throw new InvalidOperationException (
292 "Call GetClientCertificate() before calling this method.");
293 return client_cert_error;
297 public Encoding ContentEncoding {
299 if (content_encoding == null)
300 content_encoding = Encoding.Default;
301 return content_encoding;
305 public long ContentLength64 {
306 get { return content_length; }
309 public string ContentType {
310 get { return headers ["content-type"]; }
313 public CookieCollection Cookies {
315 // TODO: check if the collection is read-only
317 cookies = new CookieCollection ();
322 public bool HasEntityBody {
323 get { return (content_length > 0 || is_chunked); }
326 public NameValueCollection Headers {
327 get { return headers; }
330 public string HttpMethod {
331 get { return method; }
334 public Stream InputStream {
335 get { return input_stream; }
338 public bool IsAuthenticated {
339 get { return is_authenticated; }
342 public bool IsLocal {
343 get { return IPAddress.IsLoopback (RemoteEndPoint.Address); }
346 public bool IsSecureConnection {
347 get { return context.Connection.IsSecure; }
350 public bool KeepAlive {
351 get { return false; }
354 public IPEndPoint LocalEndPoint {
355 get { return context.Connection.LocalEndPoint; }
358 public Version ProtocolVersion {
359 get { return version; }
362 public NameValueCollection QueryString {
363 get { return query_string; }
366 public string RawUrl {
367 get { return raw_url; }
370 public IPEndPoint RemoteEndPoint {
371 get { return context.Connection.RemoteEndPoint; }
374 public Guid RequestTraceIdentifier {
375 get { return identifier; }
382 public Uri UrlReferrer {
383 get { return referrer; }
386 public string UserAgent {
387 get { return headers ["user-agent"]; }
390 public string UserHostAddress {
391 get { return LocalEndPoint.ToString (); }
394 public string UserHostName {
395 get { return headers ["host"]; }
398 public string [] UserLanguages {
399 get { return user_languages; }
402 public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, Object state)
407 public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
410 // set no_client_certificate once done.
413 public X509Certificate2 GetClientCertificate ()
415 // set no_client_certificate once done.
417 // InvalidOp if call in progress.