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 #if MONO_SECURITY_ALIAS
32 extern alias MonoSecurity;
35 #if MONO_SECURITY_ALIAS
36 using MSI = MonoSecurity::Mono.Security.Interface;
38 using MSI = Mono.Security.Interface;
42 using System.Net.Sockets;
44 using System.Threading;
45 using System.Security.Authentication;
46 using System.Security.Cryptography;
47 using System.Security.Cryptography.X509Certificates;
48 using Mono.Net.Security;
50 namespace System.Net {
51 sealed class HttpConnection
53 static AsyncCallback onread_cb = new AsyncCallback (OnRead);
54 const int BufferSize = 8192;
60 HttpListenerContext context;
61 StringBuilder current_line;
62 ListenerPrefix prefix;
63 RequestStream i_stream;
64 ResponseStream o_stream;
70 int s_timeout = 90000; // 90k ms for first request, 15k ms from then on
73 HttpListener last_listener;
74 int [] client_cert_errors;
75 X509Certificate2 client_cert;
76 IMonoSslStream ssl_stream;
78 public HttpConnection (Socket sock, EndPointListener epl, bool secure, X509Certificate cert)
84 if (secure == false) {
85 stream = new NetworkStream (sock, false);
87 ssl_stream = epl.Listener.CreateSslStream (new NetworkStream (sock, false), false, (t, c, ch, e) => {
90 var c2 = c as X509Certificate2;
92 c2 = new X509Certificate2 (c.GetRawCertData ());
94 client_cert_errors = new int[] { (int)e };
97 stream = ssl_stream.AuthenticatedStream;
99 timer = new Timer (OnTimeout, null, Timeout.Infinite, Timeout.Infinite);
103 internal int [] ClientCertificateErrors {
104 get { return client_cert_errors; }
107 internal X509Certificate2 ClientCertificate {
108 get { return client_cert; }
113 if (ssl_stream != null) {
114 ssl_stream.AuthenticateAsServer (cert, true, (SslProtocols)ServicePointManager.SecurityProtocol, false);
117 context_bound = false;
122 ms = new MemoryStream ();
124 input_state = InputState.RequestLine;
125 line_state = LineState.None;
126 context = new HttpListenerContext (this);
129 public bool IsClosed {
130 get { return (sock == null); }
134 get { return reuses; }
137 public IPEndPoint LocalEndPoint {
139 if (local_ep != null)
142 local_ep = (IPEndPoint) sock.LocalEndPoint;
147 public IPEndPoint RemoteEndPoint {
148 get { return (IPEndPoint) sock.RemoteEndPoint; }
151 public bool IsSecure {
152 get { return secure; }
155 public ListenerPrefix Prefix {
156 get { return prefix; }
157 set { prefix = value; }
160 void OnTimeout (object unused)
166 public void BeginReadRequest ()
169 buffer = new byte [BufferSize];
173 timer.Change (s_timeout, Timeout.Infinite);
174 stream.BeginRead (buffer, 0, BufferSize, onread_cb, this);
176 timer.Change (Timeout.Infinite, Timeout.Infinite);
182 public RequestStream GetRequestStream (bool chunked, long contentlength)
184 if (i_stream == null) {
185 byte [] buffer = ms.GetBuffer ();
186 int length = (int) ms.Length;
190 context.Response.SendChunked = true;
191 i_stream = new ChunkedInputStream (context, stream, buffer, position, length - position);
193 i_stream = new RequestStream (stream, buffer, position, length - position, contentlength);
199 public ResponseStream GetResponseStream ()
201 // TODO: can we get this stream before reading the input?
202 if (o_stream == null) {
203 HttpListener listener = context.Listener;
206 return new ResponseStream (stream, context.Response, true);
208 o_stream = new ResponseStream (stream, context.Response, listener.IgnoreWriteExceptions);
213 static void OnRead (IAsyncResult ares)
215 HttpConnection cnc = (HttpConnection) ares.AsyncState;
216 cnc.OnReadInternal (ares);
219 void OnReadInternal (IAsyncResult ares)
221 timer.Change (Timeout.Infinite, Timeout.Infinite);
224 nread = stream.EndRead (ares);
225 ms.Write (buffer, 0, nread);
226 if (ms.Length > 32768) {
227 SendError ("Bad request", 400);
232 if (ms != null && ms.Length > 0)
243 // SendError (); // Why bother?
249 if (ProcessInput (ms)) {
250 if (!context.HaveError)
251 context.Request.FinishInitialization ();
253 if (context.HaveError) {
259 if (!epl.BindContext (context)) {
260 SendError ("Invalid host", 400);
264 HttpListener listener = context.Listener;
265 if (last_listener != listener) {
267 listener.AddConnection (this);
268 last_listener = listener;
271 context_bound = true;
272 listener.RegisterContext (context);
275 stream.BeginRead (buffer, 0, BufferSize, onread_cb, this);
278 void RemoveConnection ()
280 if (last_listener == null)
281 epl.RemoveConnection (this);
283 last_listener.RemoveConnection (this);
297 InputState input_state = InputState.RequestLine;
298 LineState line_state = LineState.None;
301 // true -> done processing
302 // false -> need more input
303 bool ProcessInput (MemoryStream ms)
305 byte [] buffer = ms.GetBuffer ();
306 int len = (int) ms.Length;
311 if (context.HaveError)
318 line = ReadLine (buffer, position, len - position, ref used);
321 context.ErrorMessage = "Bad request";
322 context.ErrorStatus = 400;
330 if (input_state == InputState.RequestLine)
337 if (input_state == InputState.RequestLine) {
338 context.Request.SetRequestLine (line);
339 input_state = InputState.Headers;
342 context.Request.AddHeader (line);
343 } catch (Exception e) {
344 context.ErrorMessage = e.Message;
345 context.ErrorStatus = 400;
358 string ReadLine (byte [] buffer, int offset, int len, ref int used)
360 if (current_line == null)
361 current_line = new StringBuilder (128);
362 int last = offset + len;
364 for (int i = offset; i < last && line_state != LineState.LF; i++) {
368 line_state = LineState.CR;
369 } else if (b == 10) {
370 line_state = LineState.LF;
372 current_line.Append ((char) b);
376 string result = null;
377 if (line_state == LineState.LF) {
378 line_state = LineState.None;
379 result = current_line.ToString ();
380 current_line.Length = 0;
386 public void SendError (string msg, int status)
389 HttpListenerResponse response = context.Response;
390 response.StatusCode = status;
391 response.ContentType = "text/html";
392 string description = HttpListenerResponseHelper.GetStatusDescription (status);
395 str = String.Format ("<h1>{0} ({1})</h1>", description, msg);
397 str = String.Format ("<h1>{0}</h1>", description);
399 byte [] error = context.Response.ContentEncoding.GetBytes (str);
400 response.Close (error, false);
402 // response was already closed
406 public void SendError ()
408 SendError (context.ErrorMessage, context.ErrorStatus);
414 epl.UnbindContext (context);
415 context_bound = false;
438 internal void Close (bool force_close)
441 Stream st = GetResponseStream ();
449 force_close |= !context.Request.KeepAlive;
451 force_close = (context.Response.Headers ["connection"] == "close");
454 // bool conn_close = (status_code == 400 || status_code == 408 || status_code == 411 ||
455 // status_code == 413 || status_code == 414 || status_code == 500 ||
456 // status_code == 503);
458 force_close |= (context.Request.ProtocolVersion <= HttpVersion.Version10);
462 if (!force_close && context.Request.FlushInput ()) {
463 if (chunked && context.Response.ForceCloseChunked == false) {
464 // Don't close. Keep working.
483 s.Shutdown (SocketShutdown.Both);