2009-03-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                 EndpointAddress address;
44                 Uri via;
45
46                 WebRequest web_request;
47
48                 // FIXME: supply maxSizeOfHeaders.
49                 int max_headers = 0x10000;
50
51                 // Constructor
52
53                 public HttpRequestChannel (HttpChannelFactory<IRequestChannel> factory,
54                         EndpointAddress address, Uri via)
55                         : base (factory)
56                 {
57                         this.source = factory;
58                         this.address = address;
59                         this.via = via;
60                 }
61
62                 public int MaxSizeOfHeaders {
63                         get { return max_headers; }
64                 }
65
66                 public MessageEncoder Encoder {
67                         get { return source.MessageEncoder; }
68                 }
69
70                 public override EndpointAddress RemoteAddress {
71                         get { return address; }
72                 }
73
74                 public override Uri Via {
75                         get { return via; }
76                 }
77
78                 // Request
79
80                 public override Message Request (Message message, TimeSpan timeout)
81                 {
82                         return ProcessRequest (message, timeout);
83                 }
84
85                 Message ProcessRequest (Message message, TimeSpan timeout)
86                 {
87                         // FIXME: is distination really like this?
88                         Uri destination = message.Headers.To ?? Via ?? RemoteAddress.Uri;
89
90                         web_request = HttpWebRequest.Create (destination);
91                         web_request.Method = "POST";
92                         web_request.ContentType = Encoder.ContentType;
93
94 #if !NET_2_1 // FIXME: implement this to not depend on Timeout property
95                         web_request.Timeout = (int) timeout.TotalMilliseconds;
96 #endif
97
98                         // There is no SOAP Action/To header when AddressingVersion is None.
99                         if (message.Version.Addressing == AddressingVersion.None) {
100                                 if (message.Headers.Action != null) {
101                                         web_request.Headers ["SOAPAction"] = message.Headers.Action;
102                                         message.Headers.RemoveAll ("Action", message.Version.Addressing.Namespace);
103                                         if (message.Headers.Action != null) throw new Exception (message.Headers.Action);
104                                 }
105                         }
106
107                         // apply HttpRequestMessageProperty if exists.
108                         bool suppressEntityBody = false;
109 #if !NET_2_1
110                         string pname = HttpRequestMessageProperty.Name;
111                         if (message.Properties.ContainsKey (pname)) {
112                                 HttpRequestMessageProperty hp = (HttpRequestMessageProperty) message.Properties [pname];
113                                 web_request.Headers.Add (hp.Headers);
114                                 web_request.Method = hp.Method;
115                                 // FIXME: do we have to handle hp.QueryString ?
116                                 if (hp.SuppressEntityBody)
117                                         suppressEntityBody = true;
118                         }
119 #endif
120
121                         if (!suppressEntityBody && String.Compare (web_request.Method, "GET", StringComparison.OrdinalIgnoreCase) != 0) {
122                                 MemoryStream buffer = new MemoryStream ();
123                                 Encoder.WriteMessage (message, buffer);
124
125                                 if (buffer.Length > int.MaxValue)
126                                         throw new InvalidOperationException ("The argument message is too large.");
127
128 #if !NET_2_1
129                                 web_request.ContentLength = (int) buffer.Length;
130 #endif
131
132 #if NET_2_1
133                                 // We can verify cross domain access policy 
134                                 // with full set of headers and target URL.
135                                 if (!CrossDomainAccessManager.Current.IsAllowed (destination, web_request.Headers.AllKeys))
136                                         throw new InvalidOperationException (String.Format ("Cross domain web service access to {0} is not allowed", destination));
137 #endif
138
139                                 Stream requestStream = web_request.EndGetRequestStream (web_request.BeginGetRequestStream (null, null));
140                                 requestStream.Write (buffer.GetBuffer (), 0, (int) buffer.Length);
141                                 requestStream.Close ();
142                         }
143
144                         WebResponse res;
145                         Stream resstr;
146                         try {
147                                 res = web_request.EndGetResponse (web_request.BeginGetResponse (null, null));
148                                 resstr = res.GetResponseStream ();
149                         } catch (WebException we) {
150                                 res = we.Response;
151 #if NET_2_1 // debug
152                                 Console.WriteLine (we);
153 #endif
154                                 try {
155                                         // The response might contain SOAP fault. It might not.
156                                         resstr = res.GetResponseStream ();
157                                 } catch (WebException we2) {
158 #if NET_2_1 // debug
159                                         Console.WriteLine (we2);
160 #endif
161                                         throw we;
162                                 }
163                         }
164                         
165                         try {
166                                 using (var responseStream = resstr) {
167                                         MemoryStream ms = new MemoryStream ();
168                                         byte [] b = new byte [65536];
169                                         int n = 0;
170
171                                         while (true) {
172                                                 n = responseStream.Read (b, 0, 65536);
173                                                 if (n == 0)
174                                                         break;
175                                                 ms.Write (b, 0, n);
176                                         }
177                                         ms.Seek (0, SeekOrigin.Begin);
178
179                                         Message ret = Encoder.ReadMessage (
180                                                 //responseStream, MaxSizeOfHeaders);
181                                                 ms, MaxSizeOfHeaders, res.ContentType);
182 /*
183 MessageBuffer buf = ret.CreateBufferedCopy (0x10000);
184 ret = buf.CreateMessage ();
185 System.Xml.XmlTextWriter w = new System.Xml.XmlTextWriter (Console.Out);
186 w.Formatting = System.Xml.Formatting.Indented;
187 buf.CreateMessage ().WriteMessage (w);
188 w.Close ();
189 */
190                                         return ret;
191                                 }
192                         } finally {
193                                 res.Close ();
194                         }
195                 }
196
197                 public override IAsyncResult BeginRequest (Message message, TimeSpan timeout, AsyncCallback callback, object state)
198                 {
199                         ThrowIfDisposedOrNotOpen ();
200
201                         return new HttpChannelRequestAsyncResult (this, message, timeout, callback, state);
202                 }
203
204                 public override Message EndRequest (IAsyncResult result)
205                 {
206                         if (result == null)
207                                 throw new ArgumentNullException ("result");
208                         HttpChannelRequestAsyncResult r = result as HttpChannelRequestAsyncResult;
209                         if (r == null)
210                                 throw new InvalidOperationException ("Wrong IAsyncResult");
211                         r.WaitEnd ();
212                         return r.Response;
213                 }
214
215                 // Abort
216
217                 protected override void OnAbort ()
218                 {
219                         throw new NotImplementedException ();
220                 }
221
222                 // Close
223
224                 protected override void OnClose (TimeSpan timeout)
225                 {
226                         if (web_request != null)
227                                 web_request.Abort ();
228                         web_request = null;
229                 }
230
231                 protected override IAsyncResult OnBeginClose (TimeSpan timeout, AsyncCallback callback, object state)
232                 {
233                         throw new NotImplementedException ();
234                 }
235
236                 protected override void OnEndClose (IAsyncResult result)
237                 {
238                         throw new NotImplementedException ();
239                 }
240
241                 // Open
242
243                 protected override void OnOpen (TimeSpan timeout)
244                 {
245                 }
246
247                 protected override IAsyncResult OnBeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
248                 {
249                         throw new NotImplementedException ();
250                 }
251
252                 protected override void OnEndOpen (IAsyncResult result)
253                 {
254                         throw new NotImplementedException ();
255                 }
256
257                 class HttpChannelRequestAsyncResult : IAsyncResult
258                 {
259                         HttpRequestChannel channel;
260                         Message message;
261                         TimeSpan timeout;
262                         AsyncCallback callback;
263                         object state;
264                         AutoResetEvent wait;
265                         bool done, waiting;
266                         Message response;
267                         Exception error;
268
269                         public HttpChannelRequestAsyncResult (HttpRequestChannel channel, Message message, TimeSpan timeout, AsyncCallback callback, object state)
270                         {
271                                 this.channel = channel;
272                                 this.message = message;
273                                 this.timeout = timeout;
274                                 this.callback = callback;
275                                 this.state = state;
276
277                                 wait = new AutoResetEvent (false);
278                                 Thread t = new Thread (delegate () {
279                                         try {
280                                                 response = channel.ProcessRequest (message, timeout);
281                                                 if (callback != null)
282                                                         callback (this);
283                                         } catch (Exception ex) {
284                                                 error = ex;
285                                         } finally {
286                                                 done = true;
287                                                 wait.Set ();
288                                         }
289                                 });
290                                 t.Start ();
291                         }
292
293                         public Message Response {
294                                 get { return response; }
295                         }
296
297                         public WaitHandle AsyncWaitHandle {
298                                 get { return wait; }
299                         }
300
301                         public object AsyncState {
302                                 get { return state; }
303                         }
304
305                         public bool CompletedSynchronously {
306                                 get { return done && !waiting; }
307                         }
308
309                         public bool IsCompleted {
310                                 get { return done; }
311                         }
312
313                         public void WaitEnd ()
314                         {
315                                 if (!done) {
316                                         waiting = true;
317                                         wait.WaitOne (timeout, true);
318                                 }
319                                 if (error != null)
320                                         throw error;
321                         }
322                 }
323         }
324 }