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;
46 // FIXME: supply maxSizeOfHeaders.
47 int max_headers = 0x10000;
51 public HttpRequestChannel (HttpChannelFactory<IRequestChannel> factory,
52 EndpointAddress address, Uri via)
53 : base (factory, address, via)
55 this.source = factory;
58 public int MaxSizeOfHeaders {
59 get { return max_headers; }
62 public MessageEncoder Encoder {
63 get { return source.MessageEncoder; }
68 public override Message Request (Message message, TimeSpan timeout)
70 return EndRequest (BeginRequest (message, timeout, null, null));
73 void BeginProcessRequest (HttpChannelRequestAsyncResult result)
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.");
83 destination = Via ?? RemoteAddress.Uri;
86 web_request = HttpWebRequest.Create (destination);
87 web_request.Method = "POST";
88 web_request.ContentType = Encoder.ContentType;
90 #if !NET_2_1 // until we support NetworkCredential like SL4 will do.
91 // client authentication (while SL3 has NetworkCredential class, it is not implemented yet. So, it is non-SL only.)
92 var httpbe = (HttpTransportBindingElement) source.Source;
93 string authType = null;
94 switch (httpbe.AuthenticationScheme) {
95 // AuthenticationSchemes.Anonymous is the default, ignored.
96 case AuthenticationSchemes.Basic:
99 case AuthenticationSchemes.Digest:
102 case AuthenticationSchemes.Ntlm:
105 case AuthenticationSchemes.Negotiate:
106 authType = "Negotiate";
109 if (authType != null) {
110 var cred = source.ClientCredentials;
111 string user = cred != null ? cred.UserName.UserName : null;
112 string pwd = cred != null ? cred.UserName.Password : null;
113 if (String.IsNullOrEmpty (user))
114 throw new InvalidOperationException (String.Format ("Use ClientCredentials to specify a user name for required HTTP {0} authentication.", authType));
115 // FIXME: fill name/pass from UserNamePassword.
116 var nc = new NetworkCredential (user, pwd);
117 web_request.Credentials = nc;
118 web_request.UseDefaultCredentials = false;
122 #if !NET_2_1 // FIXME: implement this to not depend on Timeout property
123 web_request.Timeout = (int) timeout.TotalMilliseconds;
126 // There is no SOAP Action/To header when AddressingVersion is None.
127 if (message.Version.Envelope.Equals (EnvelopeVersion.Soap11) ||
128 message.Version.Addressing.Equals (AddressingVersion.None)) {
129 if (message.Headers.Action != null) {
130 web_request.Headers ["SOAPAction"] = String.Concat ("\"", message.Headers.Action, "\"");
131 message.Headers.RemoveAll ("Action", message.Version.Addressing.Namespace);
135 // apply HttpRequestMessageProperty if exists.
136 bool suppressEntityBody = false;
138 string pname = HttpRequestMessageProperty.Name;
139 if (message.Properties.ContainsKey (pname)) {
140 HttpRequestMessageProperty hp = (HttpRequestMessageProperty) message.Properties [pname];
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 // The response might contain SOAP fault. It might not.
189 resstr = res.GetResponseStream ();
190 } catch (WebException we2) {
191 channelResult.Complete (we2);
197 using (var responseStream = resstr) {
198 MemoryStream ms = new MemoryStream ();
199 byte [] b = new byte [65536];
203 n = responseStream.Read (b, 0, 65536);
208 ms.Seek (0, SeekOrigin.Begin);
210 channelResult.Response = Encoder.ReadMessage (
211 //responseStream, MaxSizeOfHeaders);
212 ms, MaxSizeOfHeaders, res.ContentType);
214 MessageBuffer buf = ret.CreateBufferedCopy (0x10000);
215 ret = buf.CreateMessage ();
216 System.Xml.XmlTextWriter w = new System.Xml.XmlTextWriter (Console.Out);
217 w.Formatting = System.Xml.Formatting.Indented;
218 buf.CreateMessage ().WriteMessage (w);
221 channelResult.Complete ();
223 } catch (Exception ex) {
224 channelResult.Complete (ex);
230 public override IAsyncResult BeginRequest (Message message, TimeSpan timeout, AsyncCallback callback, object state)
232 ThrowIfDisposedOrNotOpen ();
234 HttpChannelRequestAsyncResult result = new HttpChannelRequestAsyncResult (message, timeout, callback, state);
235 BeginProcessRequest (result);
239 public override Message EndRequest (IAsyncResult result)
242 throw new ArgumentNullException ("result");
243 HttpChannelRequestAsyncResult r = result as HttpChannelRequestAsyncResult;
245 throw new InvalidOperationException ("Wrong IAsyncResult");
252 protected override void OnAbort ()
254 if (web_request != null)
255 web_request.Abort ();
261 protected override void OnClose (TimeSpan timeout)
263 if (web_request != null)
264 web_request.Abort ();
268 protected override IAsyncResult OnBeginClose (TimeSpan timeout, AsyncCallback callback, object state)
270 throw new NotImplementedException ();
273 protected override void OnEndClose (IAsyncResult result)
275 throw new NotImplementedException ();
280 protected override void OnOpen (TimeSpan timeout)
284 protected override IAsyncResult OnBeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
286 throw new NotImplementedException ();
289 protected override void OnEndOpen (IAsyncResult result)
291 throw new NotImplementedException ();
294 class HttpChannelRequestAsyncResult : IAsyncResult
296 public Message Message {
300 public TimeSpan Timeout {
304 AsyncCallback callback;
305 ManualResetEvent wait;
308 public HttpChannelRequestAsyncResult (Message message, TimeSpan timeout, AsyncCallback callback, object state)
310 CompletedSynchronously = true;
313 this.callback = callback;
316 wait = new ManualResetEvent (false);
319 public Message Response {
323 public WaitHandle AsyncWaitHandle {
327 public object AsyncState {
331 public void Complete ()
336 public void Complete (Exception ex)
341 // If we've already stored an error, don't replace it
346 if (callback != null)
350 public bool CompletedSynchronously {
354 public bool IsCompleted {
358 public void WaitEnd ()
361 // FIXME: Do we need to use the timeout? If so, what happens when the timeout is reached.
362 // Is the current request cancelled and an exception thrown? If so we need to pass the
363 // exception to the Complete () method and allow the result to complete 'normally'.
364 #if NET_2_1 || MONOTOUCH
365 // neither Moonlight nor MonoTouch supports contexts (WaitOne default to false)
366 bool result = wait.WaitOne (Timeout);
368 bool result = wait.WaitOne (Timeout, true);
371 throw new TimeoutException ();