2 // System.Net.HttpConnection
5 // Gonzalo Paniagua Javier (gonzalo.mono@gmail.com)
7 // Copyright (c) 2005-2009 Novell, Inc. (http://www.novell.com)
8 // Copyright (c) 2012 Xamarin, Inc. (http://xamarin.com)
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 using System.Net.Sockets;
33 using System.Threading;
34 using System.Net.Security;
35 using System.Security.Authentication;
36 using System.Security.Cryptography;
37 using System.Security.Cryptography.X509Certificates;
39 namespace System.Net {
40 sealed class HttpConnection {
41 static AsyncCallback onread_cb = new AsyncCallback (OnRead);
42 const int BufferSize = 8192;
48 HttpListenerContext context;
49 StringBuilder current_line;
50 ListenerPrefix prefix;
51 RequestStream i_stream;
52 ResponseStream o_stream;
58 int s_timeout = 90000; // 90k ms for first request, 15k ms from then on
61 HttpListener last_listener;
62 int [] client_cert_errors;
63 X509Certificate2 client_cert;
66 public HttpConnection (Socket sock, EndPointListener epl, bool secure, X509Certificate cert)
72 if (secure == false) {
73 stream = new NetworkStream (sock, false);
75 ssl_stream = epl.Listener.CreateSslStream (new NetworkStream (sock, false), false, (t, c, ch, e) => {
78 var c2 = c as X509Certificate2;
80 c2 = new X509Certificate2 (c.GetRawCertData ());
82 client_cert_errors = new int[] { (int)e };
87 timer = new Timer (OnTimeout, null, Timeout.Infinite, Timeout.Infinite);
88 if (ssl_stream != null)
89 ssl_stream.AuthenticateAsServer (cert, true, (SslProtocols)ServicePointManager.SecurityProtocol, false);
93 internal SslStream SslStream {
94 get { return ssl_stream; }
97 internal int [] ClientCertificateErrors {
98 get { return client_cert_errors; }
101 internal X509Certificate2 ClientCertificate {
102 get { return client_cert; }
107 context_bound = false;
112 ms = new MemoryStream ();
114 input_state = InputState.RequestLine;
115 line_state = LineState.None;
116 context = new HttpListenerContext (this);
119 public bool IsClosed {
120 get { return (sock == null); }
124 get { return reuses; }
127 public IPEndPoint LocalEndPoint {
129 if (local_ep != null)
132 local_ep = (IPEndPoint) sock.LocalEndPoint;
137 public IPEndPoint RemoteEndPoint {
138 get { return (IPEndPoint) sock.RemoteEndPoint; }
141 public bool IsSecure {
142 get { return secure; }
145 public ListenerPrefix Prefix {
146 get { return prefix; }
147 set { prefix = value; }
150 void OnTimeout (object unused)
156 public void BeginReadRequest ()
159 buffer = new byte [BufferSize];
163 timer.Change (s_timeout, Timeout.Infinite);
164 stream.BeginRead (buffer, 0, BufferSize, onread_cb, this);
166 timer.Change (Timeout.Infinite, Timeout.Infinite);
172 public RequestStream GetRequestStream (bool chunked, long contentlength)
174 if (i_stream == null) {
175 byte [] buffer = ms.GetBuffer ();
176 int length = (int) ms.Length;
180 context.Response.SendChunked = true;
181 i_stream = new ChunkedInputStream (context, stream, buffer, position, length - position);
183 i_stream = new RequestStream (stream, buffer, position, length - position, contentlength);
189 public ResponseStream GetResponseStream ()
191 // TODO: can we get this stream before reading the input?
192 if (o_stream == null) {
193 HttpListener listener = context.Listener;
196 return new ResponseStream (stream, context.Response, true);
198 o_stream = new ResponseStream (stream, context.Response, listener.IgnoreWriteExceptions);
203 static void OnRead (IAsyncResult ares)
205 HttpConnection cnc = (HttpConnection) ares.AsyncState;
206 cnc.OnReadInternal (ares);
209 void OnReadInternal (IAsyncResult ares)
211 timer.Change (Timeout.Infinite, Timeout.Infinite);
214 nread = stream.EndRead (ares);
215 ms.Write (buffer, 0, nread);
216 if (ms.Length > 32768) {
217 SendError ("Bad request", 400);
222 if (ms != null && ms.Length > 0)
233 // SendError (); // Why bother?
239 if (ProcessInput (ms)) {
240 if (!context.HaveError)
241 context.Request.FinishInitialization ();
243 if (context.HaveError) {
249 if (!epl.BindContext (context)) {
250 SendError ("Invalid host", 400);
254 HttpListener listener = context.Listener;
255 if (last_listener != listener) {
257 listener.AddConnection (this);
258 last_listener = listener;
261 context_bound = true;
262 listener.RegisterContext (context);
265 stream.BeginRead (buffer, 0, BufferSize, onread_cb, this);
268 void RemoveConnection ()
270 if (last_listener == null)
271 epl.RemoveConnection (this);
273 last_listener.RemoveConnection (this);
287 InputState input_state = InputState.RequestLine;
288 LineState line_state = LineState.None;
291 // true -> done processing
292 // false -> need more input
293 bool ProcessInput (MemoryStream ms)
295 byte [] buffer = ms.GetBuffer ();
296 int len = (int) ms.Length;
301 if (context.HaveError)
308 line = ReadLine (buffer, position, len - position, ref used);
311 context.ErrorMessage = "Bad request";
312 context.ErrorStatus = 400;
320 if (input_state == InputState.RequestLine)
327 if (input_state == InputState.RequestLine) {
328 context.Request.SetRequestLine (line);
329 input_state = InputState.Headers;
332 context.Request.AddHeader (line);
333 } catch (Exception e) {
334 context.ErrorMessage = e.Message;
335 context.ErrorStatus = 400;
348 string ReadLine (byte [] buffer, int offset, int len, ref int used)
350 if (current_line == null)
351 current_line = new StringBuilder (128);
352 int last = offset + len;
354 for (int i = offset; i < last && line_state != LineState.LF; i++) {
358 line_state = LineState.CR;
359 } else if (b == 10) {
360 line_state = LineState.LF;
362 current_line.Append ((char) b);
366 string result = null;
367 if (line_state == LineState.LF) {
368 line_state = LineState.None;
369 result = current_line.ToString ();
370 current_line.Length = 0;
376 public void SendError (string msg, int status)
379 HttpListenerResponse response = context.Response;
380 response.StatusCode = status;
381 response.ContentType = "text/html";
382 string description = HttpStatusDescription.Get (status);
385 str = String.Format ("<h1>{0} ({1})</h1>", description, msg);
387 str = String.Format ("<h1>{0}</h1>", description);
389 byte [] error = context.Response.ContentEncoding.GetBytes (str);
390 response.Close (error, false);
392 // response was already closed
396 public void SendError ()
398 SendError (context.ErrorMessage, context.ErrorStatus);
404 epl.UnbindContext (context);
405 context_bound = false;
428 internal void Close (bool force_close)
431 Stream st = GetResponseStream ();
439 force_close |= !context.Request.KeepAlive;
441 force_close = (context.Response.Headers ["connection"] == "close");
444 // bool conn_close = (status_code == 400 || status_code == 408 || status_code == 411 ||
445 // status_code == 413 || status_code == 414 || status_code == 500 ||
446 // status_code == 503);
448 force_close |= (context.Request.ProtocolVersion <= HttpVersion.Version10);
452 if (!force_close && context.Request.FlushInput ()) {
453 if (chunked && context.Response.ForceCloseChunked == false) {
454 // Don't close. Keep working.
473 s.Shutdown (SocketShutdown.Both);