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.
29 #if NET_2_0 && SECURITY_DEP
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)
83 context_bound = false;
88 ms = new MemoryStream ();
90 input_state = InputState.RequestLine;
91 line_state = LineState.None;
92 context = new HttpListenerContext (this);
95 public int ChunkedUses {
96 get { return chunked_uses; }
99 public IPEndPoint LocalEndPoint {
100 get { return (IPEndPoint) sock.LocalEndPoint; }
103 public IPEndPoint RemoteEndPoint {
104 get { return (IPEndPoint) sock.RemoteEndPoint; }
107 public bool IsSecure {
108 get { return secure; }
111 public ListenerPrefix Prefix {
112 get { return prefix; }
113 set { prefix = value; }
116 public void BeginReadRequest ()
119 buffer = new byte [BufferSize];
120 stream.BeginRead (buffer, 0, BufferSize, OnRead, this);
123 public RequestStream GetRequestStream (bool chunked, long contentlength)
125 if (i_stream == null) {
126 byte [] buffer = ms.GetBuffer ();
127 int length = (int) ms.Length;
131 context.Response.SendChunked = true;
132 i_stream = new ChunkedInputStream (context, stream, buffer, position, length - position);
134 i_stream = new RequestStream (stream, buffer, position, length - position, contentlength);
140 public ResponseStream GetResponseStream ()
142 // TODO: can we get this stream before reading the input?
143 if (o_stream == null) {
144 HttpListener listener = context.Listener;
145 bool ign = (listener == null) ? true : listener.IgnoreWriteExceptions;
146 o_stream = new ResponseStream (stream, context.Response, ign);
151 void OnRead (IAsyncResult ares)
153 // TODO: set a limit on ms length.
154 HttpConnection cnc = (HttpConnection) ares.AsyncState;
157 nread = stream.EndRead (ares);
158 ms.Write (buffer, 0, nread);
159 } catch (Exception e) {
160 Console.WriteLine (e);
169 // SendError (); // Why bother?
174 if (ProcessInput (ms)) {
175 if (!context.HaveError)
176 context.Request.FinishInitialization ();
178 if (context.HaveError) {
184 if (!epl.BindContext (context)) {
185 SendError ("Invalid host", 400);
188 context_bound = true;
191 stream.BeginRead (buffer, 0, BufferSize, OnRead, cnc);
205 InputState input_state = InputState.RequestLine;
206 LineState line_state = LineState.None;
209 // true -> done processing
210 // false -> need more input
211 bool ProcessInput (MemoryStream ms)
213 byte [] buffer = ms.GetBuffer ();
214 int len = (int) ms.Length;
217 while ((line = ReadLine (buffer, position, len - position, ref used)) != null) {
220 if (input_state == InputState.RequestLine)
227 if (input_state == InputState.RequestLine) {
228 context.Request.SetRequestLine (line);
229 input_state = InputState.Headers;
231 context.Request.AddHeader (line);
234 if (context.HaveError)
248 string ReadLine (byte [] buffer, int offset, int len, ref int used)
250 if (current_line == null)
251 current_line = new StringBuilder ();
252 int last = offset + len;
254 for (int i = offset; i < last && line_state != LineState.LF; i++) {
258 line_state = LineState.CR;
259 } else if (b == 10) {
260 line_state = LineState.LF;
262 current_line.Append ((char) b);
266 string result = null;
267 if (line_state == LineState.LF) {
268 line_state = LineState.None;
269 result = current_line.ToString ();
270 current_line.Length = 0;
276 public void SendError (string msg, int status)
278 HttpListenerResponse response = context.Response;
279 response.StatusCode = status;
280 response.ContentType = "text/html";
281 string description = HttpListenerResponse.GetStatusDescription (status);
284 str = String.Format ("<h1>{0} ({1})</h1>", description, msg);
286 str = String.Format ("<h1>{0}</h1>", description);
288 byte [] error = context.Response.ContentEncoding.GetBytes (str);
289 response.Close (error, false);
292 public void SendError ()
294 SendError (context.ErrorMessage, context.ErrorStatus);
299 if (o_stream != null) {
300 Stream st = o_stream;
306 if (chunked && context.Response.ForceCloseChunked == false) {
307 // Don't close. Keep working.
317 s.Shutdown (SocketShutdown.Both);
322 epl.UnbindContext (context);