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 using System.Collections;
30 using System.Collections.Specialized;
31 using System.Globalization;
33 using System.Security.Cryptography.X509Certificates;
35 namespace System.Net {
36 public sealed class HttpListenerRequest
38 string [] accept_types;
39 int client_cert_error;
40 Encoding content_encoding;
43 CookieCollection cookies;
44 WebHeaderCollection headers;
47 bool is_authenticated;
49 NameValueCollection query_string; // check if null is ok, check if read-only, check case-sensitiveness
54 string [] user_languages;
55 bool no_get_certificate;
56 HttpListenerContext context;
58 static byte [] _100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n");
60 internal HttpListenerRequest (HttpListenerContext context)
62 this.context = context;
63 headers = new WebHeaderCollection ();
64 input_stream = Stream.Null;
67 static char [] separators = new char [] { ' ' };
68 // From WebRequestMethods.Http
69 static readonly string [] methods = new string [] { "GET", "POST", "HEAD",
70 "PUT", "CONNECT", "MKCOL" };
71 internal void SetRequestLine (string req)
73 string [] parts = req.Split (separators, 3);
74 if (parts.Length != 3) {
75 context.ErrorMessage = "Invalid request line (parts).";
80 if (Array.IndexOf (methods, method) == -1) {
81 context.ErrorMessage = "Invalid request line (verb).";
86 if (parts [2].Length != 8 || !parts [2].StartsWith ("HTTP/")) {
87 context.ErrorMessage = "Invalid request line (version).";
92 version = new Version (parts [2].Substring (5));
93 if (version.Major < 1)
94 throw new Exception ();
96 context.ErrorMessage = "Invalid request line (version).";
101 void CreateQueryString (string query)
103 query_string = new NameValueCollection ();
104 if (query == null || query.Length == 0)
107 string [] components = query.Split ('&');
108 foreach (string kv in components) {
109 int pos = kv.IndexOf ('=');
111 query_string.Add (null, HttpUtility.UrlDecode (kv));
113 string key = HttpUtility.UrlDecode (kv.Substring (0, pos));
114 string val = HttpUtility.UrlDecode (kv.Substring (pos + 1));
116 query_string.Add (key, val);
121 internal void FinishInitialization ()
123 string host = UserHostName;
124 if (version > HttpVersion.Version10 && (host == null || host == "")) {
125 context.ErrorMessage = "Invalid host name";
129 if (host == null || host == "")
130 host = UserHostAddress;
132 int colon = host.IndexOf (':');
134 host = host.Substring (0, colon);
136 string base_uri = String.Format ("{0}://{1}:{2}",
137 (IsSecureConnection) ? "https" : "http",
141 url = new Uri (base_uri + raw_url);
143 context.ErrorMessage = "Invalid url";
147 CreateQueryString (url.Query);
149 if (method == "GET" || method == "HEAD")
152 string t_encoding = null;
153 if (version >= HttpVersion.Version11) {
154 t_encoding = Headers ["Transfer-Encoding"];
155 // 'identity' is not valid!
156 if (t_encoding != null && t_encoding != "chunked") {
157 context.Connection.SendError (null, 501);
162 bool is_chunked = (t_encoding == "chunked");
163 if (!is_chunked && !cl_set) {
164 context.Connection.SendError (null, 411);
168 if (is_chunked || content_length > 0) {
169 input_stream = context.Connection.GetRequestStream (is_chunked, content_length);
172 if (Headers ["Expect"] == "100-continue") {
173 ResponseStream output = context.Connection.GetResponseStream ();
174 output.InternalWrite (_100continue, 0, _100continue.Length);
178 internal void AddHeader (string header)
180 int colon = header.IndexOf (':');
181 if (colon == -1 || colon == 0) {
182 context.ErrorMessage = "Bad Request";
186 string name = header.Substring (0, colon).Trim ();
187 string val = header.Substring (colon + 1).Trim ();
188 string lower = name.ToLower (CultureInfo.InvariantCulture);
189 headers.SetInternal (name, val);
191 case "accept-language":
192 user_languages = val.Split (','); // yes, only split with a ','
195 accept_types = val.Split (','); // yes, only split with a ','
197 case "content-length":
199 //TODO: max. content_length?
200 content_length = Int64.Parse (val.Trim ());
201 if (content_length < 0)
202 context.ErrorMessage = "Invalid Content-Length.";
205 context.ErrorMessage = "Invalid Content-Length.";
211 referrer = new Uri (val);
213 referrer = new Uri ("http://someone.is.screwing.with.the.headers.com/");
216 //TODO: cookie headers
220 public string [] AcceptTypes {
221 get { return accept_types; }
224 public int ClientCertificateError {
226 if (no_get_certificate)
227 throw new InvalidOperationException (
228 "Call GetClientCertificate() before calling this method.");
229 return client_cert_error;
233 public Encoding ContentEncoding {
235 if (content_encoding == null)
236 content_encoding = Encoding.Default;
237 return content_encoding;
241 public long ContentLength64 {
242 get { return content_length; }
245 public string ContentType {
246 get { return headers ["content-type"]; }
249 public CookieCollection Cookies {
251 // TODO: check if the collection is read-only
253 cookies = new CookieCollection ();
258 public bool HasEntityBody {
259 get { return (method == "GET" || method == "HEAD" || content_length <= 0 || is_chunked); }
262 public NameValueCollection Headers {
263 get { return headers; }
266 public string HttpMethod {
267 get { return method; }
270 public Stream InputStream {
271 get { return input_stream; }
274 public bool IsAuthenticated {
275 get { return is_authenticated; }
278 public bool IsLocal {
279 get { return IPAddress.IsLoopback (RemoteEndPoint.Address); }
282 public bool IsSecureConnection {
283 get { return context.Connection.IsSecure; }
286 public bool KeepAlive {
287 get { return false; }
290 public IPEndPoint LocalEndPoint {
291 get { return context.Connection.LocalEndPoint; }
294 public Version ProtocolVersion {
295 get { return version; }
298 public NameValueCollection QueryString {
299 get { return query_string; }
302 public string RawUrl {
303 get { return raw_url; }
306 public IPEndPoint RemoteEndPoint {
307 get { return context.Connection.RemoteEndPoint; }
310 public Guid RequestTraceIdentifier {
311 get { return identifier; }
318 public Uri UrlReferrer {
319 get { return referrer; }
322 public string UserAgent {
323 get { return headers ["user-agent"]; }
326 public string UserHostAddress {
327 get { return LocalEndPoint.ToString (); }
330 public string UserHostName {
331 get { return headers ["host"]; }
334 public string [] UserLanguages {
335 get { return user_languages; }
338 public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, Object state)
343 public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
346 // set no_client_certificate once done.
349 public X509Certificate2 GetClientCertificate ()
351 // set no_client_certificate once done.
353 // InvalidOp if call in progress.