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