2 // System.Net.HttpWebRequest
5 // Lawrence Pit (loz@cable.a2000.nl)
6 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
8 // (c) 2002 Lawrence Pit
9 // (c) 2003 Ximian, Inc. (http://www.ximian.com)
10 // (c) 2004 Novell, Inc. (http://www.novell.com)
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35 #if MONO_SECURITY_ALIAS
36 extern alias MonoSecurity;
37 using MonoSecurity::Mono.Security.Interface;
39 using Mono.Security.Interface;
44 using System.Collections;
45 using System.Configuration;
46 using System.Globalization;
49 using System.Net.Cache;
50 using System.Net.Sockets;
51 using System.Net.Security;
52 using System.Runtime.Remoting.Messaging;
53 using System.Runtime.Serialization;
54 using System.Security.Cryptography.X509Certificates;
56 using System.Threading;
57 using Mono.Net.Security;
62 public class HttpWebRequest : WebRequest, ISerializable {
66 bool allowAutoRedirect = true;
67 bool allowBuffering = true;
68 X509CertificateCollection certificates;
69 string connectionGroup;
70 bool haveContentLength;
71 long contentLength = -1;
72 HttpContinueDelegate continueDelegate;
73 CookieContainer cookieContainer;
74 ICredentials credentials;
78 WebHeaderCollection webHeaders;
79 bool keepAlive = true;
80 int maxAutoRedirect = 50;
81 string mediaType = String.Empty;
82 string method = "GET";
83 string initialMethod = "GET";
84 bool pipelined = true;
87 Version version = HttpVersion.Version11;
89 Version actualVersion;
92 ServicePoint servicePoint;
95 WebConnectionStream writeStream;
96 HttpWebResponse webResponse;
97 WebAsyncResult asyncWrite;
98 WebAsyncResult asyncRead;
99 EventHandler abortHandler;
101 bool gotRequestStream;
105 int bodyBufferLength;
106 bool getResponseCalled;
108 object locker = new object ();
109 bool finished_reading;
110 internal WebConnection WebConnection;
111 DecompressionMethods auto_decomp;
112 int maxResponseHeadersLength;
113 static int defaultMaxResponseHeadersLength;
114 int readWriteTimeout = 300000; // ms
115 IMonoTlsProvider tlsProvider;
117 MonoTlsSettings tlsSettings;
119 ServerCertValidationCallback certValidationCallback;
126 AuthorizationState auth_state, proxy_auth_state;
130 internal Action<Stream> ResendContentFactory;
133 static HttpWebRequest ()
135 defaultMaxResponseHeadersLength = 64 * 1024;
137 NetConfig config = ConfigurationSettings.GetConfig ("system.net/settings") as NetConfig;
138 if (config != null) {
139 int x = config.MaxResponseHeadersLength;
143 defaultMaxResponseHeadersLength = x;
153 HttpWebRequest (Uri uri)
155 this.requestUri = uri;
156 this.actualUri = uri;
157 this.proxy = GlobalProxySelection.Select;
158 this.webHeaders = new WebHeaderCollection (WebHeaderCollection.HeaderInfo.Request);
160 ResetAuthorization ();
164 internal HttpWebRequest (Uri uri, IMonoTlsProvider tlsProvider, MonoTlsSettings settings = null)
167 this.tlsProvider = tlsProvider;
168 this.tlsSettings = settings;
172 [Obsolete ("Serialization is obsoleted for this type", false)]
173 protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
175 SerializationInfo info = serializationInfo;
177 requestUri = (Uri) info.GetValue ("requestUri", typeof (Uri));
178 actualUri = (Uri) info.GetValue ("actualUri", typeof (Uri));
179 allowAutoRedirect = info.GetBoolean ("allowAutoRedirect");
180 allowBuffering = info.GetBoolean ("allowBuffering");
181 certificates = (X509CertificateCollection) info.GetValue ("certificates", typeof (X509CertificateCollection));
182 connectionGroup = info.GetString ("connectionGroup");
183 contentLength = info.GetInt64 ("contentLength");
184 webHeaders = (WebHeaderCollection) info.GetValue ("webHeaders", typeof (WebHeaderCollection));
185 keepAlive = info.GetBoolean ("keepAlive");
186 maxAutoRedirect = info.GetInt32 ("maxAutoRedirect");
187 mediaType = info.GetString ("mediaType");
188 method = info.GetString ("method");
189 initialMethod = info.GetString ("initialMethod");
190 pipelined = info.GetBoolean ("pipelined");
191 version = (Version) info.GetValue ("version", typeof (Version));
192 proxy = (IWebProxy) info.GetValue ("proxy", typeof (IWebProxy));
193 sendChunked = info.GetBoolean ("sendChunked");
194 timeout = info.GetInt32 ("timeout");
195 redirects = info.GetInt32 ("redirects");
196 host = info.GetString ("host");
197 ResetAuthorization ();
200 void ResetAuthorization ()
202 auth_state = new AuthorizationState (this, false);
203 proxy_auth_state = new AuthorizationState (this, true);
208 public string Accept {
209 get { return webHeaders ["Accept"]; }
211 CheckRequestStarted ();
212 webHeaders.RemoveAndAdd ("Accept", value);
217 get { return actualUri; }
218 internal set { actualUri = value; } // Used by Ftp+proxy
221 public bool AllowAutoRedirect {
222 get { return allowAutoRedirect; }
223 set { this.allowAutoRedirect = value; }
226 public bool AllowWriteStreamBuffering {
227 get { return allowBuffering; }
228 set { allowBuffering = value; }
231 public virtual bool AllowReadStreamBuffering {
232 get { return false; }
235 throw new InvalidOperationException ();
239 static Exception GetMustImplement ()
241 return new NotImplementedException ();
244 public DecompressionMethods AutomaticDecompression
250 CheckRequestStarted ();
255 internal bool InternalAllowBuffering {
257 return allowBuffering && MethodWithBuffer;
261 bool MethodWithBuffer {
263 return method != "HEAD" && method != "GET" &&
264 method != "MKCOL" && method != "CONNECT" &&
269 internal IMonoTlsProvider TlsProvider {
270 get { return tlsProvider; }
274 internal MonoTlsSettings TlsSettings {
275 get { return tlsSettings; }
279 public X509CertificateCollection ClientCertificates {
281 if (certificates == null)
282 certificates = new X509CertificateCollection ();
287 throw new ArgumentNullException ("value");
288 certificates = value;
292 public string Connection {
293 get { return webHeaders ["Connection"]; }
295 CheckRequestStarted ();
297 if (string.IsNullOrEmpty (value)) {
298 webHeaders.RemoveInternal ("Connection");
302 string val = value.ToLowerInvariant ();
303 if (val.Contains ("keep-alive") || val.Contains ("close"))
304 throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
307 value = value + ", Keep-Alive";
309 webHeaders.RemoveAndAdd ("Connection", value);
313 public override string ConnectionGroupName {
314 get { return connectionGroup; }
315 set { connectionGroup = value; }
318 public override long ContentLength {
319 get { return contentLength; }
321 CheckRequestStarted ();
323 throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
325 contentLength = value;
326 haveContentLength = true;
330 internal long InternalContentLength {
331 set { contentLength = value; }
334 internal bool ThrowOnError { get; set; }
336 public override string ContentType {
337 get { return webHeaders ["Content-Type"]; }
339 if (value == null || value.Trim().Length == 0) {
340 webHeaders.RemoveInternal ("Content-Type");
343 webHeaders.RemoveAndAdd ("Content-Type", value);
347 public HttpContinueDelegate ContinueDelegate {
348 get { return continueDelegate; }
349 set { continueDelegate = value; }
353 public CookieContainer CookieContainer {
354 get { return cookieContainer; }
355 set { cookieContainer = value; }
358 public override ICredentials Credentials {
359 get { return credentials; }
360 set { credentials = value; }
362 public DateTime Date {
364 string date = webHeaders ["Date"];
366 return DateTime.MinValue;
367 return DateTime.ParseExact (date, "r", CultureInfo.InvariantCulture).ToLocalTime ();
370 if (value.Equals (DateTime.MinValue))
371 webHeaders.RemoveInternal ("Date");
373 webHeaders.RemoveAndAdd ("Date", value.ToUniversalTime ().ToString ("r", CultureInfo.InvariantCulture));
379 public static new RequestCachePolicy DefaultCachePolicy
382 throw GetMustImplement ();
385 throw GetMustImplement ();
391 public static int DefaultMaximumErrorResponseLength
394 throw GetMustImplement ();
397 throw GetMustImplement ();
401 public string Expect {
402 get { return webHeaders ["Expect"]; }
404 CheckRequestStarted ();
407 val = val.Trim ().ToLower ();
409 if (val == null || val.Length == 0) {
410 webHeaders.RemoveInternal ("Expect");
414 if (val == "100-continue")
415 throw new ArgumentException ("100-Continue cannot be set with this property.",
417 webHeaders.RemoveAndAdd ("Expect", value);
422 public bool HaveResponse {
423 get { return haveResponse; }
426 public override WebHeaderCollection Headers {
427 get { return webHeaders; }
429 CheckRequestStarted ();
430 WebHeaderCollection newHeaders = new WebHeaderCollection (WebHeaderCollection.HeaderInfo.Request);
431 int count = value.Count;
432 for (int i = 0; i < count; i++)
433 newHeaders.Add (value.GetKey (i), value.Get (i));
435 webHeaders = newHeaders;
443 return actualUri.Authority;
448 throw new ArgumentNullException ("value");
450 if (!CheckValidHost (actualUri.Scheme, value))
451 throw new ArgumentException ("Invalid host: " + value);
457 static bool CheckValidHost (string scheme, string val)
465 int idx = val.IndexOf ('/');
470 if (IPAddress.TryParse (val, out ipaddr))
473 string u = scheme + "://" + val + "/";
474 return Uri.IsWellFormedUriString (u, UriKind.Absolute);
477 public DateTime IfModifiedSince {
479 string str = webHeaders ["If-Modified-Since"];
483 return MonoHttpDate.Parse (str);
484 } catch (Exception) {
489 CheckRequestStarted ();
491 webHeaders.SetInternal ("If-Modified-Since",
492 value.ToUniversalTime ().ToString ("r", null));
493 // TODO: check last param when using different locale
497 public bool KeepAlive {
506 public int MaximumAutomaticRedirections {
507 get { return maxAutoRedirect; }
510 throw new ArgumentException ("Must be > 0", "value");
512 maxAutoRedirect = value;
516 [MonoTODO ("Use this")]
517 public int MaximumResponseHeadersLength {
518 get { return maxResponseHeadersLength; }
519 set { maxResponseHeadersLength = value; }
522 [MonoTODO ("Use this")]
523 public static int DefaultMaximumResponseHeadersLength {
524 get { return defaultMaxResponseHeadersLength; }
525 set { defaultMaxResponseHeadersLength = value; }
528 public int ReadWriteTimeout {
529 get { return readWriteTimeout; }
532 throw new InvalidOperationException ("The request has already been sent.");
535 throw new ArgumentOutOfRangeException ("value", "Must be >= -1");
537 readWriteTimeout = value;
542 public int ContinueTimeout {
543 get { throw new NotImplementedException (); }
544 set { throw new NotImplementedException (); }
547 public string MediaType {
548 get { return mediaType; }
554 public override string Method {
555 get { return this.method; }
557 if (value == null || value.Trim () == "")
558 throw new ArgumentException ("not a valid method");
560 method = value.ToUpperInvariant ();
561 if (method != "HEAD" && method != "GET" && method != "POST" && method != "PUT" &&
562 method != "DELETE" && method != "CONNECT" && method != "TRACE" &&
569 public bool Pipelined {
570 get { return pipelined; }
571 set { pipelined = value; }
574 public override bool PreAuthenticate {
575 get { return preAuthenticate; }
576 set { preAuthenticate = value; }
579 public Version ProtocolVersion {
580 get { return version; }
582 if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
583 throw new ArgumentException ("value");
585 force_version = true;
590 public override IWebProxy Proxy {
591 get { return proxy; }
593 CheckRequestStarted ();
595 servicePoint = null; // we may need a new one
600 public string Referer {
601 get { return webHeaders ["Referer"]; }
603 CheckRequestStarted ();
604 if (value == null || value.Trim().Length == 0) {
605 webHeaders.RemoveInternal ("Referer");
608 webHeaders.SetInternal ("Referer", value);
612 public override Uri RequestUri {
613 get { return requestUri; }
616 public bool SendChunked {
617 get { return sendChunked; }
619 CheckRequestStarted ();
624 public ServicePoint ServicePoint {
625 get { return GetServicePoint (); }
628 internal ServicePoint ServicePointNoLock {
629 get { return servicePoint; }
631 public virtual bool SupportsCookieContainer {
633 // The managed implementation supports the cookie container
634 // it is only Silverlight that returns false here
638 public override int Timeout {
639 get { return timeout; }
642 throw new ArgumentOutOfRangeException ("value");
648 public string TransferEncoding {
649 get { return webHeaders ["Transfer-Encoding"]; }
651 CheckRequestStarted ();
654 val = val.Trim ().ToLower ();
656 if (val == null || val.Length == 0) {
657 webHeaders.RemoveInternal ("Transfer-Encoding");
661 if (val == "chunked")
662 throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
665 throw new ArgumentException ("SendChunked must be True", "value");
667 webHeaders.RemoveAndAdd ("Transfer-Encoding", value);
671 public override bool UseDefaultCredentials
673 get { return CredentialCache.DefaultCredentials == Credentials; }
674 set { Credentials = value ? CredentialCache.DefaultCredentials : null; }
677 public string UserAgent {
678 get { return webHeaders ["User-Agent"]; }
679 set { webHeaders.SetInternal ("User-Agent", value); }
682 bool unsafe_auth_blah;
683 public bool UnsafeAuthenticatedConnectionSharing
685 get { return unsafe_auth_blah; }
686 set { unsafe_auth_blah = value; }
689 internal bool GotRequestStream {
690 get { return gotRequestStream; }
693 internal bool ExpectContinue {
694 get { return expectContinue; }
695 set { expectContinue = value; }
698 internal Uri AuthUri {
699 get { return actualUri; }
702 internal bool ProxyQuery {
703 get { return servicePoint.UsesProxy && !servicePoint.UseConnect; }
706 internal ServerCertValidationCallback ServerCertValidationCallback {
707 get { return certValidationCallback; }
710 public RemoteCertificateValidationCallback ServerCertificateValidationCallback {
712 if (certValidationCallback == null)
714 return certValidationCallback.ValidationCallback;
719 certValidationCallback = null;
721 certValidationCallback = new ServerCertValidationCallback (value);
727 internal ServicePoint GetServicePoint ()
730 if (hostChanged || servicePoint == null) {
731 servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
739 public void AddRange (int range)
741 AddRange ("bytes", (long) range);
744 public void AddRange (int from, int to)
746 AddRange ("bytes", (long) from, (long) to);
749 public void AddRange (string rangeSpecifier, int range)
751 AddRange (rangeSpecifier, (long) range);
754 public void AddRange (string rangeSpecifier, int from, int to)
756 AddRange (rangeSpecifier, (long) from, (long) to);
759 void AddRange (long range)
761 AddRange ("bytes", (long) range);
765 void AddRange (long from, long to)
767 AddRange ("bytes", from, to);
771 void AddRange (string rangeSpecifier, long range)
773 if (rangeSpecifier == null)
774 throw new ArgumentNullException ("rangeSpecifier");
775 if (!WebHeaderCollection.IsHeaderValue (rangeSpecifier))
776 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
778 string r = webHeaders ["Range"];
780 r = rangeSpecifier + "=";
782 string old_specifier = r.Substring (0, r.IndexOf ('='));
783 if (String.Compare (old_specifier, rangeSpecifier, StringComparison.OrdinalIgnoreCase) != 0)
784 throw new InvalidOperationException ("A different range specifier is already in use");
788 string n = range.ToString (CultureInfo.InvariantCulture);
793 webHeaders.RemoveAndAdd ("Range", r);
797 void AddRange (string rangeSpecifier, long from, long to)
799 if (rangeSpecifier == null)
800 throw new ArgumentNullException ("rangeSpecifier");
801 if (!WebHeaderCollection.IsHeaderValue (rangeSpecifier))
802 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
803 if (from > to || from < 0)
804 throw new ArgumentOutOfRangeException ("from");
806 throw new ArgumentOutOfRangeException ("to");
808 string r = webHeaders ["Range"];
810 r = rangeSpecifier + "=";
814 r = String.Format ("{0}{1}-{2}", r, from, to);
815 webHeaders.RemoveAndAdd ("Range", r);
819 public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
822 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
824 bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
826 if (method == null || !send)
827 throw new ProtocolViolationException ("Cannot send data when method is: " + method);
829 if (contentLength == -1 && !sendChunked && !allowBuffering && KeepAlive)
830 throw new ProtocolViolationException ("Content-Length not set");
832 string transferEncoding = TransferEncoding;
833 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
834 throw new ProtocolViolationException ("SendChunked should be true.");
838 if (getResponseCalled)
839 throw new InvalidOperationException ("The operation cannot be performed once the request has been submitted.");
841 if (asyncWrite != null) {
842 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
843 "method while a previous call is still in progress.");
846 asyncWrite = new WebAsyncResult (this, callback, state);
847 initialMethod = method;
849 if (writeStream != null) {
850 asyncWrite.SetCompleted (true, writeStream);
851 asyncWrite.DoCallback ();
856 gotRequestStream = true;
857 WebAsyncResult result = asyncWrite;
861 servicePoint = GetServicePoint ();
862 abortHandler = servicePoint.SendRequest (this, connectionGroup);
868 public override Stream EndGetRequestStream (IAsyncResult asyncResult)
870 if (asyncResult == null)
871 throw new ArgumentNullException ("asyncResult");
873 WebAsyncResult result = asyncResult as WebAsyncResult;
875 throw new ArgumentException ("Invalid IAsyncResult");
878 result.WaitUntilComplete ();
880 Exception e = result.Exception;
884 return result.WriteStream;
887 public override Stream GetRequestStream()
889 IAsyncResult asyncResult = asyncWrite;
890 if (asyncResult == null) {
891 asyncResult = BeginGetRequestStream (null, null);
892 asyncWrite = (WebAsyncResult) asyncResult;
895 if (!asyncResult.IsCompleted && !asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
897 throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
900 return EndGetRequestStream (asyncResult);
903 bool CheckIfForceWrite (SimpleAsyncResult result)
905 if (writeStream == null || writeStream.RequestWritten || !InternalAllowBuffering)
907 if (contentLength < 0 && writeStream.CanWrite == true && writeStream.WriteBufferLength < 0)
910 if (contentLength < 0 && writeStream.WriteBufferLength >= 0)
911 InternalContentLength = writeStream.WriteBufferLength;
913 // This will write the POST/PUT if the write stream already has the expected
914 // amount of bytes in it (ContentLength) (bug #77753) or if the write stream
915 // contains data and it has been closed already (xamarin bug #1512).
917 if (writeStream.WriteBufferLength == contentLength || (contentLength == -1 && writeStream.CanWrite == false))
918 return writeStream.WriteRequestAsync (result);
923 public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
926 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
929 throw new ProtocolViolationException ("Method is null.");
931 string transferEncoding = TransferEncoding;
932 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
933 throw new ProtocolViolationException ("SendChunked should be true.");
935 Monitor.Enter (locker);
936 getResponseCalled = true;
937 if (asyncRead != null && !haveResponse) {
938 Monitor.Exit (locker);
939 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
940 "method while a previous call is still in progress.");
943 asyncRead = new WebAsyncResult (this, callback, state);
944 WebAsyncResult aread = asyncRead;
945 initialMethod = method;
947 SimpleAsyncResult.RunWithLock (locker, CheckIfForceWrite, inner => {
948 var synch = inner.CompletedSynchronously;
950 if (inner.GotException) {
951 aread.SetCompleted (synch, inner.Exception);
957 Exception saved = saved_exc;
958 if (webResponse != null) {
960 aread.SetCompleted (synch, webResponse);
962 aread.SetCompleted (synch, saved);
966 } else if (saved != null) {
967 aread.SetCompleted (synch, saved);
979 servicePoint = GetServicePoint ();
980 abortHandler = servicePoint.SendRequest (this, connectionGroup);
981 } catch (Exception ex) {
982 aread.SetCompleted (synch, ex);
990 public override WebResponse EndGetResponse (IAsyncResult asyncResult)
992 if (asyncResult == null)
993 throw new ArgumentNullException ("asyncResult");
995 WebAsyncResult result = asyncResult as WebAsyncResult;
997 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
999 if (!result.WaitUntilComplete (timeout, false)) {
1001 throw new WebException("The request timed out", WebExceptionStatus.Timeout);
1004 if (result.GotException)
1005 throw result.Exception;
1007 return result.Response;
1010 public Stream EndGetRequestStream (IAsyncResult asyncResult, out TransportContext transportContext)
1012 transportContext = null;
1013 return EndGetRequestStream (asyncResult);
1016 public override WebResponse GetResponse()
1018 WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
1019 return EndGetResponse (result);
1022 internal bool FinishedReading {
1023 get { return finished_reading; }
1024 set { finished_reading = value; }
1027 internal bool Aborted {
1028 get { return Interlocked.CompareExchange (ref aborted, 0, 0) == 1; }
1031 public override void Abort ()
1033 if (Interlocked.CompareExchange (ref aborted, 1, 0) == 1)
1036 if (haveResponse && finished_reading)
1039 haveResponse = true;
1040 if (abortHandler != null) {
1042 abortHandler (this, EventArgs.Empty);
1043 } catch (Exception) {}
1044 abortHandler = null;
1047 if (asyncWrite != null) {
1048 WebAsyncResult r = asyncWrite;
1049 if (!r.IsCompleted) {
1051 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
1052 r.SetCompleted (false, wexc);
1059 if (asyncRead != null) {
1060 WebAsyncResult r = asyncRead;
1061 if (!r.IsCompleted) {
1063 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
1064 r.SetCompleted (false, wexc);
1071 if (writeStream != null) {
1073 writeStream.Close ();
1078 if (webResponse != null) {
1080 webResponse.Close ();
1086 void ISerializable.GetObjectData (SerializationInfo serializationInfo,
1087 StreamingContext streamingContext)
1089 GetObjectData (serializationInfo, streamingContext);
1092 protected override void GetObjectData (SerializationInfo serializationInfo,
1093 StreamingContext streamingContext)
1095 SerializationInfo info = serializationInfo;
1097 info.AddValue ("requestUri", requestUri, typeof (Uri));
1098 info.AddValue ("actualUri", actualUri, typeof (Uri));
1099 info.AddValue ("allowAutoRedirect", allowAutoRedirect);
1100 info.AddValue ("allowBuffering", allowBuffering);
1101 info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
1102 info.AddValue ("connectionGroup", connectionGroup);
1103 info.AddValue ("contentLength", contentLength);
1104 info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
1105 info.AddValue ("keepAlive", keepAlive);
1106 info.AddValue ("maxAutoRedirect", maxAutoRedirect);
1107 info.AddValue ("mediaType", mediaType);
1108 info.AddValue ("method", method);
1109 info.AddValue ("initialMethod", initialMethod);
1110 info.AddValue ("pipelined", pipelined);
1111 info.AddValue ("version", version, typeof (Version));
1112 info.AddValue ("proxy", proxy, typeof (IWebProxy));
1113 info.AddValue ("sendChunked", sendChunked);
1114 info.AddValue ("timeout", timeout);
1115 info.AddValue ("redirects", redirects);
1116 info.AddValue ("host", host);
1119 void CheckRequestStarted ()
1122 throw new InvalidOperationException ("request started");
1125 internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
1127 if (continueDelegate != null)
1128 continueDelegate (statusCode, headers);
1131 void RewriteRedirectToGet ()
1134 webHeaders.RemoveInternal ("Transfer-Encoding");
1135 sendChunked = false;
1138 bool Redirect (WebAsyncResult result, HttpStatusCode code, WebResponse response)
1142 string uriString = null;
1144 case HttpStatusCode.Ambiguous: // 300
1145 e = new WebException ("Ambiguous redirect.");
1147 case HttpStatusCode.MovedPermanently: // 301
1148 case HttpStatusCode.Redirect: // 302
1149 if (method == "POST")
1150 RewriteRedirectToGet ();
1152 case HttpStatusCode.TemporaryRedirect: // 307
1154 case HttpStatusCode.SeeOther: //303
1155 RewriteRedirectToGet ();
1157 case HttpStatusCode.NotModified: // 304
1159 case HttpStatusCode.UseProxy: // 305
1160 e = new NotImplementedException ("Proxy support not available.");
1162 case HttpStatusCode.Unused: // 306
1164 e = new ProtocolViolationException ("Invalid status code: " + (int) code);
1168 if (method != "GET" && !InternalAllowBuffering && (writeStream.WriteBufferLength > 0 || contentLength > 0))
1169 e = new WebException ("The request requires buffering data to succeed.", null, WebExceptionStatus.ProtocolError, webResponse);
1174 if (AllowWriteStreamBuffering || method == "GET")
1177 uriString = webResponse.Headers ["Location"];
1179 if (uriString == null)
1180 throw new WebException ("No Location header found for " + (int) code,
1181 WebExceptionStatus.ProtocolError);
1183 Uri prev = actualUri;
1185 actualUri = new Uri (actualUri, uriString);
1186 } catch (Exception) {
1187 throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
1188 uriString, (int) code),
1189 WebExceptionStatus.ProtocolError);
1192 hostChanged = (actualUri.Scheme != prev.Scheme || Host != prev.Authority);
1196 string GetHeaders ()
1198 bool continue100 = false;
1201 webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
1202 webHeaders.RemoveInternal ("Content-Length");
1203 } else if (contentLength != -1) {
1204 if (auth_state.NtlmAuthState == NtlmAuthState.Challenge || proxy_auth_state.NtlmAuthState == NtlmAuthState.Challenge) {
1205 // We don't send any body with the NTLM Challenge request.
1206 if (haveContentLength || gotRequestStream || contentLength > 0)
1207 webHeaders.SetInternal ("Content-Length", "0");
1209 webHeaders.RemoveInternal ("Content-Length");
1211 if (contentLength > 0)
1214 if (haveContentLength || gotRequestStream || contentLength > 0)
1215 webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
1217 webHeaders.RemoveInternal ("Transfer-Encoding");
1219 webHeaders.RemoveInternal ("Content-Length");
1222 if (actualVersion == HttpVersion.Version11 && continue100 &&
1223 servicePoint.SendContinue) { // RFC2616 8.2.3
1224 webHeaders.RemoveAndAdd ("Expect" , "100-continue");
1225 expectContinue = true;
1227 webHeaders.RemoveInternal ("Expect");
1228 expectContinue = false;
1231 bool proxy_query = ProxyQuery;
1232 string connectionHeader = (proxy_query) ? "Proxy-Connection" : "Connection";
1233 webHeaders.RemoveInternal ((!proxy_query) ? "Proxy-Connection" : "Connection");
1234 Version proto_version = servicePoint.ProtocolVersion;
1235 bool spoint10 = (proto_version == null || proto_version == HttpVersion.Version10);
1237 if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
1238 if (webHeaders[connectionHeader] == null
1239 || webHeaders[connectionHeader].IndexOf ("keep-alive", StringComparison.OrdinalIgnoreCase) == -1)
1240 webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
1241 } else if (!keepAlive && version == HttpVersion.Version11) {
1242 webHeaders.RemoveAndAdd (connectionHeader, "close");
1245 webHeaders.SetInternal ("Host", Host);
1246 if (cookieContainer != null) {
1247 string cookieHeader = cookieContainer.GetCookieHeader (actualUri);
1248 if (cookieHeader != "")
1249 webHeaders.RemoveAndAdd ("Cookie", cookieHeader);
1251 webHeaders.RemoveInternal ("Cookie");
1254 string accept_encoding = null;
1255 if ((auto_decomp & DecompressionMethods.GZip) != 0)
1256 accept_encoding = "gzip";
1257 if ((auto_decomp & DecompressionMethods.Deflate) != 0)
1258 accept_encoding = accept_encoding != null ? "gzip, deflate" : "deflate";
1259 if (accept_encoding != null)
1260 webHeaders.RemoveAndAdd ("Accept-Encoding", accept_encoding);
1262 if (!usedPreAuth && preAuthenticate)
1263 DoPreAuthenticate ();
1265 return webHeaders.ToString ();
1268 void DoPreAuthenticate ()
1270 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1271 ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
1272 Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
1276 webHeaders.RemoveInternal ("Proxy-Authorization");
1277 webHeaders.RemoveInternal ("Authorization");
1278 string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
1279 webHeaders [authHeader] = auth.Message;
1283 internal void SetWriteStreamError (WebExceptionStatus status, Exception exc)
1288 WebAsyncResult r = asyncWrite;
1296 msg = "Error: " + status;
1297 wex = new WebException (msg, status);
1299 msg = String.Format ("Error: {0} ({1})", status, exc.Message);
1300 wex = new WebException (msg, exc, status);
1302 r.SetCompleted (false, wex);
1307 internal byte[] GetRequestHeaders ()
1309 StringBuilder req = new StringBuilder ();
1312 query = actualUri.PathAndQuery;
1314 query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
1316 actualUri.PathAndQuery);
1319 if (!force_version && servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
1320 actualVersion = servicePoint.ProtocolVersion;
1322 actualVersion = version;
1325 req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
1326 actualVersion.Major, actualVersion.Minor);
1327 req.Append (GetHeaders ());
1328 string reqstr = req.ToString ();
1329 return Encoding.UTF8.GetBytes (reqstr);
1332 internal void SetWriteStream (WebConnectionStream stream)
1337 writeStream = stream;
1338 if (bodyBuffer != null) {
1339 webHeaders.RemoveInternal ("Transfer-Encoding");
1340 contentLength = bodyBufferLength;
1341 writeStream.SendChunked = false;
1344 writeStream.SetHeadersAsync (false, result => {
1345 if (result.GotException) {
1346 SetWriteStreamError (result.Exception);
1352 SetWriteStreamInner (inner => {
1353 if (inner.GotException) {
1354 SetWriteStreamError (inner.Exception);
1358 if (asyncWrite != null) {
1359 asyncWrite.SetCompleted (inner.CompletedSynchronously, writeStream);
1360 asyncWrite.DoCallback ();
1367 void SetWriteStreamInner (SimpleAsyncCallback callback)
1369 SimpleAsyncResult.Run (result => {
1370 if (bodyBuffer != null) {
1371 // The body has been written and buffered. The request "user"
1372 // won't write it again, so we must do it.
1373 if (auth_state.NtlmAuthState != NtlmAuthState.Challenge && proxy_auth_state.NtlmAuthState != NtlmAuthState.Challenge) {
1374 // FIXME: this is a blocking call on the thread pool that could lead to thread pool exhaustion
1375 writeStream.Write (bodyBuffer, 0, bodyBufferLength);
1377 writeStream.Close ();
1379 } else if (MethodWithBuffer) {
1380 if (getResponseCalled && !writeStream.RequestWritten)
1381 return writeStream.WriteRequestAsync (result);
1388 void SetWriteStreamError (Exception exc)
1390 WebException wexc = exc as WebException;
1392 SetWriteStreamError (wexc.Status, wexc);
1394 SetWriteStreamError (WebExceptionStatus.SendFailure, exc);
1397 internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
1402 string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
1403 WebAsyncResult r = asyncRead;
1408 if (e is WebException) {
1409 wexc = (WebException) e;
1411 wexc = new WebException (msg, e, status, null);
1414 if (!r.IsCompleted) {
1415 r.SetCompleted (false, wexc);
1417 } else if (r == asyncWrite) {
1420 haveResponse = true;
1424 haveResponse = true;
1430 void CheckSendError (WebConnectionData data)
1432 // Got here, but no one called GetResponse
1433 int status = data.StatusCode;
1434 if (status < 400 || status == 401 || status == 407)
1437 if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
1438 // The request has not been completely sent and we got here!
1439 // We should probably just close and cause an error in any case,
1440 saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse);
1441 if (allowBuffering || sendChunked || writeStream.totalWritten >= contentLength) {
1442 webResponse.ReadAll ();
1444 writeStream.IgnoreIOErrors = true;
1449 bool HandleNtlmAuth (WebAsyncResult r)
1451 bool isProxy = webResponse.StatusCode == HttpStatusCode.ProxyAuthenticationRequired;
1452 if ((isProxy ? proxy_auth_state.NtlmAuthState : auth_state.NtlmAuthState) == NtlmAuthState.None)
1455 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1457 WebConnection cnc = wce.Connection;
1458 cnc.PriorityRequest = this;
1459 ICredentials creds = !isProxy ? credentials : proxy.Credentials;
1460 if (creds != null) {
1461 cnc.NtlmCredential = creds.GetCredential (requestUri, "NTLM");
1462 cnc.UnsafeAuthenticatedConnectionSharing = unsafe_auth_blah;
1466 finished_reading = false;
1467 haveResponse = false;
1468 webResponse.ReadAll ();
1473 internal void SetResponseData (WebConnectionData data)
1477 if (data.stream != null)
1478 data.stream.Close ();
1482 WebException wexc = null;
1484 webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
1485 } catch (Exception e) {
1486 wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null);
1487 if (data.stream != null)
1488 data.stream.Close ();
1491 if (wexc == null && (method == "POST" || method == "PUT")) {
1492 CheckSendError (data);
1493 if (saved_exc != null)
1494 wexc = (WebException) saved_exc;
1497 WebAsyncResult r = asyncRead;
1499 bool forced = false;
1500 if (r == null && webResponse != null) {
1501 // This is a forced completion (302, 204)...
1503 r = new WebAsyncResult (null, null);
1504 r.SetCompleted (false, webResponse);
1509 haveResponse = true;
1511 r.SetCompleted (false, wexc);
1516 bool isProxy = ProxyQuery && !proxy.IsBypassed (actualUri);
1520 redirected = CheckFinalStatus (r);
1522 if ((isProxy ? proxy_auth_state.IsNtlmAuthenticated : auth_state.IsNtlmAuthenticated) &&
1523 webResponse != null && (int)webResponse.StatusCode < 400) {
1524 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1526 WebConnection cnc = wce.Connection;
1527 cnc.NtlmAuthenticated = true;
1531 // clear internal buffer so that it does not
1532 // hold possible big buffer (bug #397627)
1533 if (writeStream != null)
1534 writeStream.KillBuffer ();
1536 haveResponse = true;
1537 r.SetCompleted (false, webResponse);
1541 sendChunked = false;
1542 webHeaders.RemoveInternal ("Transfer-Encoding");
1545 if (webResponse != null) {
1546 if (HandleNtlmAuth (r))
1548 webResponse.Close ();
1550 finished_reading = false;
1551 haveResponse = false;
1554 servicePoint = GetServicePoint ();
1555 abortHandler = servicePoint.SendRequest (this, connectionGroup);
1557 } catch (WebException wexc2) {
1560 haveResponse = true;
1562 r.SetCompleted (false, wexc2);
1565 } catch (Exception ex) {
1566 wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
1569 haveResponse = true;
1571 r.SetCompleted (false, wexc);
1579 struct AuthorizationState
1581 readonly HttpWebRequest request;
1582 readonly bool isProxy;
1584 NtlmAuthState ntlm_auth_state;
1586 public bool IsCompleted {
1587 get { return isCompleted; }
1590 public NtlmAuthState NtlmAuthState {
1591 get { return ntlm_auth_state; }
1594 public bool IsNtlmAuthenticated {
1595 get { return isCompleted && ntlm_auth_state != NtlmAuthState.None; }
1598 public AuthorizationState (HttpWebRequest request, bool isProxy)
1600 this.request = request;
1601 this.isProxy = isProxy;
1602 isCompleted = false;
1603 ntlm_auth_state = NtlmAuthState.None;
1606 public bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1608 isCompleted = false;
1609 if (code == HttpStatusCode.Unauthorized && request.credentials == null)
1612 // FIXME: This should never happen!
1613 if (isProxy != (code == HttpStatusCode.ProxyAuthenticationRequired))
1616 if (isProxy && (request.proxy == null || request.proxy.Credentials == null))
1619 string [] authHeaders = response.Headers.GetValues_internal (isProxy ? "Proxy-Authenticate" : "WWW-Authenticate", false);
1620 if (authHeaders == null || authHeaders.Length == 0)
1623 ICredentials creds = (!isProxy) ? request.credentials : request.proxy.Credentials;
1624 Authorization auth = null;
1625 foreach (string authHeader in authHeaders) {
1626 auth = AuthenticationManager.Authenticate (authHeader, request, creds);
1632 request.webHeaders [isProxy ? "Proxy-Authorization" : "Authorization"] = auth.Message;
1633 isCompleted = auth.Complete;
1634 bool is_ntlm = (auth.Module.AuthenticationType == "NTLM");
1636 ntlm_auth_state = (NtlmAuthState)((int) ntlm_auth_state + 1);
1640 public void Reset ()
1642 isCompleted = false;
1643 ntlm_auth_state = NtlmAuthState.None;
1644 request.webHeaders.RemoveInternal (isProxy ? "Proxy-Authorization" : "Authorization");
1647 public override string ToString ()
1649 return string.Format ("{0}AuthState [{1}:{2}]", isProxy ? "Proxy" : "", isCompleted, ntlm_auth_state);
1653 bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1655 bool isProxy = code == HttpStatusCode.ProxyAuthenticationRequired;
1656 return isProxy ? proxy_auth_state.CheckAuthorization (response, code) : auth_state.CheckAuthorization (response, code);
1659 // Returns true if redirected
1660 bool CheckFinalStatus (WebAsyncResult result)
1662 if (result.GotException) {
1664 throw result.Exception;
1667 Exception throwMe = result.Exception;
1669 HttpWebResponse resp = result.Response;
1670 WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
1671 HttpStatusCode code = 0;
1672 if (throwMe == null && webResponse != null) {
1673 code = webResponse.StatusCode;
1674 if ((!auth_state.IsCompleted && code == HttpStatusCode.Unauthorized && credentials != null) ||
1675 (ProxyQuery && !proxy_auth_state.IsCompleted && code == HttpStatusCode.ProxyAuthenticationRequired)) {
1676 if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
1677 // Keep the written body, so it can be rewritten in the retry
1678 if (MethodWithBuffer) {
1679 if (AllowWriteStreamBuffering) {
1680 if (writeStream.WriteBufferLength > 0) {
1681 bodyBuffer = writeStream.WriteBuffer;
1682 bodyBufferLength = writeStream.WriteBufferLength;
1689 // Buffering is not allowed but we have alternative way to get same content (we
1690 // need to resent it due to NTLM Authentication).
1692 if (ResendContentFactory != null) {
1693 using (var ms = new MemoryStream ()) {
1694 ResendContentFactory (ms);
1695 bodyBuffer = ms.ToArray ();
1696 bodyBufferLength = bodyBuffer.Length;
1700 } else if (method != "PUT" && method != "POST") {
1708 writeStream.InternalClose ();
1710 webResponse.Close ();
1714 throw new WebException ("This request requires buffering " +
1715 "of data for authentication or " +
1716 "redirection to be sucessful.");
1721 if ((int) code >= 400) {
1722 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1723 (int) code, webResponse.StatusDescription);
1724 throwMe = new WebException (err, null, protoError, webResponse);
1725 webResponse.ReadAll ();
1726 } else if ((int) code == 304 && allowAutoRedirect) {
1727 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1728 (int) code, webResponse.StatusDescription);
1729 throwMe = new WebException (err, null, protoError, webResponse);
1730 } else if ((int) code >= 300 && allowAutoRedirect && redirects >= maxAutoRedirect) {
1731 throwMe = new WebException ("Max. redirections exceeded.", null,
1732 protoError, webResponse);
1733 webResponse.ReadAll ();
1738 if (throwMe == null) {
1741 if (allowAutoRedirect && c >= 300) {
1742 b = Redirect (result, code, webResponse);
1743 if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
1744 bodyBuffer = writeStream.WriteBuffer;
1745 bodyBufferLength = writeStream.WriteBufferLength;
1747 if (b && !unsafe_auth_blah) {
1748 auth_state.Reset ();
1749 proxy_auth_state.Reset ();
1753 if (resp != null && c >= 300 && c != 304)
1762 if (writeStream != null) {
1763 writeStream.InternalClose ();
1772 internal bool ReuseConnection {
1777 internal WebConnection StoredConnection;