2 // System.Net.HttpConnection
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.
32 using System.Net.Sockets;
33 using System.Reflection;
35 using System.Threading;
36 using System.Security.Cryptography;
37 using System.Security.Cryptography.X509Certificates;
38 using Mono.Security.Protocol.Tls;
40 namespace System.Net {
41 sealed class HttpConnection
43 static AsyncCallback onread_cb = new AsyncCallback (OnRead);
44 const int BufferSize = 8192;
50 HttpListenerContext context;
51 StringBuilder current_line;
52 ListenerPrefix prefix;
53 RequestStream i_stream;
54 ResponseStream o_stream;
59 AsymmetricAlgorithm key;
60 int s_timeout = 90000; // 90k ms for first request, 15k ms from then on
63 HttpListener last_listener;
65 public HttpConnection (Socket sock, EndPointListener epl, bool secure, X509Certificate2 cert, AsymmetricAlgorithm key)
71 if (secure == false) {
72 stream = new NetworkStream (sock, false);
74 SslServerStream ssl_stream = new SslServerStream (new NetworkStream (sock, false), cert, false, false);
75 ssl_stream.PrivateKeyCertSelectionDelegate += OnPVKSelection;
78 timer = new Timer (OnTimeout, null, Timeout.Infinite, Timeout.Infinite);
82 AsymmetricAlgorithm OnPVKSelection (X509Certificate certificate, string targetHost)
89 context_bound = false;
94 ms = new MemoryStream ();
96 input_state = InputState.RequestLine;
97 line_state = LineState.None;
98 context = new HttpListenerContext (this);
101 public bool IsClosed {
102 get { return (sock == null); }
106 get { return reuses; }
109 public IPEndPoint LocalEndPoint {
111 if (local_ep != null)
114 local_ep = (IPEndPoint) sock.LocalEndPoint;
119 public IPEndPoint RemoteEndPoint {
120 get { return (IPEndPoint) sock.RemoteEndPoint; }
123 public bool IsSecure {
124 get { return secure; }
127 public ListenerPrefix Prefix {
128 get { return prefix; }
129 set { prefix = value; }
132 void OnTimeout (object unused)
138 public void BeginReadRequest ()
141 buffer = new byte [BufferSize];
145 timer.Change (s_timeout, Timeout.Infinite);
146 stream.BeginRead (buffer, 0, BufferSize, onread_cb, this);
148 timer.Change (Timeout.Infinite, Timeout.Infinite);
154 public RequestStream GetRequestStream (bool chunked, long contentlength)
156 if (i_stream == null) {
157 byte [] buffer = ms.GetBuffer ();
158 int length = (int) ms.Length;
162 context.Response.SendChunked = true;
163 i_stream = new ChunkedInputStream (context, stream, buffer, position, length - position);
165 i_stream = new RequestStream (stream, buffer, position, length - position, contentlength);
171 public ResponseStream GetResponseStream ()
173 // TODO: can we get this stream before reading the input?
174 if (o_stream == null) {
175 HttpListener listener = context.Listener;
176 bool ign = (listener == null) ? true : listener.IgnoreWriteExceptions;
177 o_stream = new ResponseStream (stream, context.Response, ign);
182 static void OnRead (IAsyncResult ares)
184 HttpConnection cnc = (HttpConnection) ares.AsyncState;
185 cnc.OnReadInternal (ares);
188 void OnReadInternal (IAsyncResult ares)
190 timer.Change (Timeout.Infinite, Timeout.Infinite);
193 nread = stream.EndRead (ares);
194 ms.Write (buffer, 0, nread);
195 if (ms.Length > 32768) {
196 SendError ("Bad request", 400);
201 if (ms != null && ms.Length > 0)
212 // SendError (); // Why bother?
218 if (ProcessInput (ms)) {
219 if (!context.HaveError)
220 context.Request.FinishInitialization ();
222 if (context.HaveError) {
228 if (!epl.BindContext (context)) {
229 SendError ("Invalid host", 400);
233 HttpListener listener = context.Listener;
234 if (last_listener != listener) {
236 listener.AddConnection (this);
237 last_listener = listener;
240 context_bound = true;
241 listener.RegisterContext (context);
244 stream.BeginRead (buffer, 0, BufferSize, onread_cb, this);
247 void RemoveConnection ()
249 if (last_listener == null)
250 epl.RemoveConnection (this);
252 last_listener.RemoveConnection (this);
266 InputState input_state = InputState.RequestLine;
267 LineState line_state = LineState.None;
270 // true -> done processing
271 // false -> need more input
272 bool ProcessInput (MemoryStream ms)
274 byte [] buffer = ms.GetBuffer ();
275 int len = (int) ms.Length;
280 line = ReadLine (buffer, position, len - position, ref used);
283 context.ErrorMessage = "Bad request";
284 context.ErrorStatus = 400;
292 if (input_state == InputState.RequestLine)
299 if (input_state == InputState.RequestLine) {
300 context.Request.SetRequestLine (line);
301 input_state = InputState.Headers;
304 context.Request.AddHeader (line);
305 } catch (Exception e) {
306 context.ErrorMessage = e.Message;
307 context.ErrorStatus = 400;
312 if (context.HaveError)
318 line = ReadLine (buffer, position, len - position, ref used);
321 context.ErrorMessage = "Bad request";
322 context.ErrorStatus = 400;
325 } while (line != null);
334 string ReadLine (byte [] buffer, int offset, int len, ref int used)
336 if (current_line == null)
337 current_line = new StringBuilder (128);
338 int last = offset + len;
340 for (int i = offset; i < last && line_state != LineState.LF; i++) {
344 line_state = LineState.CR;
345 } else if (b == 10) {
346 line_state = LineState.LF;
348 current_line.Append ((char) b);
352 string result = null;
353 if (line_state == LineState.LF) {
354 line_state = LineState.None;
355 result = current_line.ToString ();
356 current_line.Length = 0;
362 public void SendError (string msg, int status)
365 HttpListenerResponse response = context.Response;
366 response.StatusCode = status;
367 response.ContentType = "text/html";
368 string description = HttpListenerResponse.GetStatusDescription (status);
371 str = String.Format ("<h1>{0} ({1})</h1>", description, msg);
373 str = String.Format ("<h1>{0}</h1>", description);
375 byte [] error = context.Response.ContentEncoding.GetBytes (str);
376 response.Close (error, false);
378 // response was already closed
382 public void SendError ()
384 SendError (context.ErrorMessage, context.ErrorStatus);
390 epl.UnbindContext (context);
391 context_bound = false;
414 internal void Close (bool force_close)
417 Stream st = GetResponseStream ();
423 force_close |= !context.Request.KeepAlive;
425 force_close = (context.Response.Headers ["connection"] == "close");
428 // bool conn_close = (status_code == 400 || status_code == 408 || status_code == 411 ||
429 // status_code == 413 || status_code == 414 || status_code == 500 ||
430 // status_code == 503);
432 force_close |= (context.Request.ProtocolVersion <= HttpVersion.Version10);
436 if (!force_close && context.Request.FlushInput ()) {
437 if (chunked && context.Response.ForceCloseChunked == false) {
438 // Don't close. Keep working.
457 s.Shutdown (SocketShutdown.Both);