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