2009-09-30 Jb Evain <jbevain@novell.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 // FIXME: implement this to not depend on Timeout property
91                         web_request.Timeout = (int) timeout.TotalMilliseconds;
92 #endif
93
94                         // There is no SOAP Action/To header when AddressingVersion is None.
95                         if (message.Version.Envelope.Equals (EnvelopeVersion.Soap11) ||
96                             message.Version.Addressing.Equals (AddressingVersion.None)) {
97                                 if (message.Headers.Action != null) {
98                                         web_request.Headers ["SOAPAction"] = String.Concat ("\"", message.Headers.Action, "\"");
99                                         message.Headers.RemoveAll ("Action", message.Version.Addressing.Namespace);
100                                 }
101                         }
102
103                         // apply HttpRequestMessageProperty if exists.
104                         bool suppressEntityBody = false;
105 #if !NET_2_1
106                         string pname = HttpRequestMessageProperty.Name;
107                         if (message.Properties.ContainsKey (pname)) {
108                                 HttpRequestMessageProperty hp = (HttpRequestMessageProperty) message.Properties [pname];
109                                 web_request.Headers.Add (hp.Headers);
110                                 web_request.Method = hp.Method;
111                                 // FIXME: do we have to handle hp.QueryString ?
112                                 if (hp.SuppressEntityBody)
113                                         suppressEntityBody = true;
114                         }
115 #endif
116
117                         if (!suppressEntityBody && String.Compare (web_request.Method, "GET", StringComparison.OrdinalIgnoreCase) != 0) {
118                                 MemoryStream buffer = new MemoryStream ();
119                                 Encoder.WriteMessage (message, buffer);
120
121                                 if (buffer.Length > int.MaxValue)
122                                         throw new InvalidOperationException ("The argument message is too large.");
123
124 #if !NET_2_1
125                                 web_request.ContentLength = (int) buffer.Length;
126 #endif
127
128                                 web_request.BeginGetRequestStream (delegate (IAsyncResult r) {
129                                         try {
130                                                 result.CompletedSynchronously &= r.CompletedSynchronously;
131                                                 using (Stream s = web_request.EndGetRequestStream (r))
132                                                         s.Write (buffer.GetBuffer (), 0, (int) buffer.Length);
133                                                 web_request.BeginGetResponse (GotResponse, result);
134                                         } catch (Exception ex) {
135                                                 result.Complete (ex);
136                                         }
137                                 }, null);
138                         } else {
139                                 web_request.BeginGetResponse (GotResponse, result);
140                         }
141                 }
142                 
143                 void GotResponse (IAsyncResult result)
144                 {
145                         HttpChannelRequestAsyncResult channelResult = (HttpChannelRequestAsyncResult) result.AsyncState;
146                         channelResult.CompletedSynchronously &= result.CompletedSynchronously;
147                         
148                         WebResponse res;
149                         Stream resstr;
150                         try {
151                                 res = web_request.EndGetResponse (result);
152                                 resstr = res.GetResponseStream ();
153                         } catch (WebException we) {
154                                 res = we.Response;
155 #if NET_2_1 // debug
156                                 Console.WriteLine (we);
157 #endif
158                                 try {
159                                         // The response might contain SOAP fault. It might not.
160                                         resstr = res.GetResponseStream ();
161                                 } catch (WebException we2) {
162 #if NET_2_1 // debug
163                                         Console.WriteLine (we2);
164 #endif
165
166                                         channelResult.Complete (we2);
167                                         return;
168                                 }
169                         }
170                         
171                         try {
172                                 using (var responseStream = resstr) {
173                                         MemoryStream ms = new MemoryStream ();
174                                         byte [] b = new byte [65536];
175                                         int n = 0;
176
177                                         while (true) {
178                                                 n = responseStream.Read (b, 0, 65536);
179                                                 if (n == 0)
180                                                         break;
181                                                 ms.Write (b, 0, n);
182                                         }
183                                         ms.Seek (0, SeekOrigin.Begin);
184
185                                         channelResult.Response = Encoder.ReadMessage (
186                                                 //responseStream, MaxSizeOfHeaders);
187                                                 ms, MaxSizeOfHeaders, res.ContentType);
188 /*
189 MessageBuffer buf = ret.CreateBufferedCopy (0x10000);
190 ret = buf.CreateMessage ();
191 System.Xml.XmlTextWriter w = new System.Xml.XmlTextWriter (Console.Out);
192 w.Formatting = System.Xml.Formatting.Indented;
193 buf.CreateMessage ().WriteMessage (w);
194 w.Close ();
195 */
196                                         channelResult.Complete ();
197                                 }
198                         } catch (Exception ex) {
199                                 channelResult.Complete (ex);
200                         } finally {
201                                 res.Close ();   
202                         }
203                 }
204
205                 public override IAsyncResult BeginRequest (Message message, TimeSpan timeout, AsyncCallback callback, object state)
206                 {
207                         ThrowIfDisposedOrNotOpen ();
208
209                         HttpChannelRequestAsyncResult result = new HttpChannelRequestAsyncResult (message, timeout, callback, state);
210                         BeginProcessRequest (result);
211                         return result;
212                 }
213
214                 public override Message EndRequest (IAsyncResult result)
215                 {
216                         if (result == null)
217                                 throw new ArgumentNullException ("result");
218                         HttpChannelRequestAsyncResult r = result as HttpChannelRequestAsyncResult;
219                         if (r == null)
220                                 throw new InvalidOperationException ("Wrong IAsyncResult");
221                         r.WaitEnd ();
222                         return r.Response;
223                 }
224
225                 // Abort
226
227                 protected override void OnAbort ()
228                 {
229                         if (web_request != null)
230                                 web_request.Abort ();
231                         web_request = null;
232                 }
233
234                 // Close
235
236                 protected override void OnClose (TimeSpan timeout)
237                 {
238                         if (web_request != null)
239                                 web_request.Abort ();
240                         web_request = null;
241                 }
242
243                 protected override IAsyncResult OnBeginClose (TimeSpan timeout, AsyncCallback callback, object state)
244                 {
245                         throw new NotImplementedException ();
246                 }
247
248                 protected override void OnEndClose (IAsyncResult result)
249                 {
250                         throw new NotImplementedException ();
251                 }
252
253                 // Open
254
255                 protected override void OnOpen (TimeSpan timeout)
256                 {
257                 }
258
259                 protected override IAsyncResult OnBeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
260                 {
261                         throw new NotImplementedException ();
262                 }
263
264                 protected override void OnEndOpen (IAsyncResult result)
265                 {
266                         throw new NotImplementedException ();
267                 }
268
269                 class HttpChannelRequestAsyncResult : IAsyncResult
270                 {
271                         public Message Message {
272                                 get; private set;
273                         }
274                         
275                         public TimeSpan Timeout {
276                                 get; private set;
277                         }
278
279                         AsyncCallback callback;
280                         ManualResetEvent wait;
281                         Exception error;
282
283                         public HttpChannelRequestAsyncResult (Message message, TimeSpan timeout, AsyncCallback callback, object state)
284                         {
285                                 CompletedSynchronously = true;
286                                 Message = message;
287                                 Timeout = timeout;
288                                 this.callback = callback;
289                                 AsyncState = state;
290
291                                 wait = new ManualResetEvent (false);
292                         }
293
294                         public Message Response {
295                                 get; set;
296                         }
297
298                         public WaitHandle AsyncWaitHandle {
299                                 get { return wait; }
300                         }
301
302                         public object AsyncState {
303                                 get; private set;
304                         }
305
306                         public void Complete ()
307                         {
308                                 Complete (null);
309                         }
310                         
311                         public void Complete (Exception ex)
312                         {
313                                 if (IsCompleted) {
314                                         return;
315                                 }
316                                 // If we've already stored an error, don't replace it
317                                 error = error ?? ex;
318
319                                 IsCompleted = true;
320                                 wait.Set ();
321                                 if (callback != null)
322                                         callback (this);
323                         }
324                         
325                         public bool CompletedSynchronously {
326                                 get; set;
327                         }
328
329                         public bool IsCompleted {
330                                 get; private set;
331                         }
332
333                         public void WaitEnd ()
334                         {
335                                 if (!IsCompleted) {
336
337                                         const bool exit_context =
338 #if MONOTOUCH
339                                                 false; // MonoTouch doesn't support any remoting feature
340 #else
341                                                 true;
342 #endif
343
344                                         // FIXME: Do we need to use the timeout? If so, what happens when the timeout is reached.
345                                         // Is the current request cancelled and an exception thrown? If so we need to pass the
346                                         // exception to the Complete () method and allow the result to complete 'normally'.
347                                         if (!wait.WaitOne (Timeout, exit_context))
348                                                 throw new TimeoutException ();
349                                 }
350                                 if (error != null)
351                                         throw error;
352                         }
353                 }
354         }
355 }