Merge branch 'master' of github.com:mono/mono
[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                                 foreach (var key in hrr.Headers.AllKeys)
248                                         rp.Headers [key] = hrr.Headers [key];
249                                 ret.Properties.Add (HttpResponseMessageProperty.Name, rp);
250
251                                 channelResult.Response = ret;
252                                 channelResult.Complete ();
253                         } catch (Exception ex) {
254                                 channelResult.Complete (ex);
255                         } finally {
256                                 res.Close ();   
257                         }
258                 }
259
260                 public override IAsyncResult BeginRequest (Message message, TimeSpan timeout, AsyncCallback callback, object state)
261                 {
262                         ThrowIfDisposedOrNotOpen ();
263
264                         HttpChannelRequestAsyncResult result = new HttpChannelRequestAsyncResult (message, timeout, this, callback, state);
265                         BeginProcessRequest (result);
266                         return result;
267                 }
268
269                 public override Message EndRequest (IAsyncResult result)
270                 {
271                         if (result == null)
272                                 throw new ArgumentNullException ("result");
273                         HttpChannelRequestAsyncResult r = result as HttpChannelRequestAsyncResult;
274                         if (r == null)
275                                 throw new InvalidOperationException ("Wrong IAsyncResult");
276                         r.WaitEnd ();
277                         return r.Response;
278                 }
279
280                 // Abort
281
282                 protected override void OnAbort ()
283                 {
284                         foreach (var web_request in web_requests)
285                                 web_request.Abort ();
286                         web_requests.Clear ();
287                 }
288
289                 // Close
290
291                 protected override void OnClose (TimeSpan timeout)
292                 {
293                         OnAbort ();
294                 }
295
296                 protected override IAsyncResult OnBeginClose (TimeSpan timeout, AsyncCallback callback, object state)
297                 {
298                         OnAbort ();
299                         return base.OnBeginClose (timeout, callback, state);
300                 }
301
302                 protected override void OnEndClose (IAsyncResult result)
303                 {
304                         base.OnEndClose (result);
305                 }
306
307                 // Open
308
309                 protected override void OnOpen (TimeSpan timeout)
310                 {
311                 }
312
313                 [MonoTODO ("find out what to do here")]
314                 protected override IAsyncResult OnBeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
315                 {
316                         return base.OnBeginOpen (timeout, callback, state);
317                 }
318
319                 [MonoTODO ("find out what to do here")]
320                 protected override void OnEndOpen (IAsyncResult result)
321                 {
322                         base.OnEndOpen (result);
323                 }
324
325                 class HttpChannelRequestAsyncResult : IAsyncResult, IDisposable
326                 {
327                         public Message Message {
328                                 get; private set;
329                         }
330                         
331                         public TimeSpan Timeout {
332                                 get; private set;
333                         }
334
335                         AsyncCallback callback;
336                         ManualResetEvent wait;
337                         Exception error;
338                         object locker = new object ();
339                         bool is_completed;
340                         HttpRequestChannel owner;
341
342                         public HttpChannelRequestAsyncResult (Message message, TimeSpan timeout, HttpRequestChannel owner, AsyncCallback callback, object state)
343                         {
344                                 Message = message;
345                                 Timeout = timeout;
346                                 this.owner = owner;
347                                 this.callback = callback;
348                                 AsyncState = state;
349                         }
350
351                         public Message Response {
352                                 get; set;
353                         }
354
355                         public WebRequest WebRequest { get; set; }
356
357                         public WaitHandle AsyncWaitHandle {
358                                 get {
359                                         lock (locker) {
360                                                 if (wait == null)
361                                                         wait = new ManualResetEvent (is_completed);
362                                         }
363                                         return wait;
364                                 }
365                         }
366
367                         public object AsyncState {
368                                 get; private set;
369                         }
370
371                         public void Complete ()
372                         {
373                                 Complete (null);
374                         }
375                         
376                         public void Complete (Exception ex)
377                         {
378                                 if (IsCompleted) {
379                                         return;
380                                 }
381                                 // If we've already stored an error, don't replace it
382                                 error = error ?? ex;
383
384                                 IsCompleted = true;
385                                 if (callback != null)
386                                         callback (this);
387                         }
388                         
389                         public bool CompletedSynchronously {
390                                 get; set;
391                         }
392
393                         public bool IsCompleted {
394                                 get { return is_completed; }
395                                 set {
396                                         is_completed = value;
397                                         lock (locker) {
398                                                 if (is_completed && wait != null)
399                                                         wait.Set ();
400                                                 Cleanup ();
401                                         }
402                                 }
403                         }
404
405                         public void WaitEnd ()
406                         {
407                                 if (!IsCompleted) {
408                                         // FIXME: Do we need to use the timeout? If so, what happens when the timeout is reached.
409                                         // Is the current request cancelled and an exception thrown? If so we need to pass the
410                                         // exception to the Complete () method and allow the result to complete 'normally'.
411 #if NET_2_1
412                                         // neither Moonlight nor MonoTouch supports contexts (WaitOne default to false)
413                                         bool result = AsyncWaitHandle.WaitOne (Timeout);
414 #else
415                                         bool result = AsyncWaitHandle.WaitOne (Timeout, true);
416 #endif
417                                         if (!result)
418                                                 throw new TimeoutException ();
419                                 }
420                                 if (error != null)
421                                         throw error;
422                         }
423                         
424                         public void Dispose ()
425                         {
426                                 Cleanup ();
427                         }
428                         
429                         void Cleanup ()
430                         {
431                                 owner.web_requests.Remove (WebRequest);
432                         }
433                 }
434         }
435 }