2009-07-11 Michael Barker <mike@middlesoft.co.uk>
[mono.git] / mcs / class / System / System.Net / HttpConnection.cs
1 //
2 // System.Net.HttpConnection
3 //
4 // Author:
5 //      Gonzalo Paniagua Javier (gonzalo@novell.com)
6 //
7 // Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
8 //
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:
16 // 
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 // 
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.
27 //
28
29 #if NET_2_0 && SECURITY_DEP
30
31 using System.IO;
32 using System.Net.Sockets;
33 using System.Reflection;
34 using System.Text;
35 using System.Security.Cryptography;
36 using System.Security.Cryptography.X509Certificates;
37 using Mono.Security.Protocol.Tls;
38
39 namespace System.Net {
40         sealed class HttpConnection
41         {
42                 const int BufferSize = 8192;
43                 Socket sock;
44                 Stream stream;
45                 EndPointListener epl;
46                 MemoryStream ms;
47                 byte [] buffer;
48                 HttpListenerContext context;
49                 StringBuilder current_line;
50                 ListenerPrefix prefix;
51                 RequestStream i_stream;
52                 ResponseStream o_stream;
53                 bool chunked;
54                 int chunked_uses;
55                 bool context_bound;
56                 bool secure;
57                 AsymmetricAlgorithm key;
58
59                 public HttpConnection (Socket sock, EndPointListener epl, bool secure, X509Certificate2 cert, AsymmetricAlgorithm key)
60                 {
61                         this.sock = sock;
62                         this.epl = epl;
63                         this.secure = secure;
64                         this.key = key;
65                         if (secure == false) {
66                                 stream = new NetworkStream (sock, false);
67                         } else {
68 #if EMBEDDED_IN_1_0
69                                 throw new NotImplementedException ();
70 #else
71                                 SslServerStream ssl_stream = new SslServerStream (new NetworkStream (sock, false), cert, false, false);
72                                 ssl_stream.PrivateKeyCertSelectionDelegate += OnPVKSelection;
73                                 stream = ssl_stream;
74 #endif
75                         }
76                         Init ();
77                 }
78
79                 AsymmetricAlgorithm OnPVKSelection (X509Certificate certificate, string targetHost)
80                 {
81                         return key;
82                 }
83
84
85                 void Init ()
86                 {
87                         context_bound = false;
88                         i_stream = null;
89                         o_stream = null;
90                         prefix = null;
91                         chunked = false;
92                         ms = new MemoryStream ();
93                         position = 0;
94                         input_state = InputState.RequestLine;
95                         line_state = LineState.None;
96                         context = new HttpListenerContext (this);
97                 }
98
99                 public int ChunkedUses {
100                         get { return chunked_uses; }
101                 }
102
103                 public IPEndPoint LocalEndPoint {
104                         get { return (IPEndPoint) sock.LocalEndPoint; }
105                 }
106
107                 public IPEndPoint RemoteEndPoint {
108                         get { return (IPEndPoint) sock.RemoteEndPoint; }
109                 }
110
111                 public bool IsSecure {
112                         get { return secure; }
113                 }
114
115                 public ListenerPrefix Prefix {
116                         get { return prefix; }
117                         set { prefix = value; }
118                 }
119
120                 public void BeginReadRequest ()
121                 {
122                         if (buffer == null)
123                                 buffer = new byte [BufferSize];
124                         try {
125                                 stream.BeginRead (buffer, 0, BufferSize, OnRead, this);
126                         } catch {
127                                 sock.Close (); // stream disposed
128                         }
129                 }
130
131                 public RequestStream GetRequestStream (bool chunked, long contentlength)
132                 {
133                         if (i_stream == null) {
134                                 byte [] buffer = ms.GetBuffer ();
135                                 int length = (int) ms.Length;
136                                 ms = null;
137                                 if (chunked) {
138                                         this.chunked = true;
139                                         context.Response.SendChunked = true;
140                                         i_stream = new ChunkedInputStream (context, stream, buffer, position, length - position);
141                                 } else {
142                                         i_stream = new RequestStream (stream, buffer, position, length - position, contentlength);
143                                 }
144                         }
145                         return i_stream;
146                 }
147
148                 public ResponseStream GetResponseStream ()
149                 {
150                         // TODO: can we get this stream before reading the input?
151                         if (o_stream == null) {
152                                 HttpListener listener = context.Listener;
153                                 bool ign = (listener == null) ? true : listener.IgnoreWriteExceptions;
154                                 o_stream = new ResponseStream (stream, context.Response, ign);
155                         }
156                         return o_stream;
157                 }
158
159                 void OnRead (IAsyncResult ares)
160                 {
161                         // TODO: set a limit on ms length.
162                         HttpConnection cnc = (HttpConnection) ares.AsyncState;
163                         int nread = -1;
164                         try {
165                                 nread = stream.EndRead (ares);
166                                 ms.Write (buffer, 0, nread);
167                         } catch (Exception e) {
168                                 //Console.WriteLine (e);
169                                 if (ms.Length > 0)
170                                         SendError ();
171                                 sock.Close ();
172                                 return;
173                         }
174
175                         if (nread == 0) {
176                                 //if (ms.Length > 0)
177                                 //      SendError (); // Why bother?
178                                 sock.Close ();
179                                 return;
180                         }
181
182                         if (ProcessInput (ms)) {
183                                 if (!context.HaveError)
184                                         context.Request.FinishInitialization ();
185
186                                 if (context.HaveError) {
187                                         SendError ();
188                                         Close ();
189                                         return;
190                                 }
191
192                                 if (!epl.BindContext (context)) {
193                                         SendError ("Invalid host", 400);
194                                         Close ();
195                                 }
196                                 context_bound = true;
197                                 return;
198                         }
199                         stream.BeginRead (buffer, 0, BufferSize, OnRead, cnc);
200                 }
201
202                 enum InputState {
203                         RequestLine,
204                         Headers
205                 }
206
207                 enum LineState {
208                         None,
209                         CR,
210                         LF
211                 }
212
213                 InputState input_state = InputState.RequestLine;
214                 LineState line_state = LineState.None;
215                 int position;
216
217                 // true -> done processing
218                 // false -> need more input
219                 bool ProcessInput (MemoryStream ms)
220                 {
221                         byte [] buffer = ms.GetBuffer ();
222                         int len = (int) ms.Length;
223                         int used = 0;
224                         string line;
225                         while ((line = ReadLine (buffer, position, len - position, ref used)) != null) {
226                                 position += used;
227                                 if (line == "") {
228                                         if (input_state == InputState.RequestLine)
229                                                 continue;
230                                         current_line = null;
231                                         ms = null;
232                                         return true;
233                                 }
234
235                                 if (input_state == InputState.RequestLine) {
236                                         context.Request.SetRequestLine (line);
237                                         input_state = InputState.Headers;
238                                 } else {
239                                         context.Request.AddHeader (line);
240                                 }
241
242                                 if (context.HaveError)
243                                         return true;
244
245                                 if (position >= len)
246                                         break;
247                         }
248
249                         if (used == len) {
250                                 ms.SetLength (0);
251                                 position = 0;
252                         }
253                         return false;
254                 }
255
256                 string ReadLine (byte [] buffer, int offset, int len, ref int used)
257                 {
258                         if (current_line == null)
259                                 current_line = new StringBuilder ();
260                         int last = offset + len;
261                         used = 0;
262                         for (int i = offset; i < last && line_state != LineState.LF; i++) {
263                                 used++;
264                                 byte b = buffer [i];
265                                 if (b == 13) {
266                                         line_state = LineState.CR;
267                                 } else if (b == 10) {
268                                         line_state = LineState.LF;
269                                 } else {
270                                         current_line.Append ((char) b);
271                                 }
272                         }
273
274                         string result = null;
275                         if (line_state == LineState.LF) {
276                                 line_state = LineState.None;
277                                 result = current_line.ToString ();
278                                 current_line.Length = 0;
279                         }
280
281                         return result;
282                 }
283
284                 public void SendError (string msg, int status)
285                 {
286                         HttpListenerResponse response = context.Response;
287                         response.StatusCode = status;
288                         response.ContentType = "text/html";
289                         string description = HttpListenerResponse.GetStatusDescription (status);
290                         string str;
291                         if (msg != null)
292                                 str = String.Format ("<h1>{0} ({1})</h1>", description, msg);
293                         else
294                                 str = String.Format ("<h1>{0}</h1>", description);
295
296                         byte [] error = context.Response.ContentEncoding.GetBytes (str);
297                         response.Close (error, false);
298                 }
299
300                 public void SendError ()
301                 {
302                         SendError (context.ErrorMessage, context.ErrorStatus);
303                 }
304
305                 void Unbind ()
306                 {
307                         if (context_bound) {
308                                 epl.UnbindContext (context);
309                                 context_bound = false;
310                         }
311                 }
312
313                 public void Close ()
314                 {
315                         Close (false);
316                 }
317
318                 internal void Close (bool force_close)
319                 {
320                         if (sock != null) {
321                                 Stream st = GetResponseStream ();
322                                 st.Close ();
323                                 o_stream = null;
324                         }
325
326                         if (sock != null) {
327                                 if (!force_close && chunked && context.Response.ForceCloseChunked == false) {
328                                         // Don't close. Keep working.
329                                         chunked_uses++;
330                                         Unbind ();
331                                         Init ();
332                                         BeginReadRequest ();
333                                         return;
334                                 }
335
336                                 if (force_close || context.Response.Headers ["connection"] == "close") {
337                                         Socket s = sock;
338                                         sock = null;
339                                         try {
340                                                 s.Shutdown (SocketShutdown.Both);
341                                         } catch {
342                                         } finally {
343                                                 s.Close ();
344                                         }
345                                         Unbind ();
346                                 } else {
347                                         Unbind ();
348                                         Init ();
349                                         BeginReadRequest ();
350                                         return;
351                                 }
352                         }
353                 }
354         }
355 }
356 #endif
357