2009-02-18 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                                 Stream requestStream = web_request.EndGetRequestStream (web_request.BeginGetRequestStream (null, null));
132                                 requestStream.Write (buffer.GetBuffer (), 0, (int) buffer.Length);
133                                 requestStream.Close ();
134                         }
135
136                         WebResponse res;
137                         Stream resstr;
138                         try {
139                                 res = web_request.EndGetResponse (web_request.BeginGetResponse (null, null));
140                                 resstr = res.GetResponseStream ();
141                         } catch (WebException we) {
142                                 res = we.Response;
143 #if NET_2_1 // debug
144                                 Console.WriteLine (we);
145 #endif
146                                 try {
147                                         // The response might contain SOAP fault. It might not.
148                                         resstr = res.GetResponseStream ();
149                                 } catch (WebException we2) {
150 #if NET_2_1 // debug
151                                         Console.WriteLine (we2);
152 #endif
153                                         throw we;
154                                 }
155                         }
156                         
157                         try {
158                                 using (var responseStream = resstr) {
159                                         MemoryStream ms = new MemoryStream ();
160                                         byte [] b = new byte [65536];
161                                         int n = 0;
162
163                                         while (true) {
164                                                 n = responseStream.Read (b, 0, 65536);
165                                                 if (n == 0)
166                                                         break;
167                                                 ms.Write (b, 0, n);
168                                         }
169                                         ms.Seek (0, SeekOrigin.Begin);
170
171                                         Message ret = Encoder.ReadMessage (
172                                                 //responseStream, MaxSizeOfHeaders);
173                                                 ms, MaxSizeOfHeaders, res.ContentType);
174 /*
175 MessageBuffer buf = ret.CreateBufferedCopy (0x10000);
176 ret = buf.CreateMessage ();
177 System.Xml.XmlTextWriter w = new System.Xml.XmlTextWriter (Console.Out);
178 w.Formatting = System.Xml.Formatting.Indented;
179 buf.CreateMessage ().WriteMessage (w);
180 w.Close ();
181 */
182                                         return ret;
183                                 }
184                         } finally {
185                                 res.Close ();
186                         }
187                 }
188
189                 public override IAsyncResult BeginRequest (Message message, TimeSpan timeout, AsyncCallback callback, object state)
190                 {
191                         ThrowIfDisposedOrNotOpen ();
192
193                         return new HttpChannelRequestAsyncResult (this, message, timeout, callback, state);
194                 }
195
196                 public override Message EndRequest (IAsyncResult result)
197                 {
198                         if (result == null)
199                                 throw new ArgumentNullException ("result");
200                         HttpChannelRequestAsyncResult r = result as HttpChannelRequestAsyncResult;
201                         if (r == null)
202                                 throw new InvalidOperationException ("Wrong IAsyncResult");
203                         r.WaitEnd ();
204                         return r.Response;
205                 }
206
207                 // Abort
208
209                 protected override void OnAbort ()
210                 {
211                         throw new NotImplementedException ();
212                 }
213
214                 // Close
215
216                 protected override void OnClose (TimeSpan timeout)
217                 {
218                         if (web_request != null)
219                                 web_request.Abort ();
220                         web_request = null;
221                 }
222
223                 protected override IAsyncResult OnBeginClose (TimeSpan timeout, AsyncCallback callback, object state)
224                 {
225                         throw new NotImplementedException ();
226                 }
227
228                 protected override void OnEndClose (IAsyncResult result)
229                 {
230                         throw new NotImplementedException ();
231                 }
232
233                 // Open
234
235                 protected override void OnOpen (TimeSpan timeout)
236                 {
237                 }
238
239                 protected override IAsyncResult OnBeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
240                 {
241                         throw new NotImplementedException ();
242                 }
243
244                 protected override void OnEndOpen (IAsyncResult result)
245                 {
246                         throw new NotImplementedException ();
247                 }
248
249                 class HttpChannelRequestAsyncResult : IAsyncResult
250                 {
251                         HttpRequestChannel channel;
252                         Message message;
253                         TimeSpan timeout;
254                         AsyncCallback callback;
255                         object state;
256                         AutoResetEvent wait;
257                         bool done, waiting;
258                         Message response;
259                         Exception error;
260
261                         public HttpChannelRequestAsyncResult (HttpRequestChannel channel, Message message, TimeSpan timeout, AsyncCallback callback, object state)
262                         {
263                                 this.channel = channel;
264                                 this.message = message;
265                                 this.timeout = timeout;
266                                 this.callback = callback;
267                                 this.state = state;
268
269                                 wait = new AutoResetEvent (false);
270                                 Thread t = new Thread (delegate () {
271                                         try {
272                                                 response = channel.ProcessRequest (message, timeout);
273                                                 if (callback != null)
274                                                         callback (this);
275                                         } catch (Exception ex) {
276                                                 error = ex;
277                                         } finally {
278                                                 done = true;
279                                                 wait.Set ();
280                                         }
281                                 });
282                                 t.Start ();
283                         }
284
285                         public Message Response {
286                                 get { return response; }
287                         }
288
289                         public WaitHandle AsyncWaitHandle {
290                                 get { return wait; }
291                         }
292
293                         public object AsyncState {
294                                 get { return state; }
295                         }
296
297                         public bool CompletedSynchronously {
298                                 get { return done && !waiting; }
299                         }
300
301                         public bool IsCompleted {
302                                 get { return done; }
303                         }
304
305                         public void WaitEnd ()
306                         {
307                                 if (!done) {
308                                         waiting = true;
309                                         wait.WaitOne (timeout, true);
310                                 }
311                                 if (error != null)
312                                         throw error;
313                         }
314                 }
315         }
316 }