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.
33 using System.Net.Sockets;
34 using System.Reflection;
36 using System.Threading;
37 using System.Security.Cryptography;
38 using System.Security.Cryptography.X509Certificates;
39 using Mono.Security.Protocol.Tls;
41 namespace System.Net {
42 sealed class HttpConnection
44 static AsyncCallback onread_cb = new AsyncCallback (OnRead);
45 const int BufferSize = 8192;
51 HttpListenerContext context;
52 StringBuilder current_line;
53 ListenerPrefix prefix;
54 RequestStream i_stream;
55 ResponseStream o_stream;
60 AsymmetricAlgorithm key;
61 int s_timeout = 90000; // 90k ms for first request, 15k ms from then on
64 HttpListener last_listener;
65 int [] client_cert_errors;
66 X509Certificate2 client_cert;
68 public HttpConnection (Socket sock, EndPointListener epl, bool secure, X509Certificate2 cert, AsymmetricAlgorithm key)
74 if (secure == false) {
75 stream = new NetworkStream (sock, false);
77 SslServerStream ssl_stream = new SslServerStream (new NetworkStream (sock, false), cert, false, true, false);
78 ssl_stream.PrivateKeyCertSelectionDelegate += OnPVKSelection;
79 ssl_stream.ClientCertValidationDelegate += OnClientCertificateValidation;
82 timer = new Timer (OnTimeout, null, Timeout.Infinite, Timeout.Infinite);
86 internal int [] ClientCertificateErrors {
87 get { return client_cert_errors; }
90 internal X509Certificate2 ClientCertificate {
91 get { return client_cert; }
94 bool OnClientCertificateValidation (X509Certificate certificate, int[] errors)
96 if (certificate == null)
98 X509Certificate2 cert = certificate as X509Certificate2;
100 cert = new X509Certificate2 (certificate.GetRawCertData ());
102 client_cert_errors = errors;
106 AsymmetricAlgorithm OnPVKSelection (X509Certificate certificate, string targetHost)
113 context_bound = false;
118 ms = new MemoryStream ();
120 input_state = InputState.RequestLine;
121 line_state = LineState.None;
122 context = new HttpListenerContext (this);
125 public bool IsClosed {
126 get { return (sock == null); }
130 get { return reuses; }
133 public IPEndPoint LocalEndPoint {
135 if (local_ep != null)
138 local_ep = (IPEndPoint) sock.LocalEndPoint;
143 public IPEndPoint RemoteEndPoint {
144 get { return (IPEndPoint) sock.RemoteEndPoint; }
147 public bool IsSecure {
148 get { return secure; }
151 public ListenerPrefix Prefix {
152 get { return prefix; }
153 set { prefix = value; }
156 void OnTimeout (object unused)
162 public void BeginReadRequest ()
165 buffer = new byte [BufferSize];
169 timer.Change (s_timeout, Timeout.Infinite);
170 stream.BeginRead (buffer, 0, BufferSize, onread_cb, this);
172 timer.Change (Timeout.Infinite, Timeout.Infinite);
178 public RequestStream GetRequestStream (bool chunked, long contentlength)
180 if (i_stream == null) {
181 byte [] buffer = ms.GetBuffer ();
182 int length = (int) ms.Length;
186 context.Response.SendChunked = true;
187 i_stream = new ChunkedInputStream (context, stream, buffer, position, length - position);
189 i_stream = new RequestStream (stream, buffer, position, length - position, contentlength);
195 public ResponseStream GetResponseStream ()
197 // TODO: can we get this stream before reading the input?
198 if (o_stream == null) {
199 HttpListener listener = context.Listener;
200 bool ign = (listener == null) ? true : listener.IgnoreWriteExceptions;
201 o_stream = new ResponseStream (stream, context.Response, ign);
206 static void OnRead (IAsyncResult ares)
208 HttpConnection cnc = (HttpConnection) ares.AsyncState;
209 cnc.OnReadInternal (ares);
212 void OnReadInternal (IAsyncResult ares)
214 timer.Change (Timeout.Infinite, Timeout.Infinite);
217 nread = stream.EndRead (ares);
218 ms.Write (buffer, 0, nread);
219 if (ms.Length > 32768) {
220 SendError ("Bad request", 400);
225 if (ms != null && ms.Length > 0)
236 // SendError (); // Why bother?
242 if (ProcessInput (ms)) {
243 if (!context.HaveError)
244 context.Request.FinishInitialization ();
246 if (context.HaveError) {
252 if (!epl.BindContext (context)) {
253 SendError ("Invalid host", 400);
257 HttpListener listener = context.Listener;
258 if (last_listener != listener) {
260 listener.AddConnection (this);
261 last_listener = listener;
264 context_bound = true;
265 listener.RegisterContext (context);
268 stream.BeginRead (buffer, 0, BufferSize, onread_cb, this);
271 void RemoveConnection ()
273 if (last_listener == null)
274 epl.RemoveConnection (this);
276 last_listener.RemoveConnection (this);
290 InputState input_state = InputState.RequestLine;
291 LineState line_state = LineState.None;
294 // true -> done processing
295 // false -> need more input
296 bool ProcessInput (MemoryStream ms)
298 byte [] buffer = ms.GetBuffer ();
299 int len = (int) ms.Length;
304 line = ReadLine (buffer, position, len - position, ref used);
307 context.ErrorMessage = "Bad request";
308 context.ErrorStatus = 400;
316 if (input_state == InputState.RequestLine)
323 if (input_state == InputState.RequestLine) {
324 context.Request.SetRequestLine (line);
325 input_state = InputState.Headers;
328 context.Request.AddHeader (line);
329 } catch (Exception e) {
330 context.ErrorMessage = e.Message;
331 context.ErrorStatus = 400;
336 if (context.HaveError)
342 line = ReadLine (buffer, position, len - position, ref used);
345 context.ErrorMessage = "Bad request";
346 context.ErrorStatus = 400;
349 } while (line != null);
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 = HttpListenerResponse.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 ();
447 force_close |= !context.Request.KeepAlive;
449 force_close = (context.Response.Headers ["connection"] == "close");
452 // bool conn_close = (status_code == 400 || status_code == 408 || status_code == 411 ||
453 // status_code == 413 || status_code == 414 || status_code == 500 ||
454 // status_code == 503);
456 force_close |= (context.Request.ProtocolVersion <= HttpVersion.Version10);
460 if (!force_close && context.Request.FlushInput ()) {
461 if (chunked && context.Response.ForceCloseChunked == false) {
462 // Don't close. Keep working.
481 s.Shutdown (SocketShutdown.Both);