Merge pull request #2869 from BrzVlad/feature-mod-union-opt
[mono.git] / mcs / class / System / System.Net / HttpConnection.cs
1 //
2 // System.Net.HttpConnection
3 //
4 // Author:
5 //      Gonzalo Paniagua Javier (gonzalo.mono@gmail.com)
6 //
7 // Copyright (c) 2005-2009 Novell, Inc. (http://www.novell.com)
8 // Copyright (c) 2012 Xamarin, Inc. (http://xamarin.com)
9 //
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
17 // 
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
20 // 
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 //
29
30 #if SECURITY_DEP
31 #if MONO_SECURITY_ALIAS
32 extern alias MonoSecurity;
33 #endif
34
35 #if MONO_SECURITY_ALIAS
36 using MSI = MonoSecurity::Mono.Security.Interface;
37 #else
38 using MSI = Mono.Security.Interface;
39 #endif
40
41 using System.IO;
42 using System.Net.Sockets;
43 using System.Text;
44 using System.Threading;
45 using System.Security.Authentication;
46 using System.Security.Cryptography;
47 using System.Security.Cryptography.X509Certificates;
48 using Mono.Net.Security;
49
50 namespace System.Net {
51         sealed class HttpConnection
52         {
53                 static AsyncCallback onread_cb = new AsyncCallback (OnRead);
54                 const int BufferSize = 8192;
55                 Socket sock;
56                 Stream stream;
57                 EndPointListener epl;
58                 MemoryStream ms;
59                 byte [] buffer;
60                 HttpListenerContext context;
61                 StringBuilder current_line;
62                 ListenerPrefix prefix;
63                 RequestStream i_stream;
64                 ResponseStream o_stream;
65                 bool chunked;
66                 int reuses;
67                 bool context_bound;
68                 bool secure;
69                 X509Certificate cert;
70                 int s_timeout = 90000; // 90k ms for first request, 15k ms from then on
71                 Timer timer;
72                 IPEndPoint local_ep;
73                 HttpListener last_listener;
74                 int [] client_cert_errors;
75                 X509Certificate2 client_cert;
76                 IMonoSslStream ssl_stream;
77
78                 public HttpConnection (Socket sock, EndPointListener epl, bool secure, X509Certificate cert)
79                 {
80                         this.sock = sock;
81                         this.epl = epl;
82                         this.secure = secure;
83                         this.cert = cert;
84                         if (secure == false) {
85                                 stream = new NetworkStream (sock, false);
86                         } else {
87                                 ssl_stream = epl.Listener.CreateSslStream (new NetworkStream (sock, false), false, (t, c, ch, e) => {
88                                         if (c == null)
89                                                 return true;
90                                         var c2 = c as X509Certificate2;
91                                         if (c2 == null)
92                                                 c2 = new X509Certificate2 (c.GetRawCertData ());
93                                         client_cert = c2;
94                                         client_cert_errors = new int[] { (int)e };
95                                         return true;
96                                 });
97                                 stream = ssl_stream.AuthenticatedStream;
98                         }
99                         timer = new Timer (OnTimeout, null, Timeout.Infinite, Timeout.Infinite);
100                         Init ();
101                 }
102
103                 internal int [] ClientCertificateErrors {
104                         get { return client_cert_errors; }
105                 }
106
107                 internal X509Certificate2 ClientCertificate {
108                         get { return client_cert; }
109                 }
110
111                 void Init ()
112                 {
113                         if (ssl_stream != null) {
114                                 ssl_stream.AuthenticateAsServer (cert, true, (SslProtocols)ServicePointManager.SecurityProtocol, false);
115                         }
116
117                         context_bound = false;
118                         i_stream = null;
119                         o_stream = null;
120                         prefix = null;
121                         chunked = false;
122                         ms = new MemoryStream ();
123                         position = 0;
124                         input_state = InputState.RequestLine;
125                         line_state = LineState.None;
126                         context = new HttpListenerContext (this);
127                 }
128
129                 public bool IsClosed {
130                         get { return (sock == null); }
131                 }
132
133                 public int Reuses {
134                         get { return reuses; }
135                 }
136
137                 public IPEndPoint LocalEndPoint {
138                         get {
139                                 if (local_ep != null)
140                                         return local_ep;
141
142                                 local_ep = (IPEndPoint) sock.LocalEndPoint;
143                                 return local_ep;
144                         }
145                 }
146
147                 public IPEndPoint RemoteEndPoint {
148                         get { return (IPEndPoint) sock.RemoteEndPoint; }
149                 }
150
151                 public bool IsSecure {
152                         get { return secure; }
153                 }
154
155                 public ListenerPrefix Prefix {
156                         get { return prefix; }
157                         set { prefix = value; }
158                 }
159
160                 void OnTimeout (object unused)
161                 {
162                         CloseSocket ();
163                         Unbind ();
164                 }
165
166                 public void BeginReadRequest ()
167                 {
168                         if (buffer == null)
169                                 buffer = new byte [BufferSize];
170                         try {
171                                 if (reuses == 1)
172                                         s_timeout = 15000;
173                                 timer.Change (s_timeout, Timeout.Infinite);
174                                 stream.BeginRead (buffer, 0, BufferSize, onread_cb, this);
175                         } catch {
176                                 timer.Change (Timeout.Infinite, Timeout.Infinite);
177                                 CloseSocket ();
178                                 Unbind ();
179                         }
180                 }
181
182                 public RequestStream GetRequestStream (bool chunked, long contentlength)
183                 {
184                         if (i_stream == null) {
185                                 byte [] buffer = ms.GetBuffer ();
186                                 int length = (int) ms.Length;
187                                 ms = null;
188                                 if (chunked) {
189                                         this.chunked = true;
190                                         context.Response.SendChunked = true;
191                                         i_stream = new ChunkedInputStream (context, stream, buffer, position, length - position);
192                                 } else {
193                                         i_stream = new RequestStream (stream, buffer, position, length - position, contentlength);
194                                 }
195                         }
196                         return i_stream;
197                 }
198
199                 public ResponseStream GetResponseStream ()
200                 {
201                         // TODO: can we get this stream before reading the input?
202                         if (o_stream == null) {
203                                 HttpListener listener = context.Listener;
204                                 
205                                 if(listener == null)
206                                         return new ResponseStream (stream, context.Response, true);
207
208                                 o_stream = new ResponseStream (stream, context.Response, listener.IgnoreWriteExceptions);
209                         }
210                         return o_stream;
211                 }
212
213                 static void OnRead (IAsyncResult ares)
214                 {
215                         HttpConnection cnc = (HttpConnection) ares.AsyncState;
216                         cnc.OnReadInternal (ares);
217                 }
218
219                 void OnReadInternal (IAsyncResult ares)
220                 {
221                         timer.Change (Timeout.Infinite, Timeout.Infinite);
222                         int nread = -1;
223                         try {
224                                 nread = stream.EndRead (ares);
225                                 ms.Write (buffer, 0, nread);
226                                 if (ms.Length > 32768) {
227                                         SendError ("Bad request", 400);
228                                         Close (true);
229                                         return;
230                                 }
231                         } catch {
232                                 if (ms != null && ms.Length > 0)
233                                         SendError ();
234                                 if (sock != null) {
235                                         CloseSocket ();
236                                         Unbind ();
237                                 }
238                                 return;
239                         }
240
241                         if (nread == 0) {
242                                 //if (ms.Length > 0)
243                                 //      SendError (); // Why bother?
244                                 CloseSocket ();
245                                 Unbind ();
246                                 return;
247                         }
248
249                         if (ProcessInput (ms)) {
250                                 if (!context.HaveError)
251                                         context.Request.FinishInitialization ();
252
253                                 if (context.HaveError) {
254                                         SendError ();
255                                         Close (true);
256                                         return;
257                                 }
258
259                                 if (!epl.BindContext (context)) {
260                                         SendError ("Invalid host", 400);
261                                         Close (true);
262                                         return;
263                                 }
264                                 HttpListener listener = context.Listener;
265                                 if (last_listener != listener) {
266                                         RemoveConnection ();
267                                         listener.AddConnection (this);
268                                         last_listener = listener;
269                                 }
270
271                                 context_bound = true;
272                                 listener.RegisterContext (context);
273                                 return;
274                         }
275                         stream.BeginRead (buffer, 0, BufferSize, onread_cb, this);
276                 }
277
278                 void RemoveConnection ()
279                 {
280                         if (last_listener == null)
281                                 epl.RemoveConnection (this);
282                         else
283                                 last_listener.RemoveConnection (this);
284                 }
285
286                 enum InputState {
287                         RequestLine,
288                         Headers
289                 }
290
291                 enum LineState {
292                         None,
293                         CR,
294                         LF
295                 }
296
297                 InputState input_state = InputState.RequestLine;
298                 LineState line_state = LineState.None;
299                 int position;
300
301                 // true -> done processing
302                 // false -> need more input
303                 bool ProcessInput (MemoryStream ms)
304                 {
305                         byte [] buffer = ms.GetBuffer ();
306                         int len = (int) ms.Length;
307                         int used = 0;
308                         string line;
309
310                         while (true) {
311                                 if (context.HaveError)
312                                         return true;
313
314                                 if (position >= len)
315                                         break;
316
317                                 try {
318                                         line = ReadLine (buffer, position, len - position, ref used);
319                                         position += used;
320                                 } catch {
321                                         context.ErrorMessage = "Bad request";
322                                         context.ErrorStatus = 400;
323                                         return true;
324                                 }
325
326                                 if (line == null)
327                                         break;
328
329                                 if (line == "") {
330                                         if (input_state == InputState.RequestLine)
331                                                 continue;
332                                         current_line = null;
333                                         ms = null;
334                                         return true;
335                                 }
336
337                                 if (input_state == InputState.RequestLine) {
338                                         context.Request.SetRequestLine (line);
339                                         input_state = InputState.Headers;
340                                 } else {
341                                         try {
342                                                 context.Request.AddHeader (line);
343                                         } catch (Exception e) {
344                                                 context.ErrorMessage = e.Message;
345                                                 context.ErrorStatus = 400;
346                                                 return true;
347                                         }
348                                 }
349                         }
350
351                         if (used == len) {
352                                 ms.SetLength (0);
353                                 position = 0;
354                         }
355                         return false;
356                 }
357
358                 string ReadLine (byte [] buffer, int offset, int len, ref int used)
359                 {
360                         if (current_line == null)
361                                 current_line = new StringBuilder (128);
362                         int last = offset + len;
363                         used = 0;
364                         for (int i = offset; i < last && line_state != LineState.LF; i++) {
365                                 used++;
366                                 byte b = buffer [i];
367                                 if (b == 13) {
368                                         line_state = LineState.CR;
369                                 } else if (b == 10) {
370                                         line_state = LineState.LF;
371                                 } else {
372                                         current_line.Append ((char) b);
373                                 }
374                         }
375
376                         string result = null;
377                         if (line_state == LineState.LF) {
378                                 line_state = LineState.None;
379                                 result = current_line.ToString ();
380                                 current_line.Length = 0;
381                         }
382
383                         return result;
384                 }
385
386                 public void SendError (string msg, int status)
387                 {
388                         try {
389                                 HttpListenerResponse response = context.Response;
390                                 response.StatusCode = status;
391                                 response.ContentType = "text/html";
392                                 string description = HttpListenerResponseHelper.GetStatusDescription (status);
393                                 string str;
394                                 if (msg != null)
395                                         str = String.Format ("<h1>{0} ({1})</h1>", description, msg);
396                                 else
397                                         str = String.Format ("<h1>{0}</h1>", description);
398
399                                 byte [] error = context.Response.ContentEncoding.GetBytes (str);
400                                 response.Close (error, false);
401                         } catch {
402                                 // response was already closed
403                         }
404                 }
405
406                 public void SendError ()
407                 {
408                         SendError (context.ErrorMessage, context.ErrorStatus);
409                 }
410
411                 void Unbind ()
412                 {
413                         if (context_bound) {
414                                 epl.UnbindContext (context);
415                                 context_bound = false;
416                         }
417                 }
418
419                 public void Close ()
420                 {
421                         Close (false);
422                 }
423
424                 void CloseSocket ()
425                 {
426                         if (sock == null)
427                                 return;
428
429                         try {
430                                 sock.Close ();
431                         } catch {
432                         } finally {
433                                 sock = null;
434                         }
435                         RemoveConnection ();
436                 }
437
438                 internal void Close (bool force_close)
439                 {
440                         if (sock != null) {
441                                 Stream st = GetResponseStream ();
442                                 if (st != null)
443                                         st.Close ();
444
445                                 o_stream = null;
446                         }
447
448                         if (sock != null) {
449                                 force_close |= !context.Request.KeepAlive;
450                                 if (!force_close)
451                                         force_close = (context.Response.Headers ["connection"] == "close");
452                                 /*
453                                 if (!force_close) {
454 //                                      bool conn_close = (status_code == 400 || status_code == 408 || status_code == 411 ||
455 //                                                      status_code == 413 || status_code == 414 || status_code == 500 ||
456 //                                                      status_code == 503);
457
458                                         force_close |= (context.Request.ProtocolVersion <= HttpVersion.Version10);
459                                 }
460                                 */
461
462                                 if (!force_close && context.Request.FlushInput ()) {
463                                         if (chunked && context.Response.ForceCloseChunked == false) {
464                                                 // Don't close. Keep working.
465                                                 reuses++;
466                                                 Unbind ();
467                                                 Init ();
468                                                 BeginReadRequest ();
469                                                 return;
470                                         }
471
472                                         reuses++;
473                                         Unbind ();
474                                         Init ();
475                                         BeginReadRequest ();
476                                         return;
477                                 }
478
479                                 Socket s = sock;
480                                 sock = null;
481                                 try {
482                                         if (s != null)
483                                                 s.Shutdown (SocketShutdown.Both);
484                                 } catch {
485                                 } finally {
486                                         if (s != null)
487                                                 s.Close ();
488                                 }
489                                 Unbind ();
490                                 RemoveConnection ();
491                                 return;
492                         }
493                 }
494         }
495 }
496 #endif
497