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.
32 extern alias MonoSecurity;
35 using System.Net.Sockets;
36 using System.Reflection;
38 using System.Threading;
39 using System.Security.Cryptography;
40 using System.Security.Cryptography.X509Certificates;
41 using MonoSecurity::Mono.Security.Protocol.Tls;
43 namespace System.Net {
44 sealed class HttpConnection
46 static AsyncCallback onread_cb = new AsyncCallback (OnRead);
47 const int BufferSize = 8192;
53 HttpListenerContext context;
54 StringBuilder current_line;
55 ListenerPrefix prefix;
56 RequestStream i_stream;
57 ResponseStream o_stream;
62 AsymmetricAlgorithm key;
63 int s_timeout = 90000; // 90k ms for first request, 15k ms from then on
66 HttpListener last_listener;
67 int [] client_cert_errors;
68 X509Certificate2 client_cert;
70 public HttpConnection (Socket sock, EndPointListener epl, bool secure, X509Certificate2 cert, AsymmetricAlgorithm key)
76 if (secure == false) {
77 stream = new NetworkStream (sock, false);
79 SslServerStream ssl_stream = new SslServerStream (new NetworkStream (sock, false), cert, false, true, false);
80 ssl_stream.PrivateKeyCertSelectionDelegate += OnPVKSelection;
81 ssl_stream.ClientCertValidationDelegate += OnClientCertificateValidation;
84 timer = new Timer (OnTimeout, null, Timeout.Infinite, Timeout.Infinite);
88 internal int [] ClientCertificateErrors {
89 get { return client_cert_errors; }
92 internal X509Certificate2 ClientCertificate {
93 get { return client_cert; }
96 bool OnClientCertificateValidation (X509Certificate certificate, int[] errors)
98 if (certificate == null)
100 X509Certificate2 cert = certificate as X509Certificate2;
102 cert = new X509Certificate2 (certificate.GetRawCertData ());
104 client_cert_errors = errors;
108 AsymmetricAlgorithm OnPVKSelection (X509Certificate certificate, string targetHost)
115 context_bound = false;
120 ms = new MemoryStream ();
122 input_state = InputState.RequestLine;
123 line_state = LineState.None;
124 context = new HttpListenerContext (this);
127 public bool IsClosed {
128 get { return (sock == null); }
132 get { return reuses; }
135 public IPEndPoint LocalEndPoint {
137 if (local_ep != null)
140 local_ep = (IPEndPoint) sock.LocalEndPoint;
145 public IPEndPoint RemoteEndPoint {
146 get { return (IPEndPoint) sock.RemoteEndPoint; }
149 public bool IsSecure {
150 get { return secure; }
153 public ListenerPrefix Prefix {
154 get { return prefix; }
155 set { prefix = value; }
158 void OnTimeout (object unused)
164 public void BeginReadRequest ()
167 buffer = new byte [BufferSize];
171 timer.Change (s_timeout, Timeout.Infinite);
172 stream.BeginRead (buffer, 0, BufferSize, onread_cb, this);
174 timer.Change (Timeout.Infinite, Timeout.Infinite);
180 public RequestStream GetRequestStream (bool chunked, long contentlength)
182 if (i_stream == null) {
183 byte [] buffer = ms.GetBuffer ();
184 int length = (int) ms.Length;
188 context.Response.SendChunked = true;
189 i_stream = new ChunkedInputStream (context, stream, buffer, position, length - position);
191 i_stream = new RequestStream (stream, buffer, position, length - position, contentlength);
197 public ResponseStream GetResponseStream ()
199 // TODO: can we get this stream before reading the input?
200 if (o_stream == null) {
201 HttpListener listener = context.Listener;
202 bool ign = (listener == null) ? true : listener.IgnoreWriteExceptions;
203 o_stream = new ResponseStream (stream, context.Response, ign);
208 static void OnRead (IAsyncResult ares)
210 HttpConnection cnc = (HttpConnection) ares.AsyncState;
211 cnc.OnReadInternal (ares);
214 void OnReadInternal (IAsyncResult ares)
216 timer.Change (Timeout.Infinite, Timeout.Infinite);
219 nread = stream.EndRead (ares);
220 ms.Write (buffer, 0, nread);
221 if (ms.Length > 32768) {
222 SendError ("Bad request", 400);
227 if (ms != null && ms.Length > 0)
238 // SendError (); // Why bother?
244 if (ProcessInput (ms)) {
245 if (!context.HaveError)
246 context.Request.FinishInitialization ();
248 if (context.HaveError) {
254 if (!epl.BindContext (context)) {
255 SendError ("Invalid host", 400);
259 HttpListener listener = context.Listener;
260 if (last_listener != listener) {
262 listener.AddConnection (this);
263 last_listener = listener;
266 context_bound = true;
267 listener.RegisterContext (context);
270 stream.BeginRead (buffer, 0, BufferSize, onread_cb, this);
273 void RemoveConnection ()
275 if (last_listener == null)
276 epl.RemoveConnection (this);
278 last_listener.RemoveConnection (this);
292 InputState input_state = InputState.RequestLine;
293 LineState line_state = LineState.None;
296 // true -> done processing
297 // false -> need more input
298 bool ProcessInput (MemoryStream ms)
300 byte [] buffer = ms.GetBuffer ();
301 int len = (int) ms.Length;
306 line = ReadLine (buffer, position, len - position, ref used);
309 context.ErrorMessage = "Bad request";
310 context.ErrorStatus = 400;
318 if (input_state == InputState.RequestLine)
325 if (input_state == InputState.RequestLine) {
326 context.Request.SetRequestLine (line);
327 input_state = InputState.Headers;
330 context.Request.AddHeader (line);
331 } catch (Exception e) {
332 context.ErrorMessage = e.Message;
333 context.ErrorStatus = 400;
338 if (context.HaveError)
344 line = ReadLine (buffer, position, len - position, ref used);
347 context.ErrorMessage = "Bad request";
348 context.ErrorStatus = 400;
351 } while (line != null);
360 string ReadLine (byte [] buffer, int offset, int len, ref int used)
362 if (current_line == null)
363 current_line = new StringBuilder (128);
364 int last = offset + len;
366 for (int i = offset; i < last && line_state != LineState.LF; i++) {
370 line_state = LineState.CR;
371 } else if (b == 10) {
372 line_state = LineState.LF;
374 current_line.Append ((char) b);
378 string result = null;
379 if (line_state == LineState.LF) {
380 line_state = LineState.None;
381 result = current_line.ToString ();
382 current_line.Length = 0;
388 public void SendError (string msg, int status)
391 HttpListenerResponse response = context.Response;
392 response.StatusCode = status;
393 response.ContentType = "text/html";
394 string description = HttpListenerResponse.GetStatusDescription (status);
397 str = String.Format ("<h1>{0} ({1})</h1>", description, msg);
399 str = String.Format ("<h1>{0}</h1>", description);
401 byte [] error = context.Response.ContentEncoding.GetBytes (str);
402 response.Close (error, false);
404 // response was already closed
408 public void SendError ()
410 SendError (context.ErrorMessage, context.ErrorStatus);
416 epl.UnbindContext (context);
417 context_bound = false;
440 internal void Close (bool force_close)
443 Stream st = GetResponseStream ();
451 force_close |= !context.Request.KeepAlive;
453 force_close = (context.Response.Headers ["connection"] == "close");
456 // bool conn_close = (status_code == 400 || status_code == 408 || status_code == 411 ||
457 // status_code == 413 || status_code == 414 || status_code == 500 ||
458 // status_code == 503);
460 force_close |= (context.Request.ProtocolVersion <= HttpVersion.Version10);
464 if (!force_close && context.Request.FlushInput ()) {
465 if (chunked && context.Response.ForceCloseChunked == false) {
466 // Don't close. Keep working.
485 s.Shutdown (SocketShutdown.Both);