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