1 #define EMBEDDED_IN_1_0
4 // System.Net.HttpConnection
7 // Gonzalo Paniagua Javier (gonzalo@novell.com)
9 // Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 using System.Net.Sockets;
35 using System.Reflection;
37 using System.Security.Cryptography;
38 using System.Security.Cryptography.X509Certificates;
41 using Mono.Security.Protocol.Tls;
44 using System; using System.Net; namespace MonoHttp {
46 interface IHttpListenerContextBinder {
47 bool BindContext (HttpListenerContext context);
48 void UnbindContext (HttpListenerContext context);
51 sealed class HttpConnection
53 const int BufferSize = 8192;
56 IHttpListenerContextBinder epl;
59 HttpListenerContext context;
60 StringBuilder current_line;
61 ListenerPrefix prefix;
62 RequestStream i_stream;
63 ResponseStream o_stream;
68 AsymmetricAlgorithm key;
71 public HttpConnection (Socket sock, IHttpListenerContextBinder epl)
75 stream = new NetworkStream (sock, false);
79 public HttpConnection (Socket sock, IHttpListenerContextBinder epl, bool secure, X509Certificate2 cert, AsymmetricAlgorithm key)
85 if (secure == false) {
86 stream = new NetworkStream (sock, false);
88 SslServerStream ssl_stream = new SslServerStream (new NetworkStream (sock, false), cert, false, false);
89 ssl_stream.PrivateKeyCertSelectionDelegate += OnPVKSelection;
97 AsymmetricAlgorithm OnPVKSelection (X509Certificate certificate, string targetHost)
105 context_bound = false;
110 ms = new MemoryStream ();
112 input_state = InputState.RequestLine;
113 line_state = LineState.None;
114 context = new HttpListenerContext (this);
117 public int ChunkedUses {
118 get { return chunked_uses; }
121 public IPEndPoint LocalEndPoint {
122 get { return (IPEndPoint) sock.LocalEndPoint; }
125 public IPEndPoint RemoteEndPoint {
126 get { return (IPEndPoint) sock.RemoteEndPoint; }
129 public bool IsSecure {
130 get { return secure; }
133 public ListenerPrefix Prefix {
134 get { return prefix; }
135 set { prefix = value; }
138 public void BeginReadRequest ()
141 buffer = new byte [BufferSize];
142 stream.BeginRead (buffer, 0, BufferSize, OnRead, this);
145 public RequestStream GetRequestStream (bool chunked, long contentlength)
147 if (i_stream == null) {
148 byte [] buffer = ms.GetBuffer ();
149 int length = (int) ms.Length;
153 context.Response.SendChunked = true;
154 i_stream = new ChunkedInputStream (context, stream, buffer, position, length - position);
156 i_stream = new RequestStream (stream, buffer, position, length - position, contentlength);
162 public ResponseStream GetResponseStream ()
164 // TODO: can we get this stream before reading the input?
165 if (o_stream == null) {
166 HttpListener listener = context.Listener;
167 bool ign = false;// ? true : listener.IgnoreWriteExceptions;
168 o_stream = new ResponseStream (stream, context.Response, ign);
173 void OnRead (IAsyncResult ares)
175 // TODO: set a limit on ms length.
176 HttpConnection cnc = (HttpConnection) ares.AsyncState;
179 nread = stream.EndRead (ares);
180 ms.Write (buffer, 0, nread);
181 } catch (Exception e) {
182 Console.WriteLine (e);
191 // SendError (); // Why bother?
196 if (ProcessInput (ms)) {
197 if (!context.HaveError)
198 context.Request.FinishInitialization ();
200 if (context.HaveError) {
206 if (!epl.BindContext (context)) {
207 SendError ("Invalid host", 400);
210 context_bound = true;
213 stream.BeginRead (buffer, 0, BufferSize, OnRead, cnc);
227 InputState input_state = InputState.RequestLine;
228 LineState line_state = LineState.None;
231 // true -> done processing
232 // false -> need more input
233 bool ProcessInput (MemoryStream ms)
235 byte [] buffer = ms.GetBuffer ();
236 int len = (int) ms.Length;
239 while ((line = ReadLine (buffer, position, len - position, ref used)) != null) {
242 if (input_state == InputState.RequestLine)
249 if (input_state == InputState.RequestLine) {
250 context.Request.SetRequestLine (line);
251 input_state = InputState.Headers;
253 context.Request.AddHeader (line);
256 if (context.HaveError)
270 string ReadLine (byte [] buffer, int offset, int len, ref int used)
272 if (current_line == null)
273 current_line = new StringBuilder ();
274 int last = offset + len;
276 for (int i = offset; i < last && line_state != LineState.LF; i++) {
280 line_state = LineState.CR;
281 } else if (b == 10) {
282 line_state = LineState.LF;
284 current_line.Append ((char) b);
288 string result = null;
289 if (line_state == LineState.LF) {
290 line_state = LineState.None;
291 result = current_line.ToString ();
292 current_line.Length = 0;
298 public void SendError (string msg, int status)
300 HttpListenerResponse response = context.Response;
301 response.StatusCode = status;
302 response.ContentType = "text/html";
303 string description = HttpListenerResponse.GetStatusDescription (status);
306 str = String.Format ("<h1>{0} ({1})</h1>", description, msg);
308 str = String.Format ("<h1>{0}</h1>", description);
310 byte [] error = context.Response.ContentEncoding.GetBytes (str);
311 response.Close (error, false);
314 public void SendError ()
316 SendError (context.ErrorMessage, context.ErrorStatus);
321 if (o_stream != null) {
322 Stream st = o_stream;
328 if (chunked && context.Response.ForceCloseChunked == false) {
329 // Don't close. Keep working.
339 s.Shutdown (SocketShutdown.Both);
344 epl.UnbindContext (context);