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");
62 internal HttpListenerRequest (HttpListenerContext context)
64 this.context = context;
65 headers = new WebHeaderCollection ();
66 input_stream = Stream.Null;
69 static char [] separators = new char [] { ' ' };
72 static readonly string [] methods = new string [] { "GET", "POST", "HEAD",
73 "PUT", "CONNECT", "MKCOL" };
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).";
83 method = parts [0].ToUpperInvariant ();
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)";
100 // According to bug #80504 we should allow any verbs to go
103 if (Array.IndexOf (methods, method) == -1) {
104 context.ErrorMessage = "Invalid request line (verb).";
110 if (parts [2].Length != 8 || !parts [2].StartsWith ("HTTP/")) {
111 context.ErrorMessage = "Invalid request line (version).";
116 version = new Version (parts [2].Substring (5));
117 if (version.Major < 1)
118 throw new Exception ();
120 context.ErrorMessage = "Invalid request line (version).";
125 void CreateQueryString (string query)
127 query_string = new NameValueCollection ();
128 if (query == null || query.Length == 0)
131 if (query [0] == '?')
132 query = query.Substring (1);
133 string [] components = query.Split ('&');
134 foreach (string kv in components) {
135 int pos = kv.IndexOf ('=');
137 query_string.Add (null, HttpUtility.UrlDecode (kv));
139 string key = HttpUtility.UrlDecode (kv.Substring (0, pos));
140 string val = HttpUtility.UrlDecode (kv.Substring (pos + 1));
142 query_string.Add (key, val);
147 internal void FinishInitialization ()
149 string host = UserHostName;
150 if (version > HttpVersion.Version10 && (host == null || host == "")) {
151 context.ErrorMessage = "Invalid host name";
155 if (host == null || host == "")
156 host = UserHostAddress;
158 int colon = host.IndexOf (':');
160 host = host.Substring (0, colon);
162 string base_uri = String.Format ("{0}://{1}:{2}",
163 (IsSecureConnection) ? "https" : "http",
167 url = new Uri (base_uri + raw_url);
169 context.ErrorMessage = "Invalid url";
173 CreateQueryString (url.Query);
175 if (method == "GET" || method == "HEAD" || method == "DELETE")
178 string t_encoding = null;
179 if (version >= HttpVersion.Version11) {
180 t_encoding = Headers ["Transfer-Encoding"];
181 // 'identity' is not valid!
182 if (t_encoding != null && t_encoding != "chunked") {
183 context.Connection.SendError (null, 501);
188 bool is_chunked = (t_encoding == "chunked");
189 if (!is_chunked && !cl_set) {
190 context.Connection.SendError (null, 411);
194 if (is_chunked || content_length > 0) {
195 input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
198 if (Headers ["Expect"] == "100-continue") {
199 ResponseStream output = context.Connection.GetResponseStream ();
200 output.InternalWrite (_100continue, 0, _100continue.Length);
204 internal static string Unquote (String str) {
205 int start = str.IndexOf ('\"');
206 int end = str.LastIndexOf ('\"');
207 if (start >= 0 && end >=0)
208 str = str.Substring (start + 1, end - 1);
212 internal void AddHeader (string header)
214 int colon = header.IndexOf (':');
215 if (colon == -1 || colon == 0) {
216 context.ErrorMessage = "Bad Request";
220 string name = header.Substring (0, colon).Trim ();
221 string val = header.Substring (colon + 1).Trim ();
222 string lower = name.ToLower (CultureInfo.InvariantCulture);
223 headers.SetInternal (name, val);
225 case "accept-language":
226 user_languages = val.Split (','); // yes, only split with a ','
229 accept_types = val.Split (','); // yes, only split with a ','
231 case "content-length":
233 //TODO: max. content_length?
234 content_length = Int64.Parse (val.Trim ());
235 if (content_length < 0)
236 context.ErrorMessage = "Invalid Content-Length.";
239 context.ErrorMessage = "Invalid Content-Length.";
245 referrer = new Uri (val);
247 referrer = new Uri ("http://someone.is.screwing.with.the.headers.com/");
252 cookies = new CookieCollection();
254 string[] cookieStrings = val.Split(new char[] {',', ';'});
255 Cookie current = null;
257 foreach (string cookieString in cookieStrings) {
258 string str = cookieString.Trim ();
261 if (str.StartsWith ("$Version")) {
262 version = Int32.Parse (Unquote (str.Substring (str.IndexOf ("=") + 1)));
263 } else if (str.StartsWith ("$Path")) {
265 current.Path = str.Substring (str.IndexOf ("=") + 1).Trim ();
266 } else if (str.StartsWith ("$Domain")) {
268 current.Domain = str.Substring (str.IndexOf ("=") + 1).Trim ();
269 } else if (str.StartsWith ("$Port")) {
271 current.Port = str.Substring (str.IndexOf ("=") + 1).Trim ();
273 if (current != null) {
274 cookies.Add (current);
276 current = new Cookie ();
277 int idx = str.IndexOf ("=");
279 current.Name = str.Substring (0, idx).Trim ();
280 current.Value = str.Substring (idx + 1).Trim ();
282 current.Name = str.Trim ();
283 current.Value = String.Empty;
285 current.Version = version;
288 if (current != null) {
289 cookies.Add (current);
295 public string [] AcceptTypes {
296 get { return accept_types; }
299 public int ClientCertificateError {
301 if (no_get_certificate)
302 throw new InvalidOperationException (
303 "Call GetClientCertificate() before calling this method.");
304 return client_cert_error;
308 public Encoding ContentEncoding {
310 if (content_encoding == null)
311 content_encoding = Encoding.Default;
312 return content_encoding;
316 public long ContentLength64 {
317 get { return content_length; }
320 public string ContentType {
321 get { return headers ["content-type"]; }
324 public CookieCollection Cookies {
326 // TODO: check if the collection is read-only
328 cookies = new CookieCollection ();
333 public bool HasEntityBody {
334 get { return !(method == "GET" || method == "HEAD" || content_length <= 0 || is_chunked); }
337 public NameValueCollection Headers {
338 get { return headers; }
341 public string HttpMethod {
342 get { return method; }
345 public Stream InputStream {
346 get { return input_stream; }
349 public bool IsAuthenticated {
350 get { return is_authenticated; }
353 public bool IsLocal {
354 get { return IPAddress.IsLoopback (RemoteEndPoint.Address); }
357 public bool IsSecureConnection {
358 get { return context.Connection.IsSecure; }
361 public bool KeepAlive {
362 get { return false; }
365 public IPEndPoint LocalEndPoint {
366 get { return context.Connection.LocalEndPoint; }
369 public Version ProtocolVersion {
370 get { return version; }
373 public NameValueCollection QueryString {
374 get { return query_string; }
377 public string RawUrl {
378 get { return raw_url; }
381 public IPEndPoint RemoteEndPoint {
382 get { return context.Connection.RemoteEndPoint; }
385 public Guid RequestTraceIdentifier {
386 get { return identifier; }
393 public Uri UrlReferrer {
394 get { return referrer; }
397 public string UserAgent {
398 get { return headers ["user-agent"]; }
401 public string UserHostAddress {
402 get { return LocalEndPoint.ToString (); }
405 public string UserHostName {
406 get { return headers ["host"]; }
409 public string [] UserLanguages {
410 get { return user_languages; }
413 public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, Object state)
418 public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
421 // set no_client_certificate once done.
424 public X509Certificate2 GetClientCertificate ()
426 // set no_client_certificate once done.
428 // InvalidOp if call in progress.