2010-01-20 Zoltan Varga <vargaz@gmail.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.Transport.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
91                         var cmgr = source.GetProperty<IHttpCookieContainerManager> ();
92                         if (cmgr != null)
93                                 ((HttpWebRequest) web_request).CookieContainer = cmgr.CookieContainer;
94 #endif
95
96 #if !NET_2_1 // until we support NetworkCredential like SL4 will do.
97                         // client authentication (while SL3 has NetworkCredential class, it is not implemented yet. So, it is non-SL only.)
98                         var httpbe = (HttpTransportBindingElement) source.Transport;
99                         string authType = null;
100                         switch (httpbe.AuthenticationScheme) {
101                         // AuthenticationSchemes.Anonymous is the default, ignored.
102                         case AuthenticationSchemes.Basic:
103                                 authType = "Basic";
104                                 break;
105                         case AuthenticationSchemes.Digest:
106                                 authType = "Digest";
107                                 break;
108                         case AuthenticationSchemes.Ntlm:
109                                 authType = "Ntlm";
110                                 break;
111                         case AuthenticationSchemes.Negotiate:
112                                 authType = "Negotiate";
113                                 break;
114                         }
115                         if (authType != null) {
116                                 var cred = source.ClientCredentials;
117                                 string user = cred != null ? cred.UserName.UserName : null;
118                                 string pwd = cred != null ? cred.UserName.Password : null;
119                                 if (String.IsNullOrEmpty (user))
120                                         throw new InvalidOperationException (String.Format ("Use ClientCredentials to specify a user name for required HTTP {0} authentication.", authType));
121                                 var nc = new NetworkCredential (user, pwd);
122                                 web_request.Credentials = nc;
123                                 // FIXME: it is said required in SL4, but it blocks full WCF.
124                                 //web_request.UseDefaultCredentials = false;
125                         }
126 #endif
127
128 #if !NET_2_1 // FIXME: implement this to not depend on Timeout property
129                         web_request.Timeout = (int) timeout.TotalMilliseconds;
130 #endif
131
132                         // There is no SOAP Action/To header when AddressingVersion is None.
133                         if (message.Version.Envelope.Equals (EnvelopeVersion.Soap11) ||
134                             message.Version.Addressing.Equals (AddressingVersion.None)) {
135                                 if (message.Headers.Action != null) {
136                                         web_request.Headers ["SOAPAction"] = String.Concat ("\"", message.Headers.Action, "\"");
137                                         message.Headers.RemoveAll ("Action", message.Version.Addressing.Namespace);
138                                 }
139                         }
140
141                         // apply HttpRequestMessageProperty if exists.
142                         bool suppressEntityBody = false;
143 #if !NET_2_1
144                         string pname = HttpRequestMessageProperty.Name;
145                         if (message.Properties.ContainsKey (pname)) {
146                                 HttpRequestMessageProperty hp = (HttpRequestMessageProperty) message.Properties [pname];
147                                 web_request.Headers.Clear ();
148                                 web_request.Headers.Add (hp.Headers);
149                                 web_request.Method = hp.Method;
150                                 // FIXME: do we have to handle hp.QueryString ?
151                                 if (hp.SuppressEntityBody)
152                                         suppressEntityBody = true;
153                         }
154 #endif
155
156                         if (!suppressEntityBody && String.Compare (web_request.Method, "GET", StringComparison.OrdinalIgnoreCase) != 0) {
157                                 MemoryStream buffer = new MemoryStream ();
158                                 Encoder.WriteMessage (message, buffer);
159
160                                 if (buffer.Length > int.MaxValue)
161                                         throw new InvalidOperationException ("The argument message is too large.");
162
163 #if !NET_2_1
164                                 web_request.ContentLength = (int) buffer.Length;
165 #endif
166
167                                 web_request.BeginGetRequestStream (delegate (IAsyncResult r) {
168                                         try {
169                                                 result.CompletedSynchronously &= r.CompletedSynchronously;
170                                                 using (Stream s = web_request.EndGetRequestStream (r))
171                                                         s.Write (buffer.GetBuffer (), 0, (int) buffer.Length);
172                                                 web_request.BeginGetResponse (GotResponse, result);
173                                         } catch (Exception ex) {
174                                                 result.Complete (ex);
175                                         }
176                                 }, null);
177                         } else {
178                                 web_request.BeginGetResponse (GotResponse, result);
179                         }
180                 }
181                 
182                 void GotResponse (IAsyncResult result)
183                 {
184                         HttpChannelRequestAsyncResult channelResult = (HttpChannelRequestAsyncResult) result.AsyncState;
185                         channelResult.CompletedSynchronously &= result.CompletedSynchronously;
186                         
187                         WebResponse res;
188                         Stream resstr;
189                         try {
190                                 res = web_request.EndGetResponse (result);
191                                 resstr = res.GetResponseStream ();
192                         } catch (WebException we) {
193                                 res = we.Response;
194                                 if (res == null) {
195                                         channelResult.Complete (we);
196                                         return;
197                                 }
198                                 try {
199                                         // The response might contain SOAP fault. It might not.
200                                         resstr = res.GetResponseStream ();
201                                 } catch (WebException we2) {
202                                         channelResult.Complete (we2);
203                                         return;
204                                 }
205                         }
206
207                         var hrr = (HttpWebResponse) res;
208                         if ((int) hrr.StatusCode >= 400) {
209                                 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)));
210                         }
211
212                         try {
213                                 using (var responseStream = resstr) {
214                                         MemoryStream ms = new MemoryStream ();
215                                         byte [] b = new byte [65536];
216                                         int n = 0;
217
218                                         while (true) {
219                                                 n = responseStream.Read (b, 0, 65536);
220                                                 if (n == 0)
221                                                         break;
222                                                 ms.Write (b, 0, n);
223                                         }
224                                         ms.Seek (0, SeekOrigin.Begin);
225
226                                         channelResult.Response = Encoder.ReadMessage (
227                                                 //responseStream, MaxSizeOfHeaders);
228                                                 ms, MaxSizeOfHeaders, res.ContentType);
229 /*
230 MessageBuffer buf = ret.CreateBufferedCopy (0x10000);
231 ret = buf.CreateMessage ();
232 System.Xml.XmlTextWriter w = new System.Xml.XmlTextWriter (Console.Out);
233 w.Formatting = System.Xml.Formatting.Indented;
234 buf.CreateMessage ().WriteMessage (w);
235 w.Close ();
236 */
237                                         channelResult.Complete ();
238                                 }
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                         throw new NotImplementedException ();
287                 }
288
289                 protected override void OnEndClose (IAsyncResult result)
290                 {
291                         throw new NotImplementedException ();
292                 }
293
294                 // Open
295
296                 protected override void OnOpen (TimeSpan timeout)
297                 {
298                 }
299
300                 protected override IAsyncResult OnBeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
301                 {
302                         throw new NotImplementedException ();
303                 }
304
305                 protected override void OnEndOpen (IAsyncResult result)
306                 {
307                         throw new NotImplementedException ();
308                 }
309
310                 class HttpChannelRequestAsyncResult : IAsyncResult
311                 {
312                         public Message Message {
313                                 get; private set;
314                         }
315                         
316                         public TimeSpan Timeout {
317                                 get; private set;
318                         }
319
320                         AsyncCallback callback;
321                         ManualResetEvent wait;
322                         Exception error;
323
324                         public HttpChannelRequestAsyncResult (Message message, TimeSpan timeout, AsyncCallback callback, object state)
325                         {
326                                 CompletedSynchronously = true;
327                                 Message = message;
328                                 Timeout = timeout;
329                                 this.callback = callback;
330                                 AsyncState = state;
331
332                                 wait = new ManualResetEvent (false);
333                         }
334
335                         public Message Response {
336                                 get; set;
337                         }
338
339                         public WaitHandle AsyncWaitHandle {
340                                 get { return wait; }
341                         }
342
343                         public object AsyncState {
344                                 get; private set;
345                         }
346
347                         public void Complete ()
348                         {
349                                 Complete (null);
350                         }
351                         
352                         public void Complete (Exception ex)
353                         {
354                                 if (IsCompleted) {
355                                         return;
356                                 }
357                                 // If we've already stored an error, don't replace it
358                                 error = error ?? ex;
359
360                                 IsCompleted = true;
361                                 wait.Set ();
362                                 if (callback != null)
363                                         callback (this);
364                         }
365                         
366                         public bool CompletedSynchronously {
367                                 get; set;
368                         }
369
370                         public bool IsCompleted {
371                                 get; private set;
372                         }
373
374                         public void WaitEnd ()
375                         {
376                                 if (!IsCompleted) {
377                                         // FIXME: Do we need to use the timeout? If so, what happens when the timeout is reached.
378                                         // Is the current request cancelled and an exception thrown? If so we need to pass the
379                                         // exception to the Complete () method and allow the result to complete 'normally'.
380 #if NET_2_1 || MONOTOUCH
381                                         // neither Moonlight nor MonoTouch supports contexts (WaitOne default to false)
382                                         bool result = wait.WaitOne (Timeout);
383 #else
384                                         bool result = wait.WaitOne (Timeout, true);
385 #endif
386                                         if (!result)
387                                                 throw new TimeoutException ();
388                                 }
389                                 if (error != null)
390                                         throw error;
391                         }
392                 }
393         }
394 }