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