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