2009-12-10 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                 // FIXME: supply maxSizeOfHeaders.
47                 int max_headers = 0x10000;
48
49                 // Constructor
50
51                 public HttpRequestChannel (HttpChannelFactory<IRequestChannel> factory,
52                         EndpointAddress address, Uri via)
53                         : base (factory, address, via)
54                 {
55                         this.source = factory;
56                 }
57
58                 public int MaxSizeOfHeaders {
59                         get { return max_headers; }
60                 }
61
62                 public MessageEncoder Encoder {
63                         get { return source.MessageEncoder; }
64                 }
65
66                 // Request
67
68                 public override Message Request (Message message, TimeSpan timeout)
69                 {
70                         return EndRequest (BeginRequest (message, timeout, null, null));
71                 }
72
73                 void BeginProcessRequest (HttpChannelRequestAsyncResult result)
74                 {
75                         Message message = result.Message;
76                         TimeSpan timeout = result.Timeout;
77                         // FIXME: is distination really like this?
78                         Uri destination = message.Headers.To;
79                         if (destination == null) {
80                                 if (source.Source.ManualAddressing)
81                                         throw new InvalidOperationException ("When manual addressing is enabled on the transport, every request messages must be set its destination address.");
82                                  else
83                                         destination = Via ?? RemoteAddress.Uri;
84                         }
85
86                         web_request = HttpWebRequest.Create (destination);
87                         web_request.Method = "POST";
88                         web_request.ContentType = Encoder.ContentType;
89
90 #if !NET_2_1 // until we support NetworkCredential like SL4 will do.
91                         // client authentication (while SL3 has NetworkCredential class, it is not implemented yet. So, it is non-SL only.)
92                         var httpbe = (HttpTransportBindingElement) source.Source;
93                         string authType = null;
94                         switch (httpbe.AuthenticationScheme) {
95                         // AuthenticationSchemes.Anonymous is the default, ignored.
96                         case AuthenticationSchemes.Basic:
97                                 authType = "Basic";
98                                 break;
99                         case AuthenticationSchemes.Digest:
100                                 authType = "Digest";
101                                 break;
102                         case AuthenticationSchemes.Ntlm:
103                                 authType = "Ntlm";
104                                 break;
105                         case AuthenticationSchemes.Negotiate:
106                                 authType = "Negotiate";
107                                 break;
108                         }
109                         if (authType != null) {
110                                 var cred = source.ClientCredentials;
111                                 string user = cred != null ? cred.UserName.UserName : null;
112                                 string pwd = cred != null ? cred.UserName.Password : null;
113                                 if (String.IsNullOrEmpty (user))
114                                         throw new InvalidOperationException (String.Format ("Use ClientCredentials to specify a user name for required HTTP {0} authentication.", authType));
115                                 var nc = new NetworkCredential (user, pwd);
116                                 web_request.Credentials = nc;
117                                 // FIXME: it is said required in SL4, but it blocks full WCF.
118                                 //web_request.UseDefaultCredentials = false;
119                         }
120 #endif
121
122 #if !NET_2_1 // FIXME: implement this to not depend on Timeout property
123                         web_request.Timeout = (int) timeout.TotalMilliseconds;
124 #endif
125
126                         // There is no SOAP Action/To header when AddressingVersion is None.
127                         if (message.Version.Envelope.Equals (EnvelopeVersion.Soap11) ||
128                             message.Version.Addressing.Equals (AddressingVersion.None)) {
129                                 if (message.Headers.Action != null) {
130                                         web_request.Headers ["SOAPAction"] = String.Concat ("\"", message.Headers.Action, "\"");
131                                         message.Headers.RemoveAll ("Action", message.Version.Addressing.Namespace);
132                                 }
133                         }
134
135                         // apply HttpRequestMessageProperty if exists.
136                         bool suppressEntityBody = false;
137 #if !NET_2_1
138                         string pname = HttpRequestMessageProperty.Name;
139                         if (message.Properties.ContainsKey (pname)) {
140                                 HttpRequestMessageProperty hp = (HttpRequestMessageProperty) message.Properties [pname];
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) {
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                                         channelResult.Response = Encoder.ReadMessage (
220                                                 //responseStream, MaxSizeOfHeaders);
221                                                 ms, MaxSizeOfHeaders, res.ContentType);
222 /*
223 MessageBuffer buf = ret.CreateBufferedCopy (0x10000);
224 ret = buf.CreateMessage ();
225 System.Xml.XmlTextWriter w = new System.Xml.XmlTextWriter (Console.Out);
226 w.Formatting = System.Xml.Formatting.Indented;
227 buf.CreateMessage ().WriteMessage (w);
228 w.Close ();
229 */
230                                         channelResult.Complete ();
231                                 }
232                         } catch (Exception ex) {
233                                 channelResult.Complete (ex);
234                         } finally {
235                                 res.Close ();   
236                         }
237                 }
238
239                 public override IAsyncResult BeginRequest (Message message, TimeSpan timeout, AsyncCallback callback, object state)
240                 {
241                         ThrowIfDisposedOrNotOpen ();
242
243                         HttpChannelRequestAsyncResult result = new HttpChannelRequestAsyncResult (message, timeout, callback, state);
244                         BeginProcessRequest (result);
245                         return result;
246                 }
247
248                 public override Message EndRequest (IAsyncResult result)
249                 {
250                         if (result == null)
251                                 throw new ArgumentNullException ("result");
252                         HttpChannelRequestAsyncResult r = result as HttpChannelRequestAsyncResult;
253                         if (r == null)
254                                 throw new InvalidOperationException ("Wrong IAsyncResult");
255                         r.WaitEnd ();
256                         return r.Response;
257                 }
258
259                 // Abort
260
261                 protected override void OnAbort ()
262                 {
263                         if (web_request != null)
264                                 web_request.Abort ();
265                         web_request = null;
266                 }
267
268                 // Close
269
270                 protected override void OnClose (TimeSpan timeout)
271                 {
272                         if (web_request != null)
273                                 web_request.Abort ();
274                         web_request = null;
275                 }
276
277                 protected override IAsyncResult OnBeginClose (TimeSpan timeout, AsyncCallback callback, object state)
278                 {
279                         throw new NotImplementedException ();
280                 }
281
282                 protected override void OnEndClose (IAsyncResult result)
283                 {
284                         throw new NotImplementedException ();
285                 }
286
287                 // Open
288
289                 protected override void OnOpen (TimeSpan timeout)
290                 {
291                 }
292
293                 protected override IAsyncResult OnBeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
294                 {
295                         throw new NotImplementedException ();
296                 }
297
298                 protected override void OnEndOpen (IAsyncResult result)
299                 {
300                         throw new NotImplementedException ();
301                 }
302
303                 class HttpChannelRequestAsyncResult : IAsyncResult
304                 {
305                         public Message Message {
306                                 get; private set;
307                         }
308                         
309                         public TimeSpan Timeout {
310                                 get; private set;
311                         }
312
313                         AsyncCallback callback;
314                         ManualResetEvent wait;
315                         Exception error;
316
317                         public HttpChannelRequestAsyncResult (Message message, TimeSpan timeout, AsyncCallback callback, object state)
318                         {
319                                 CompletedSynchronously = true;
320                                 Message = message;
321                                 Timeout = timeout;
322                                 this.callback = callback;
323                                 AsyncState = state;
324
325                                 wait = new ManualResetEvent (false);
326                         }
327
328                         public Message Response {
329                                 get; set;
330                         }
331
332                         public WaitHandle AsyncWaitHandle {
333                                 get { return wait; }
334                         }
335
336                         public object AsyncState {
337                                 get; private set;
338                         }
339
340                         public void Complete ()
341                         {
342                                 Complete (null);
343                         }
344                         
345                         public void Complete (Exception ex)
346                         {
347                                 if (IsCompleted) {
348                                         return;
349                                 }
350                                 // If we've already stored an error, don't replace it
351                                 error = error ?? ex;
352
353                                 IsCompleted = true;
354                                 wait.Set ();
355                                 if (callback != null)
356                                         callback (this);
357                         }
358                         
359                         public bool CompletedSynchronously {
360                                 get; set;
361                         }
362
363                         public bool IsCompleted {
364                                 get; private set;
365                         }
366
367                         public void WaitEnd ()
368                         {
369                                 if (!IsCompleted) {
370                                         // FIXME: Do we need to use the timeout? If so, what happens when the timeout is reached.
371                                         // Is the current request cancelled and an exception thrown? If so we need to pass the
372                                         // exception to the Complete () method and allow the result to complete 'normally'.
373 #if NET_2_1 || MONOTOUCH
374                                         // neither Moonlight nor MonoTouch supports contexts (WaitOne default to false)
375                                         bool result = wait.WaitOne (Timeout);
376 #else
377                                         bool result = wait.WaitOne (Timeout, true);
378 #endif
379                                         if (!result)
380                                                 throw new TimeoutException ();
381                                 }
382                                 if (error != null)
383                                         throw error;
384                         }
385                 }
386         }
387 }