2 // HttpRequestChannel.cs
5 // Atsushi Enomoto <atsushi@ximian.com>
7 // Copyright (C) 2006 Novell, Inc. http://www.novell.com
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:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
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.
29 using System.Collections.Generic;
32 using System.Net.Security;
33 using System.ServiceModel;
34 using System.ServiceModel.Description;
35 using System.ServiceModel.Security;
36 using System.Threading;
38 namespace System.ServiceModel.Channels
40 internal class HttpRequestChannel : RequestChannelBase
42 HttpChannelFactory<IRequestChannel> source;
44 WebRequest web_request;
48 public HttpRequestChannel (HttpChannelFactory<IRequestChannel> factory,
49 EndpointAddress address, Uri via)
50 : base (factory, address, via)
52 this.source = factory;
55 public MessageEncoder Encoder {
56 get { return source.MessageEncoder; }
61 public override Message Request (Message message, TimeSpan timeout)
63 return EndRequest (BeginRequest (message, timeout, null, null));
66 void BeginProcessRequest (HttpChannelRequestAsyncResult result)
68 Message message = result.Message;
69 TimeSpan timeout = result.Timeout;
70 // FIXME: is distination really like this?
71 Uri destination = message.Headers.To;
72 if (destination == null) {
73 if (source.Transport.ManualAddressing)
74 throw new InvalidOperationException ("When manual addressing is enabled on the transport, every request messages must be set its destination address.");
76 destination = Via ?? RemoteAddress.Uri;
79 web_request = HttpWebRequest.Create (destination);
80 web_request.Method = "POST";
81 web_request.ContentType = Encoder.ContentType;
84 var cmgr = source.GetProperty<IHttpCookieContainerManager> ();
86 ((HttpWebRequest) web_request).CookieContainer = cmgr.CookieContainer;
89 #if !MOONLIGHT // until we support NetworkCredential like SL4 will do.
90 // client authentication (while SL3 has NetworkCredential class, it is not implemented yet. So, it is non-SL only.)
91 var httpbe = (HttpTransportBindingElement) source.Transport;
92 string authType = null;
93 switch (httpbe.AuthenticationScheme) {
94 // AuthenticationSchemes.Anonymous is the default, ignored.
95 case AuthenticationSchemes.Basic:
98 case AuthenticationSchemes.Digest:
101 case AuthenticationSchemes.Ntlm:
104 case AuthenticationSchemes.Negotiate:
105 authType = "Negotiate";
108 if (authType != null) {
109 var cred = source.ClientCredentials;
110 string user = cred != null ? cred.UserName.UserName : null;
111 string pwd = cred != null ? cred.UserName.Password : null;
112 if (String.IsNullOrEmpty (user))
113 throw new InvalidOperationException (String.Format ("Use ClientCredentials to specify a user name for required HTTP {0} authentication.", authType));
114 var nc = new NetworkCredential (user, pwd);
115 web_request.Credentials = nc;
116 // FIXME: it is said required in SL4, but it blocks full WCF.
117 //web_request.UseDefaultCredentials = false;
121 #if !NET_2_1 // FIXME: implement this to not depend on Timeout property
122 web_request.Timeout = (int) timeout.TotalMilliseconds;
125 // There is no SOAP Action/To header when AddressingVersion is None.
126 if (message.Version.Envelope.Equals (EnvelopeVersion.Soap11) ||
127 message.Version.Addressing.Equals (AddressingVersion.None)) {
128 if (message.Headers.Action != null) {
129 web_request.Headers ["SOAPAction"] = String.Concat ("\"", message.Headers.Action, "\"");
130 message.Headers.RemoveAll ("Action", message.Version.Addressing.Namespace);
134 // apply HttpRequestMessageProperty if exists.
135 bool suppressEntityBody = false;
137 string pname = HttpRequestMessageProperty.Name;
138 if (message.Properties.ContainsKey (pname)) {
139 HttpRequestMessageProperty hp = (HttpRequestMessageProperty) message.Properties [pname];
140 web_request.Headers.Clear ();
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;
149 if (!suppressEntityBody && String.Compare (web_request.Method, "GET", StringComparison.OrdinalIgnoreCase) != 0) {
150 MemoryStream buffer = new MemoryStream ();
151 Encoder.WriteMessage (message, buffer);
153 if (buffer.Length > int.MaxValue)
154 throw new InvalidOperationException ("The argument message is too large.");
157 web_request.ContentLength = (int) buffer.Length;
160 web_request.BeginGetRequestStream (delegate (IAsyncResult r) {
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);
171 web_request.BeginGetResponse (GotResponse, result);
175 void GotResponse (IAsyncResult result)
177 HttpChannelRequestAsyncResult channelResult = (HttpChannelRequestAsyncResult) result.AsyncState;
178 channelResult.CompletedSynchronously &= result.CompletedSynchronously;
183 res = web_request.EndGetResponse (result);
184 resstr = res.GetResponseStream ();
185 } catch (WebException we) {
188 channelResult.Complete (we);
192 // The response might contain SOAP fault. It might not.
193 resstr = res.GetResponseStream ();
194 } catch (WebException we2) {
195 channelResult.Complete (we2);
200 var hrr = (HttpWebResponse) res;
201 if ((int) hrr.StatusCode >= 400 && (int) hrr.StatusCode < 500) {
202 channelResult.Complete (new WebException (String.Format ("There was an error on processing web request: Status code {0}({1}): {2}", (int) hrr.StatusCode, hrr.StatusCode, hrr.StatusDescription)));
206 using (var responseStream = resstr) {
207 MemoryStream ms = new MemoryStream ();
208 byte [] b = new byte [65536];
212 n = responseStream.Read (b, 0, 65536);
217 ms.Seek (0, SeekOrigin.Begin);
219 Message ret = Encoder.ReadMessage (
220 ms, (int) source.Transport.MaxReceivedMessageSize, res.ContentType);
221 var rp = new HttpResponseMessageProperty () { StatusCode = hrr.StatusCode, StatusDescription = hrr.StatusDescription };
222 foreach (var key in hrr.Headers.AllKeys)
223 rp.Headers [key] = hrr.Headers [key];
224 ret.Properties.Add (HttpResponseMessageProperty.Name, rp);
226 MessageBuffer buf = ret.CreateBufferedCopy (0x10000);
227 ret = buf.CreateMessage ();
228 System.Xml.XmlTextWriter w = new System.Xml.XmlTextWriter (Console.Out);
229 w.Formatting = System.Xml.Formatting.Indented;
230 buf.CreateMessage ().WriteMessage (w);
233 channelResult.Response = ret;
234 channelResult.Complete ();
236 } catch (Exception ex) {
237 channelResult.Complete (ex);
243 public override IAsyncResult BeginRequest (Message message, TimeSpan timeout, AsyncCallback callback, object state)
245 ThrowIfDisposedOrNotOpen ();
247 HttpChannelRequestAsyncResult result = new HttpChannelRequestAsyncResult (message, timeout, callback, state);
248 BeginProcessRequest (result);
252 public override Message EndRequest (IAsyncResult result)
255 throw new ArgumentNullException ("result");
256 HttpChannelRequestAsyncResult r = result as HttpChannelRequestAsyncResult;
258 throw new InvalidOperationException ("Wrong IAsyncResult");
265 protected override void OnAbort ()
267 if (web_request != null)
268 web_request.Abort ();
274 protected override void OnClose (TimeSpan timeout)
276 if (web_request != null)
277 web_request.Abort ();
281 protected override IAsyncResult OnBeginClose (TimeSpan timeout, AsyncCallback callback, object state)
283 throw new NotImplementedException ();
286 protected override void OnEndClose (IAsyncResult result)
288 throw new NotImplementedException ();
293 protected override void OnOpen (TimeSpan timeout)
297 protected override IAsyncResult OnBeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
299 throw new NotImplementedException ();
302 protected override void OnEndOpen (IAsyncResult result)
304 throw new NotImplementedException ();
307 class HttpChannelRequestAsyncResult : IAsyncResult
309 public Message Message {
313 public TimeSpan Timeout {
317 AsyncCallback callback;
318 ManualResetEvent wait;
321 public HttpChannelRequestAsyncResult (Message message, TimeSpan timeout, AsyncCallback callback, object state)
323 CompletedSynchronously = true;
326 this.callback = callback;
329 wait = new ManualResetEvent (false);
332 public Message Response {
336 public WaitHandle AsyncWaitHandle {
340 public object AsyncState {
344 public void Complete ()
349 public void Complete (Exception ex)
354 // If we've already stored an error, don't replace it
359 if (callback != null)
363 public bool CompletedSynchronously {
367 public bool IsCompleted {
371 public void WaitEnd ()
374 // FIXME: Do we need to use the timeout? If so, what happens when the timeout is reached.
375 // Is the current request cancelled and an exception thrown? If so we need to pass the
376 // exception to the Complete () method and allow the result to complete 'normally'.
378 // neither Moonlight nor MonoTouch supports contexts (WaitOne default to false)
379 bool result = wait.WaitOne (Timeout);
381 bool result = wait.WaitOne (Timeout, true);
384 throw new TimeoutException ();