[WCF] bonus, NET_2_1 is blocking set_Timeout. It didn't exist in Moonlight.
[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 NET_2_1
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
130                         // There is no SOAP Action/To header when AddressingVersion is None.
131                         if (message.Version.Envelope.Equals (EnvelopeVersion.Soap11) ||
132                             message.Version.Addressing.Equals (AddressingVersion.None)) {
133                                 if (message.Headers.Action != null) {
134                                         web_request.Headers ["SOAPAction"] = String.Concat ("\"", message.Headers.Action, "\"");
135                                         message.Headers.RemoveAll ("Action", message.Version.Addressing.Namespace);
136                                 }
137                         }
138
139                         // apply HttpRequestMessageProperty if exists.
140                         bool suppressEntityBody = false;
141                         string pname = HttpRequestMessageProperty.Name;
142                         if (message.Properties.ContainsKey (pname)) {
143                                 HttpRequestMessageProperty hp = (HttpRequestMessageProperty) message.Properties [pname];
144                                 foreach (var key in hp.Headers.AllKeys) {
145                                         if (WebHeaderCollection.IsRestricted (key)) { // do not ignore this. WebHeaderCollection rejects restricted ones.
146                                                 // FIXME: huh, there should be any better way to do such stupid conversion.
147                                                 switch (key) {
148                                                 case "Accept":
149                                                         web_request.Accept = hp.Headers [key];
150                                                         break;
151                                                 case "Connection":
152                                                         web_request.Connection = hp.Headers [key];
153                                                         break;
154                                                 //case "ContentLength":
155                                                 //      web_request.ContentLength = hp.Headers [key];
156                                                 //      break;
157                                                 case "ContentType":
158                                                         web_request.ContentType = hp.Headers [key];
159                                                         break;
160                                                 //case "Date":
161                                                 //      web_request.Date = hp.Headers [key];
162                                                 //      break;
163                                                 case "Expect":
164                                                         web_request.Expect = hp.Headers [key];
165                                                         break;
166                                                 case "Host":
167                                                         web_request.Host = hp.Headers [key];
168                                                         break;
169                                                 //case "If-Modified-Since":
170                                                 //      web_request.IfModifiedSince = hp.Headers [key];
171                                                 //      break;
172                                                 case "Referer":
173                                                         web_request.Referer = hp.Headers [key];
174                                                         break;
175                                                 case "Transfer-Encoding":
176                                                         web_request.TransferEncoding = hp.Headers [key];
177                                                         break;
178                                                 case "User-Agent":
179                                                         web_request.UserAgent = hp.Headers [key];
180                                                         break;
181                                                 }
182                                         }
183                                         else
184                                                 web_request.Headers [key] = hp.Headers [key];
185                                 }
186                                 web_request.Method = hp.Method;
187                                 // FIXME: do we have to handle hp.QueryString ?
188                                 if (hp.SuppressEntityBody)
189                                         suppressEntityBody = true;
190                         }
191
192 #if !NET_2_1
193                         if (source.ClientCredentials != null) {
194                                 var cred = source.ClientCredentials;
195                                 if ((cred.ClientCertificate != null) && (cred.ClientCertificate.Certificate != null))
196                                         ((HttpWebRequest)web_request).ClientCertificates.Add (cred.ClientCertificate.Certificate);
197                         }
198 #endif
199
200                         if (!suppressEntityBody && String.Compare (web_request.Method, "GET", StringComparison.OrdinalIgnoreCase) != 0) {
201                                 MemoryStream buffer = new MemoryStream ();
202                                 Encoder.WriteMessage (message, buffer);
203
204                                 if (buffer.Length > int.MaxValue)
205                                         throw new InvalidOperationException ("The argument message is too large.");
206
207                                 web_request.ContentLength = (int) buffer.Length;
208
209                                 web_request.BeginGetRequestStream (delegate (IAsyncResult r) {
210                                         try {
211                                                 result.CompletedSynchronously &= r.CompletedSynchronously;
212                                                 using (Stream s = web_request.EndGetRequestStream (r))
213                                                         s.Write (buffer.GetBuffer (), 0, (int) buffer.Length);
214                                                 web_request.BeginGetResponse (GotResponse, result);
215                                         } catch (WebException ex) {
216                                                 switch (ex.Status) {
217                                                 case WebExceptionStatus.NameResolutionFailure:
218                                                 case WebExceptionStatus.ConnectFailure:
219                                                         result.Complete (new EndpointNotFoundException (new EndpointNotFoundException ().Message, ex));
220                                                         break;
221                                                 default:
222                                                         result.Complete (ex);
223                                                         break;
224                                                 }
225                                         } catch (Exception ex) {
226                                                 result.Complete (ex);
227                                         }
228                                 }, null);
229                         } else {
230                                 web_request.BeginGetResponse (GotResponse, result);
231                         }
232                 }
233                 
234                 void GotResponse (IAsyncResult result)
235                 {
236                         HttpChannelRequestAsyncResult channelResult = (HttpChannelRequestAsyncResult) result.AsyncState;
237                         channelResult.CompletedSynchronously &= result.CompletedSynchronously;
238                         
239                         WebResponse res;
240                         Stream resstr;
241                         try {
242                                 res = channelResult.WebRequest.EndGetResponse (result);
243                                 resstr = res.GetResponseStream ();
244                         } catch (WebException we) {
245                                 res = we.Response;
246                                 if (res == null) {
247                                         channelResult.Complete (we);
248                                         return;
249                                 }
250
251
252                                 var hrr2 = (HttpWebResponse) res;
253                                 
254                                 if ((int) hrr2.StatusCode >= 400 && (int) hrr2.StatusCode < 500) {
255                                         Exception exception = new WebException (
256                                                 String.Format ("There was an error on processing web request: Status code {0}({1}): {2}",
257                                                                (int) hrr2.StatusCode, hrr2.StatusCode, hrr2.StatusDescription), null,
258                                                 WebExceptionStatus.ProtocolError, hrr2); 
259                                         
260                                         if ((int) hrr2.StatusCode == 404) {
261                                                 // Throw the same exception .NET does
262                                                 exception = new EndpointNotFoundException (
263                                                         "There was no endpoint listening at {0} that could accept the message. This is often caused by an incorrect address " +
264                                                         "or SOAP action. See InnerException, if present, for more details.",
265                                                         exception);
266                                         }
267                                         
268                                         channelResult.Complete (exception);
269                                         return;
270                                 }
271
272
273                                 try {
274                                         // The response might contain SOAP fault. It might not.
275                                         resstr = res.GetResponseStream ();
276                                 } catch (WebException we2) {
277                                         channelResult.Complete (we2);
278                                         return;
279                                 }
280                         }
281
282                         var hrr = (HttpWebResponse) res;
283                         if ((int) hrr.StatusCode >= 400 && (int) hrr.StatusCode < 500) {
284                                 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)));
285                         }
286
287                         try {
288                                 Message ret;
289
290                                 // TODO: unit test to make sure an empty response never throws
291                                 // an exception at this level
292                                 if (hrr.ContentLength == 0) {
293                                         ret = Message.CreateMessage (Encoder.MessageVersion, String.Empty);
294                                 } else {
295
296                                         using (var responseStream = resstr) {
297                                                 MemoryStream ms = new MemoryStream ();
298                                                 byte [] b = new byte [65536];
299                                                 int n = 0;
300
301                                                 while (true) {
302                                                         n = responseStream.Read (b, 0, 65536);
303                                                         if (n == 0)
304                                                                 break;
305                                                         ms.Write (b, 0, n);
306                                                 }
307                                                 ms.Seek (0, SeekOrigin.Begin);
308
309                                                 ret = Encoder.ReadMessage (
310                                                         ms, (int) source.Transport.MaxReceivedMessageSize, res.ContentType);
311                                         }
312                                 }
313
314                                 var rp = new HttpResponseMessageProperty () { StatusCode = hrr.StatusCode, StatusDescription = hrr.StatusDescription };
315                                 foreach (var key in hrr.Headers.AllKeys)
316                                         rp.Headers [key] = hrr.Headers [key];
317                                 ret.Properties.Add (HttpResponseMessageProperty.Name, rp);
318
319                                 channelResult.Response = ret;
320                                 channelResult.Complete ();
321                         } catch (Exception ex) {
322                                 channelResult.Complete (ex);
323                         } finally {
324                                 res.Close ();   
325                         }
326                 }
327
328                 public override IAsyncResult BeginRequest (Message message, TimeSpan timeout, AsyncCallback callback, object state)
329                 {
330                         ThrowIfDisposedOrNotOpen ();
331
332                         HttpChannelRequestAsyncResult result = new HttpChannelRequestAsyncResult (message, timeout, this, callback, state);
333                         BeginProcessRequest (result);
334                         return result;
335                 }
336
337                 public override Message EndRequest (IAsyncResult result)
338                 {
339                         if (result == null)
340                                 throw new ArgumentNullException ("result");
341                         HttpChannelRequestAsyncResult r = result as HttpChannelRequestAsyncResult;
342                         if (r == null)
343                                 throw new InvalidOperationException ("Wrong IAsyncResult");
344                         r.WaitEnd ();
345                         return r.Response;
346                 }
347
348                 // Abort
349
350                 protected override void OnAbort ()
351                 {
352                         foreach (var web_request in web_requests.ToArray ())
353                                 web_request.Abort ();
354                         web_requests.Clear ();
355                 }
356
357                 // Close
358
359                 protected override void OnClose (TimeSpan timeout)
360                 {
361                         OnAbort ();
362                 }
363
364                 protected override IAsyncResult OnBeginClose (TimeSpan timeout, AsyncCallback callback, object state)
365                 {
366                         OnAbort ();
367                         return base.OnBeginClose (timeout, callback, state);
368                 }
369
370                 protected override void OnEndClose (IAsyncResult result)
371                 {
372                         base.OnEndClose (result);
373                 }
374
375                 // Open
376
377                 protected override void OnOpen (TimeSpan timeout)
378                 {
379                 }
380
381                 [MonoTODO ("find out what to do here")]
382                 protected override IAsyncResult OnBeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
383                 {
384                         return base.OnBeginOpen (timeout, callback, state);
385                 }
386
387                 [MonoTODO ("find out what to do here")]
388                 protected override void OnEndOpen (IAsyncResult result)
389                 {
390                         base.OnEndOpen (result);
391                 }
392
393                 class HttpChannelRequestAsyncResult : IAsyncResult, IDisposable
394                 {
395                         public Message Message {
396                                 get; private set;
397                         }
398                         
399                         public TimeSpan Timeout {
400                                 get; private set;
401                         }
402
403                         AsyncCallback callback;
404                         ManualResetEvent wait;
405                         Exception error;
406                         object locker = new object ();
407                         bool is_completed;
408                         HttpRequestChannel owner;
409
410                         public HttpChannelRequestAsyncResult (Message message, TimeSpan timeout, HttpRequestChannel owner, AsyncCallback callback, object state)
411                         {
412                                 Message = message;
413                                 Timeout = timeout;
414                                 this.owner = owner;
415                                 this.callback = callback;
416                                 AsyncState = state;
417                         }
418
419                         public Message Response {
420                                 get; set;
421                         }
422
423                         public WebRequest WebRequest { get; set; }
424
425                         public WaitHandle AsyncWaitHandle {
426                                 get {
427                                         lock (locker) {
428                                                 if (wait == null)
429                                                         wait = new ManualResetEvent (is_completed);
430                                         }
431                                         return wait;
432                                 }
433                         }
434
435                         public object AsyncState {
436                                 get; private set;
437                         }
438
439                         public void Complete ()
440                         {
441                                 Complete (null);
442                         }
443                         
444                         public void Complete (Exception ex)
445                         {
446                                 if (IsCompleted) {
447                                         return;
448                                 }
449                                 // If we've already stored an error, don't replace it
450                                 error = error ?? ex;
451
452                                 IsCompleted = true;
453                                 if (callback != null)
454                                         callback (this);
455                         }
456                         
457                         public bool CompletedSynchronously {
458                                 get; set;
459                         }
460
461                         public bool IsCompleted {
462                                 get { return is_completed; }
463                                 set {
464                                         is_completed = value;
465                                         lock (locker) {
466                                                 if (is_completed && wait != null)
467                                                         wait.Set ();
468                                                 Cleanup ();
469                                         }
470                                 }
471                         }
472
473                         public void WaitEnd ()
474                         {
475                                 if (!IsCompleted) {
476                                         // FIXME: Do we need to use the timeout? If so, what happens when the timeout is reached.
477                                         // Is the current request cancelled and an exception thrown? If so we need to pass the
478                                         // exception to the Complete () method and allow the result to complete 'normally'.
479 #if NET_2_1
480                                         // neither Moonlight nor MonoTouch supports contexts (WaitOne default to false)
481                                         bool result = AsyncWaitHandle.WaitOne (Timeout);
482 #else
483                                         bool result = AsyncWaitHandle.WaitOne (Timeout, true);
484 #endif
485                                         if (!result)
486                                                 throw new TimeoutException ();
487                                 }
488                                 if (error != null)
489                                         throw error;
490                         }
491                         
492                         public void Dispose ()
493                         {
494                                 Cleanup ();
495                         }
496                         
497                         void Cleanup ()
498                         {
499                                 owner.web_requests.Remove (WebRequest);
500                         }
501                 }
502         }
503 }