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