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.Security.Cryptography;
36 using System.Security.Cryptography.X509Certificates;
37 using Mono.Security.Protocol.Tls;
39 namespace System.Net {
40 sealed class HttpConnection
42 const int BufferSize = 8192;
48 HttpListenerContext context;
49 StringBuilder current_line;
50 ListenerPrefix prefix;
51 RequestStream i_stream;
52 ResponseStream o_stream;
57 AsymmetricAlgorithm key;
59 public HttpConnection (Socket sock, EndPointListener epl, bool secure, X509Certificate2 cert, AsymmetricAlgorithm key)
65 if (secure == false) {
66 stream = new NetworkStream (sock, false);
68 SslServerStream ssl_stream = new SslServerStream (new NetworkStream (sock, false), cert, false, false);
69 ssl_stream.PrivateKeyCertSelectionDelegate += OnPVKSelection;
75 AsymmetricAlgorithm OnPVKSelection (X509Certificate certificate, string targetHost)
82 context_bound = false;
87 ms = new MemoryStream ();
89 input_state = InputState.RequestLine;
90 line_state = LineState.None;
91 context = new HttpListenerContext (this);
94 public int ChunkedUses {
95 get { return chunked_uses; }
98 public IPEndPoint LocalEndPoint {
99 get { return (IPEndPoint) sock.LocalEndPoint; }
102 public IPEndPoint RemoteEndPoint {
103 get { return (IPEndPoint) sock.RemoteEndPoint; }
106 public bool IsSecure {
107 get { return secure; }
110 public ListenerPrefix Prefix {
111 get { return prefix; }
112 set { prefix = value; }
115 public void BeginReadRequest ()
118 buffer = new byte [BufferSize];
120 stream.BeginRead (buffer, 0, BufferSize, OnRead, this);
122 sock.Close (); // stream disposed
126 public RequestStream GetRequestStream (bool chunked, long contentlength)
128 if (i_stream == null) {
129 byte [] buffer = ms.GetBuffer ();
130 int length = (int) ms.Length;
134 context.Response.SendChunked = true;
135 i_stream = new ChunkedInputStream (context, stream, buffer, position, length - position);
137 i_stream = new RequestStream (stream, buffer, position, length - position, contentlength);
143 public ResponseStream GetResponseStream ()
145 // TODO: can we get this stream before reading the input?
146 if (o_stream == null) {
147 HttpListener listener = context.Listener;
148 bool ign = (listener == null) ? true : listener.IgnoreWriteExceptions;
149 o_stream = new ResponseStream (stream, context.Response, ign);
154 void OnRead (IAsyncResult ares)
156 HttpConnection cnc = (HttpConnection) ares.AsyncState;
159 nread = stream.EndRead (ares);
160 ms.Write (buffer, 0, nread);
161 if (ms.Length > 32768) {
162 SendError ("Bad request", 400);
167 if (ms != null && ms.Length > 0)
176 // SendError (); // Why bother?
181 if (ProcessInput (ms)) {
182 if (!context.HaveError)
183 context.Request.FinishInitialization ();
185 if (context.HaveError) {
191 if (!epl.BindContext (context)) {
192 SendError ("Invalid host", 400);
195 context_bound = true;
198 stream.BeginRead (buffer, 0, BufferSize, OnRead, cnc);
212 InputState input_state = InputState.RequestLine;
213 LineState line_state = LineState.None;
216 // true -> done processing
217 // false -> need more input
218 bool ProcessInput (MemoryStream ms)
220 byte [] buffer = ms.GetBuffer ();
221 int len = (int) ms.Length;
226 line = ReadLine (buffer, position, len - position, ref used);
229 context.ErrorMessage = "Bad request";
230 context.ErrorStatus = 400;
238 if (input_state == InputState.RequestLine)
245 if (input_state == InputState.RequestLine) {
246 context.Request.SetRequestLine (line);
247 input_state = InputState.Headers;
250 context.Request.AddHeader (line);
251 } catch (Exception e) {
252 context.ErrorMessage = e.Message;
253 context.ErrorStatus = 400;
258 if (context.HaveError)
264 line = ReadLine (buffer, position, len - position, ref used);
267 context.ErrorMessage = "Bad request";
268 context.ErrorStatus = 400;
271 } while (line != null);
280 string ReadLine (byte [] buffer, int offset, int len, ref int used)
282 if (current_line == null)
283 current_line = new StringBuilder ();
284 int last = offset + len;
286 for (int i = offset; i < last && line_state != LineState.LF; i++) {
290 line_state = LineState.CR;
291 } else if (b == 10) {
292 line_state = LineState.LF;
294 current_line.Append ((char) b);
298 string result = null;
299 if (line_state == LineState.LF) {
300 line_state = LineState.None;
301 result = current_line.ToString ();
302 current_line.Length = 0;
308 public void SendError (string msg, int status)
311 HttpListenerResponse response = context.Response;
312 response.StatusCode = status;
313 response.ContentType = "text/html";
314 string description = HttpListenerResponse.GetStatusDescription (status);
317 str = String.Format ("<h1>{0} ({1})</h1>", description, msg);
319 str = String.Format ("<h1>{0}</h1>", description);
321 byte [] error = context.Response.ContentEncoding.GetBytes (str);
322 response.Close (error, false);
324 // response was already closed
328 public void SendError ()
330 SendError (context.ErrorMessage, context.ErrorStatus);
336 epl.UnbindContext (context);
337 context_bound = false;
346 internal void Close (bool force_close)
349 Stream st = GetResponseStream ();
355 force_close |= (context.Request.Headers ["connection"] == "close");
357 int status_code = context.Response.StatusCode;
358 bool conn_close = (status_code == 400 || status_code == 408 || status_code == 411 ||
359 status_code == 413 || status_code == 414 || status_code == 500 ||
362 force_close |= (context.Request.ProtocolVersion <= HttpVersion.Version10);
365 if (!force_close && context.Request.FlushInput ()) {
366 if (chunked && context.Response.ForceCloseChunked == false) {
367 // Don't close. Keep working.
384 s.Shutdown (SocketShutdown.Both);