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