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