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;
69 public HttpConnection (Socket sock, IHttpListenerContextBinder epl)
73 stream = new NetworkStream (sock, false);
77 public HttpConnection (Socket sock, IHttpListenerContextBinder epl, bool secure, X509Certificate2 cert, AsymmetricAlgorithm key)
83 if (secure == false) {
84 stream = new NetworkStream (sock, false);
86 SslServerStream ssl_stream = new SslServerStream (new NetworkStream (sock, false), cert, false, false);
87 ssl_stream.PrivateKeyCertSelectionDelegate += OnPVKSelection;
97 context_bound = false;
102 ms = new MemoryStream ();
104 input_state = InputState.RequestLine;
105 line_state = LineState.None;
106 context = new HttpListenerContext (this);
109 public int ChunkedUses {
110 get { return chunked_uses; }
113 public IPEndPoint LocalEndPoint {
114 get { return (IPEndPoint) sock.LocalEndPoint; }
117 public IPEndPoint RemoteEndPoint {
118 get { return (IPEndPoint) sock.RemoteEndPoint; }
121 public bool IsSecure {
122 get { return false; }
125 public ListenerPrefix Prefix {
126 get { return prefix; }
127 set { prefix = value; }
130 public void BeginReadRequest ()
133 buffer = new byte [BufferSize];
135 stream.BeginRead (buffer, 0, BufferSize, OnRead, this);
137 sock.Close (); // stream disposed
141 public RequestStream GetRequestStream (bool chunked, long contentlength)
143 if (i_stream == null) {
144 byte [] buffer = ms.GetBuffer ();
145 int length = (int) ms.Length;
149 context.Response.SendChunked = true;
150 i_stream = new ChunkedInputStream (context, stream, buffer, position, length - position);
152 i_stream = new RequestStream (stream, buffer, position, length - position, contentlength);
158 public ResponseStream GetResponseStream ()
160 // TODO: can we get this stream before reading the input?
161 if (o_stream == null) {
162 bool ign = false;// ? true : listener.IgnoreWriteExceptions;
163 o_stream = new ResponseStream (stream, context.Response, ign);
168 void OnRead (IAsyncResult ares)
170 // TODO: set a limit on ms length.
171 HttpConnection cnc = (HttpConnection) ares.AsyncState;
174 nread = stream.EndRead (ares);
175 ms.Write (buffer, 0, nread);
176 } catch (Exception) {
177 //Console.WriteLine (e);
186 // SendError (); // Why bother?
191 if (ProcessInput (ms)) {
192 if (!context.HaveError)
193 context.Request.FinishInitialization ();
195 if (context.HaveError) {
201 if (!epl.BindContext (context)) {
202 SendError ("Invalid host", 400);
205 context_bound = true;
208 stream.BeginRead (buffer, 0, BufferSize, OnRead, cnc);
222 InputState input_state = InputState.RequestLine;
223 LineState line_state = LineState.None;
226 // true -> done processing
227 // false -> need more input
228 bool ProcessInput (MemoryStream ms)
230 byte [] buffer = ms.GetBuffer ();
231 int len = (int) ms.Length;
234 while ((line = ReadLine (buffer, position, len - position, ref used)) != null) {
237 if (input_state == InputState.RequestLine)
244 if (input_state == InputState.RequestLine) {
245 context.Request.SetRequestLine (line);
246 input_state = InputState.Headers;
248 context.Request.AddHeader (line);
251 if (context.HaveError)
265 string ReadLine (byte [] buffer, int offset, int len, ref int used)
267 if (current_line == null)
268 current_line = new StringBuilder ();
269 int last = offset + len;
271 for (int i = offset; i < last && line_state != LineState.LF; i++) {
275 line_state = LineState.CR;
276 } else if (b == 10) {
277 line_state = LineState.LF;
279 current_line.Append ((char) b);
283 string result = null;
284 if (line_state == LineState.LF) {
285 line_state = LineState.None;
286 result = current_line.ToString ();
287 current_line.Length = 0;
293 public void SendError (string msg, int status)
295 HttpListenerResponse response = context.Response;
296 response.StatusCode = status;
297 response.ContentType = "text/html";
298 string description = HttpListenerResponse.GetStatusDescription (status);
301 str = String.Format ("<h1>{0} ({1})</h1>", description, msg);
303 str = String.Format ("<h1>{0}</h1>", description);
305 byte [] error = context.Response.ContentEncoding.GetBytes (str);
306 response.Close (error, false);
309 public void SendError ()
311 SendError (context.ErrorMessage, context.ErrorStatus);
317 Stream st = GetResponseStream ();
323 if (chunked && context.Response.ForceCloseChunked == false) {
324 // Don't close. Keep working.
331 if (context.Response.Headers ["connection"] == "close") {
335 s.Shutdown (SocketShutdown.Both);
347 epl.UnbindContext (context);