2010-04-02 Atsushi Enomoto <atsushi@ximian.com>
[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                                 using (var responseStream = resstr) {
207                                         MemoryStream ms = new MemoryStream ();
208                                         byte [] b = new byte [65536];
209                                         int n = 0;
210
211                                         while (true) {
212                                                 n = responseStream.Read (b, 0, 65536);
213                                                 if (n == 0)
214                                                         break;
215                                                 ms.Write (b, 0, n);
216                                         }
217                                         ms.Seek (0, SeekOrigin.Begin);
218
219                                         Message ret = Encoder.ReadMessage (
220                                                 ms, (int) source.Transport.MaxReceivedMessageSize, res.ContentType);
221                                         var rp = new HttpResponseMessageProperty () { StatusCode = hrr.StatusCode, StatusDescription = hrr.StatusDescription };
222                                         foreach (var key in hrr.Headers.AllKeys)
223                                                 rp.Headers [key] = hrr.Headers [key];
224                                         ret.Properties.Add (HttpResponseMessageProperty.Name, rp);
225 /*
226 MessageBuffer buf = ret.CreateBufferedCopy (0x10000);
227 ret = buf.CreateMessage ();
228 System.Xml.XmlTextWriter w = new System.Xml.XmlTextWriter (Console.Out);
229 w.Formatting = System.Xml.Formatting.Indented;
230 buf.CreateMessage ().WriteMessage (w);
231 w.Close ();
232 */
233                                         channelResult.Response = ret;
234                                         channelResult.Complete ();
235                                 }
236                         } catch (Exception ex) {
237                                 channelResult.Complete (ex);
238                         } finally {
239                                 res.Close ();   
240                         }
241                 }
242
243                 public override IAsyncResult BeginRequest (Message message, TimeSpan timeout, AsyncCallback callback, object state)
244                 {
245                         ThrowIfDisposedOrNotOpen ();
246
247                         HttpChannelRequestAsyncResult result = new HttpChannelRequestAsyncResult (message, timeout, callback, state);
248                         BeginProcessRequest (result);
249                         return result;
250                 }
251
252                 public override Message EndRequest (IAsyncResult result)
253                 {
254                         if (result == null)
255                                 throw new ArgumentNullException ("result");
256                         HttpChannelRequestAsyncResult r = result as HttpChannelRequestAsyncResult;
257                         if (r == null)
258                                 throw new InvalidOperationException ("Wrong IAsyncResult");
259                         r.WaitEnd ();
260                         return r.Response;
261                 }
262
263                 // Abort
264
265                 protected override void OnAbort ()
266                 {
267                         if (web_request != null)
268                                 web_request.Abort ();
269                         web_request = null;
270                 }
271
272                 // Close
273
274                 protected override void OnClose (TimeSpan timeout)
275                 {
276                         if (web_request != null)
277                                 web_request.Abort ();
278                         web_request = null;
279                 }
280
281                 protected override IAsyncResult OnBeginClose (TimeSpan timeout, AsyncCallback callback, object state)
282                 {
283                         throw new NotImplementedException ();
284                 }
285
286                 protected override void OnEndClose (IAsyncResult result)
287                 {
288                         throw new NotImplementedException ();
289                 }
290
291                 // Open
292
293                 protected override void OnOpen (TimeSpan timeout)
294                 {
295                 }
296
297                 protected override IAsyncResult OnBeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
298                 {
299                         throw new NotImplementedException ();
300                 }
301
302                 protected override void OnEndOpen (IAsyncResult result)
303                 {
304                         throw new NotImplementedException ();
305                 }
306
307                 class HttpChannelRequestAsyncResult : IAsyncResult
308                 {
309                         public Message Message {
310                                 get; private set;
311                         }
312                         
313                         public TimeSpan Timeout {
314                                 get; private set;
315                         }
316
317                         AsyncCallback callback;
318                         ManualResetEvent wait;
319                         Exception error;
320
321                         public HttpChannelRequestAsyncResult (Message message, TimeSpan timeout, AsyncCallback callback, object state)
322                         {
323                                 CompletedSynchronously = true;
324                                 Message = message;
325                                 Timeout = timeout;
326                                 this.callback = callback;
327                                 AsyncState = state;
328
329                                 wait = new ManualResetEvent (false);
330                         }
331
332                         public Message Response {
333                                 get; set;
334                         }
335
336                         public WaitHandle AsyncWaitHandle {
337                                 get { return wait; }
338                         }
339
340                         public object AsyncState {
341                                 get; private set;
342                         }
343
344                         public void Complete ()
345                         {
346                                 Complete (null);
347                         }
348                         
349                         public void Complete (Exception ex)
350                         {
351                                 if (IsCompleted) {
352                                         return;
353                                 }
354                                 // If we've already stored an error, don't replace it
355                                 error = error ?? ex;
356
357                                 IsCompleted = true;
358                                 wait.Set ();
359                                 if (callback != null)
360                                         callback (this);
361                         }
362                         
363                         public bool CompletedSynchronously {
364                                 get; set;
365                         }
366
367                         public bool IsCompleted {
368                                 get; private set;
369                         }
370
371                         public void WaitEnd ()
372                         {
373                                 if (!IsCompleted) {
374                                         // FIXME: Do we need to use the timeout? If so, what happens when the timeout is reached.
375                                         // Is the current request cancelled and an exception thrown? If so we need to pass the
376                                         // exception to the Complete () method and allow the result to complete 'normally'.
377 #if NET_2_1
378                                         // neither Moonlight nor MonoTouch supports contexts (WaitOne default to false)
379                                         bool result = wait.WaitOne (Timeout);
380 #else
381                                         bool result = wait.WaitOne (Timeout, true);
382 #endif
383                                         if (!result)
384                                                 throw new TimeoutException ();
385                                 }
386                                 if (error != null)
387                                         throw error;
388                         }
389                 }
390         }
391 }