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