Merge pull request #3528 from BrzVlad/fix-sgen-check-before-collections
[mono.git] / mcs / class / System.ServiceModel / System.ServiceModel.Channels / HttpRequestChannel.cs
1 //
2 // HttpRequestChannel.cs 
3 //
4 // Author:
5 //      Atsushi Enomoto <atsushi@ximian.com>
6 //
7 // Copyright (C) 2006 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 using System;
29 using System.Collections.Generic;
30 using System.IO;
31 using System.Net;
32 using System.Net.Security;
33 using System.ServiceModel;
34 using System.ServiceModel.Description;
35 using System.ServiceModel.Security;
36 using System.Threading;
37
38 namespace System.ServiceModel.Channels
39 {
40         internal class HttpRequestChannel : RequestChannelBase
41         {
42                 HttpChannelFactory<IRequestChannel> source;
43
44                 List<WebRequest> web_requests = new List<WebRequest> ();
45
46                 // Constructor
47
48                 public HttpRequestChannel (HttpChannelFactory<IRequestChannel> factory,
49                         EndpointAddress address, Uri via)
50                         : base (factory, address, via)
51                 {
52                         this.source = factory;
53                 }
54
55                 public MessageEncoder Encoder {
56                         get { return source.MessageEncoder; }
57                 }
58
59 #if MOBILE
60                 public override T GetProperty<T> ()
61                 {
62                         if (typeof (T) == typeof (IHttpCookieContainerManager))
63                                 return source.GetProperty<T> ();
64                         return base.GetProperty<T> ();
65                 }
66 #endif
67
68                 // Request
69
70                 public override Message Request (Message message, TimeSpan timeout)
71                 {
72                         return EndRequest (BeginRequest (message, timeout, null, null));
73                 }
74
75                 void BeginProcessRequest (HttpChannelRequestAsyncResult result)
76                 {
77                         Message message = result.Message;
78                         TimeSpan timeout = result.Timeout;
79                         // FIXME: is distination really like this?
80                         Uri destination = message.Headers.To;
81                         if (destination == null) {
82                                 if (source.Transport.ManualAddressing)
83                                         throw new InvalidOperationException ("When manual addressing is enabled on the transport, every request messages must be set its destination address.");
84                                  else
85                                         destination = Via ?? RemoteAddress.Uri;
86                         }
87
88                         var web_request = (HttpWebRequest) HttpWebRequest.Create (destination);
89                         web_requests.Add (web_request);
90                         result.WebRequest = web_request;
91                         web_request.Method = "POST";
92                         web_request.ContentType = Encoder.ContentType;
93                         HttpWebRequest hwr = (web_request as HttpWebRequest);
94                         var cmgr = source.GetProperty<IHttpCookieContainerManager> ();
95                         if (cmgr != null)
96                                 hwr.CookieContainer = cmgr.CookieContainer;
97
98                         // client authentication (while SL3 has NetworkCredential class, it is not implemented yet. So, it is non-SL only.)
99                         var httpbe = (HttpTransportBindingElement) source.Transport;
100                         string authType = null;
101                         switch (httpbe.AuthenticationScheme) {
102                         // AuthenticationSchemes.Anonymous is the default, ignored.
103                         case AuthenticationSchemes.Basic:
104                                 authType = "Basic";
105                                 break;
106                         case AuthenticationSchemes.Digest:
107                                 authType = "Digest";
108                                 break;
109                         case AuthenticationSchemes.Ntlm:
110                                 authType = "Ntlm";
111                                 break;
112                         case AuthenticationSchemes.Negotiate:
113                                 authType = "Negotiate";
114                                 break;
115                         }
116                         if (authType != null) {
117                                 var cred = source.ClientCredentials;
118                                 string user = cred != null ? cred.UserName.UserName : null;
119                                 string pwd = cred != null ? cred.UserName.Password : null;
120                                 if (String.IsNullOrEmpty (user))
121                                         throw new InvalidOperationException (String.Format ("Use ClientCredentials to specify a user name for required HTTP {0} authentication.", authType));
122                                 var nc = new NetworkCredential (user, pwd);
123                                 web_request.Credentials = nc;
124                                 // FIXME: it is said required in SL4, but it blocks full WCF.
125                                 //web_request.UseDefaultCredentials = false;
126                         }
127
128                         web_request.Timeout = (int) timeout.TotalMilliseconds;
129                         web_request.KeepAlive = httpbe.KeepAliveEnabled;
130
131                         // There is no SOAP Action/To header when AddressingVersion is None.
132                         if (message.Version.Envelope.Equals (EnvelopeVersion.Soap11) ||
133                             message.Version.Addressing.Equals (AddressingVersion.None)) {
134                                 if (message.Headers.Action != null) {
135                                         web_request.Headers ["SOAPAction"] = String.Concat ("\"", message.Headers.Action, "\"");
136                                         message.Headers.RemoveAll ("Action", message.Version.Addressing.Namespace);
137                                 }
138                         }
139
140                         // apply HttpRequestMessageProperty if exists.
141                         bool suppressEntityBody = false;
142                         string pname = HttpRequestMessageProperty.Name;
143                         if (message.Properties.ContainsKey (pname)) {
144                                 HttpRequestMessageProperty hp = (HttpRequestMessageProperty) message.Properties [pname];
145                                 foreach (var key in hp.Headers.AllKeys) {
146                                         if (WebHeaderCollection.IsRestricted (key)) { // do not ignore this. WebHeaderCollection rejects restricted ones.
147                                                 // FIXME: huh, there should be any better way to do such stupid conversion.
148                                                 switch (key) {
149                                                 case "Accept":
150                                                         web_request.Accept = hp.Headers [key];
151                                                         break;
152                                                 case "Connection":
153                                                         web_request.Connection = hp.Headers [key];
154                                                         break;
155                                                 //case "ContentLength":
156                                                 //      web_request.ContentLength = hp.Headers [key];
157                                                 //      break;
158                                                 case "ContentType":
159                                                         web_request.ContentType = hp.Headers [key];
160                                                         break;
161                                                 //case "Date":
162                                                 //      web_request.Date = hp.Headers [key];
163                                                 //      break;
164                                                 case "Expect":
165                                                         web_request.Expect = hp.Headers [key];
166                                                         break;
167                                                 case "Host":
168                                                         web_request.Host = hp.Headers [key];
169                                                         break;
170                                                 //case "If-Modified-Since":
171                                                 //      web_request.IfModifiedSince = hp.Headers [key];
172                                                 //      break;
173                                                 case "Referer":
174                                                         web_request.Referer = hp.Headers [key];
175                                                         break;
176                                                 case "Transfer-Encoding":
177                                                         web_request.TransferEncoding = hp.Headers [key];
178                                                         break;
179                                                 case "User-Agent":
180                                                         web_request.UserAgent = hp.Headers [key];
181                                                         break;
182                                                 }
183                                         }
184                                         else
185                                                 web_request.Headers [key] = hp.Headers [key];
186                                 }
187                                 web_request.Method = hp.Method;
188                                 // FIXME: do we have to handle hp.QueryString ?
189                                 if (hp.SuppressEntityBody)
190                                         suppressEntityBody = true;
191                         }
192
193 #if !MOBILE
194                         if (source.ClientCredentials != null) {
195                                 var cred = source.ClientCredentials;
196                                 if ((cred.ClientCertificate != null) && (cred.ClientCertificate.Certificate != null))
197                                         ((HttpWebRequest)web_request).ClientCertificates.Add (cred.ClientCertificate.Certificate);
198                         }
199 #endif
200
201                         if (!suppressEntityBody && String.Compare (web_request.Method, "GET", StringComparison.OrdinalIgnoreCase) != 0) {
202                                 MemoryStream buffer = new MemoryStream ();
203                                 Encoder.WriteMessage (message, buffer);
204
205                                 if (buffer.Length > int.MaxValue)
206                                         throw new InvalidOperationException ("The argument message is too large.");
207
208                                 web_request.ContentLength = (int) buffer.Length;
209
210                                 web_request.BeginGetRequestStream (delegate (IAsyncResult r) {
211                                         try {
212                                                 result.CompletedSynchronously &= r.CompletedSynchronously;
213                                                 using (Stream s = web_request.EndGetRequestStream (r))
214                                                         s.Write (buffer.GetBuffer (), 0, (int) buffer.Length);
215                                                 web_request.BeginGetResponse (GotResponse, result);
216                                         } catch (WebException ex) {
217                                                 switch (ex.Status) {
218                                                 case WebExceptionStatus.NameResolutionFailure:
219                                                 case WebExceptionStatus.ConnectFailure:
220                                                         result.Complete (new EndpointNotFoundException (new EndpointNotFoundException ().Message, ex));
221                                                         break;
222                                                 default:
223                                                         result.Complete (ex);
224                                                         break;
225                                                 }
226                                         } catch (Exception ex) {
227                                                 result.Complete (ex);
228                                         }
229                                 }, null);
230                         } else {
231                                 web_request.BeginGetResponse (GotResponse, result);
232                         }
233                 }
234                 
235                 void GotResponse (IAsyncResult result)
236                 {
237                         HttpChannelRequestAsyncResult channelResult = (HttpChannelRequestAsyncResult) result.AsyncState;
238                         channelResult.CompletedSynchronously &= result.CompletedSynchronously;
239                         
240                         WebResponse res;
241                         Stream resstr;
242                         try {
243                                 res = channelResult.WebRequest.EndGetResponse (result);
244                                 resstr = res.GetResponseStream ();
245                         } catch (WebException we) {
246                                 res = we.Response;
247                                 if (res == null) {
248                                         channelResult.Complete (we);
249                                         return;
250                                 }
251
252
253                                 var hrr2 = (HttpWebResponse) res;
254                                 
255                                 if ((int) hrr2.StatusCode >= 400 && (int) hrr2.StatusCode < 500) {
256                                         Exception exception = new WebException (
257                                                 String.Format ("There was an error on processing web request: Status code {0}({1}): {2}",
258                                                                (int) hrr2.StatusCode, hrr2.StatusCode, hrr2.StatusDescription), null,
259                                                 WebExceptionStatus.ProtocolError, hrr2); 
260                                         
261                                         if ((int) hrr2.StatusCode == 404) {
262                                                 // Throw the same exception .NET does
263                                                 exception = new EndpointNotFoundException (
264                                                         "There was no endpoint listening at {0} that could accept the message. This is often caused by an incorrect address " +
265                                                         "or SOAP action. See InnerException, if present, for more details.",
266                                                         exception);
267                                         }
268                                         
269                                         channelResult.Complete (exception);
270                                         return;
271                                 }
272
273
274                                 try {
275                                         // The response might contain SOAP fault. It might not.
276                                         resstr = res.GetResponseStream ();
277                                 } catch (WebException we2) {
278                                         channelResult.Complete (we2);
279                                         return;
280                                 }
281                         }
282
283                         var hrr = (HttpWebResponse) res;
284                         if ((int) hrr.StatusCode >= 400 && (int) hrr.StatusCode < 500) {
285                                 channelResult.Complete (new WebException (String.Format ("There was an error on processing web request: Status code {0}({1}): {2}", (int) hrr.StatusCode, hrr.StatusCode, hrr.StatusDescription)));
286                         }
287
288                         try {
289                                 Message ret;
290
291                                 // TODO: unit test to make sure an empty response never throws
292                                 // an exception at this level
293                                 if (hrr.ContentLength == 0) {
294                                         ret = Message.CreateMessage (Encoder.MessageVersion, String.Empty);
295                                 } else {
296
297                                         using (var responseStream = resstr) {
298                                                 MemoryStream ms = new MemoryStream ();
299                                                 byte [] b = new byte [65536];
300                                                 int n = 0;
301
302                                                 while (true) {
303                                                         n = responseStream.Read (b, 0, 65536);
304                                                         if (n == 0)
305                                                                 break;
306                                                         ms.Write (b, 0, n);
307                                                 }
308                                                 ms.Seek (0, SeekOrigin.Begin);
309
310                                                 ret = Encoder.ReadMessage (
311                                                         ms, (int) source.Transport.MaxReceivedMessageSize, res.ContentType);
312                                         }
313                                 }
314
315                                 var rp = new HttpResponseMessageProperty () { StatusCode = hrr.StatusCode, StatusDescription = hrr.StatusDescription };
316                                 foreach (var key in hrr.Headers.AllKeys)
317                                         rp.Headers [key] = hrr.Headers [key];
318                                 ret.Properties.Add (HttpResponseMessageProperty.Name, rp);
319
320                                 channelResult.Response = ret;
321                                 channelResult.Complete ();
322                         } catch (Exception ex) {
323                                 channelResult.Complete (ex);
324                         } finally {
325                                 res.Close ();   
326                         }
327                 }
328
329                 public override IAsyncResult BeginRequest (Message message, TimeSpan timeout, AsyncCallback callback, object state)
330                 {
331                         ThrowIfDisposedOrNotOpen ();
332
333                         HttpChannelRequestAsyncResult result = new HttpChannelRequestAsyncResult (message, timeout, this, callback, state);
334                         BeginProcessRequest (result);
335                         return result;
336                 }
337
338                 public override Message EndRequest (IAsyncResult result)
339                 {
340                         if (result == null)
341                                 throw new ArgumentNullException ("result");
342                         HttpChannelRequestAsyncResult r = result as HttpChannelRequestAsyncResult;
343                         if (r == null)
344                                 throw new InvalidOperationException ("Wrong IAsyncResult");
345                         r.WaitEnd ();
346                         return r.Response;
347                 }
348
349                 // Abort
350
351                 protected override void OnAbort ()
352                 {
353                         foreach (var web_request in web_requests.ToArray ())
354                                 web_request.Abort ();
355                         web_requests.Clear ();
356                 }
357
358                 // Close
359
360                 protected override void OnClose (TimeSpan timeout)
361                 {
362                         OnAbort ();
363                 }
364
365                 protected override IAsyncResult OnBeginClose (TimeSpan timeout, AsyncCallback callback, object state)
366                 {
367                         OnAbort ();
368                         return base.OnBeginClose (timeout, callback, state);
369                 }
370
371                 protected override void OnEndClose (IAsyncResult result)
372                 {
373                         base.OnEndClose (result);
374                 }
375
376                 // Open
377
378                 protected override void OnOpen (TimeSpan timeout)
379                 {
380                 }
381
382                 [MonoTODO ("find out what to do here")]
383                 protected override IAsyncResult OnBeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
384                 {
385                         return base.OnBeginOpen (timeout, callback, state);
386                 }
387
388                 [MonoTODO ("find out what to do here")]
389                 protected override void OnEndOpen (IAsyncResult result)
390                 {
391                         base.OnEndOpen (result);
392                 }
393
394                 class HttpChannelRequestAsyncResult : IAsyncResult, IDisposable
395                 {
396                         public Message Message {
397                                 get; private set;
398                         }
399                         
400                         public TimeSpan Timeout {
401                                 get; private set;
402                         }
403
404                         AsyncCallback callback;
405                         ManualResetEvent wait;
406                         Exception error;
407                         object locker = new object ();
408                         bool is_completed;
409                         HttpRequestChannel owner;
410
411                         public HttpChannelRequestAsyncResult (Message message, TimeSpan timeout, HttpRequestChannel owner, AsyncCallback callback, object state)
412                         {
413                                 Message = message;
414                                 Timeout = timeout;
415                                 this.owner = owner;
416                                 this.callback = callback;
417                                 AsyncState = state;
418                         }
419
420                         public Message Response {
421                                 get; set;
422                         }
423
424                         public WebRequest WebRequest { get; set; }
425
426                         public WaitHandle AsyncWaitHandle {
427                                 get {
428                                         lock (locker) {
429                                                 if (wait == null)
430                                                         wait = new ManualResetEvent (is_completed);
431                                         }
432                                         return wait;
433                                 }
434                         }
435
436                         public object AsyncState {
437                                 get; private set;
438                         }
439
440                         public void Complete ()
441                         {
442                                 Complete (null);
443                         }
444                         
445                         public void Complete (Exception ex)
446                         {
447                                 if (IsCompleted) {
448                                         return;
449                                 }
450                                 // If we've already stored an error, don't replace it
451                                 error = error ?? ex;
452
453                                 IsCompleted = true;
454                                 if (callback != null)
455                                         callback (this);
456                         }
457                         
458                         public bool CompletedSynchronously {
459                                 get; set;
460                         }
461
462                         public bool IsCompleted {
463                                 get { return is_completed; }
464                                 set {
465                                         is_completed = value;
466                                         lock (locker) {
467                                                 if (is_completed && wait != null)
468                                                         wait.Set ();
469                                                 Cleanup ();
470                                         }
471                                 }
472                         }
473
474                         public void WaitEnd ()
475                         {
476                                 if (!IsCompleted) {
477                                         // FIXME: Do we need to use the timeout? If so, what happens when the timeout is reached.
478                                         // Is the current request cancelled and an exception thrown? If so we need to pass the
479                                         // exception to the Complete () method and allow the result to complete 'normally'.
480 #if MOBILE
481                                         // neither Moonlight nor MonoTouch supports contexts (WaitOne default to false)
482                                         bool result = AsyncWaitHandle.WaitOne (Timeout);
483 #else
484                                         bool result = AsyncWaitHandle.WaitOne (Timeout, true);
485 #endif
486                                         if (!result)
487                                                 throw new TimeoutException ();
488                                 }
489                                 if (error != null)
490                                         throw error;
491                         }
492                         
493                         public void Dispose ()
494                         {
495                                 Cleanup ();
496                         }
497                         
498                         void Cleanup ()
499                         {
500                                 owner.web_requests.Remove (WebRequest);
501                         }
502                 }
503         }
504 }