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 using System.Collections;
36 using System.Configuration;
37 using System.Globalization;
39 using System.Net.Cache;
40 using System.Net.Sockets;
41 using System.Runtime.Remoting.Messaging;
42 using System.Runtime.Serialization;
43 using System.Security.Cryptography.X509Certificates;
45 using System.Threading;
50 public class HttpWebRequest : WebRequest, ISerializable {
54 bool allowAutoRedirect = true;
55 bool allowBuffering = true;
56 X509CertificateCollection certificates;
57 string connectionGroup;
58 long contentLength = -1;
59 HttpContinueDelegate continueDelegate;
60 CookieContainer cookieContainer;
61 ICredentials credentials;
65 WebHeaderCollection webHeaders;
66 bool keepAlive = true;
67 int maxAutoRedirect = 50;
68 string mediaType = String.Empty;
69 string method = "GET";
70 string initialMethod = "GET";
71 bool pipelined = true;
74 Version version = HttpVersion.Version11;
76 Version actualVersion;
79 ServicePoint servicePoint;
82 WebConnectionStream writeStream;
83 HttpWebResponse webResponse;
84 WebAsyncResult asyncWrite;
85 WebAsyncResult asyncRead;
86 EventHandler abortHandler;
88 bool gotRequestStream;
94 bool getResponseCalled;
96 object locker = new object ();
97 bool finished_reading;
98 internal WebConnection WebConnection;
99 DecompressionMethods auto_decomp;
100 int maxResponseHeadersLength;
101 static int defaultMaxResponseHeadersLength;
102 int readWriteTimeout = 300000; // ms
109 NtlmAuthState ntlm_auth_state;
113 static HttpWebRequest ()
115 defaultMaxResponseHeadersLength = 64 * 1024;
117 NetConfig config = ConfigurationSettings.GetConfig ("system.net/settings") as NetConfig;
118 if (config != null) {
119 int x = config.MaxResponseHeadersLength;
123 defaultMaxResponseHeadersLength = x;
133 HttpWebRequest (Uri uri)
135 this.requestUri = uri;
136 this.actualUri = uri;
137 this.proxy = GlobalProxySelection.Select;
138 this.webHeaders = new WebHeaderCollection (WebHeaderCollection.HeaderInfo.Request);
142 [Obsolete ("Serialization is obsoleted for this type", false)]
143 protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
145 SerializationInfo info = serializationInfo;
147 requestUri = (Uri) info.GetValue ("requestUri", typeof (Uri));
148 actualUri = (Uri) info.GetValue ("actualUri", typeof (Uri));
149 allowAutoRedirect = info.GetBoolean ("allowAutoRedirect");
150 allowBuffering = info.GetBoolean ("allowBuffering");
151 certificates = (X509CertificateCollection) info.GetValue ("certificates", typeof (X509CertificateCollection));
152 connectionGroup = info.GetString ("connectionGroup");
153 contentLength = info.GetInt64 ("contentLength");
154 webHeaders = (WebHeaderCollection) info.GetValue ("webHeaders", typeof (WebHeaderCollection));
155 keepAlive = info.GetBoolean ("keepAlive");
156 maxAutoRedirect = info.GetInt32 ("maxAutoRedirect");
157 mediaType = info.GetString ("mediaType");
158 method = info.GetString ("method");
159 initialMethod = info.GetString ("initialMethod");
160 pipelined = info.GetBoolean ("pipelined");
161 version = (Version) info.GetValue ("version", typeof (Version));
162 proxy = (IWebProxy) info.GetValue ("proxy", typeof (IWebProxy));
163 sendChunked = info.GetBoolean ("sendChunked");
164 timeout = info.GetInt32 ("timeout");
165 redirects = info.GetInt32 ("redirects");
166 host = info.GetString ("host");
171 public string Accept {
172 get { return webHeaders ["Accept"]; }
174 CheckRequestStarted ();
175 webHeaders.RemoveAndAdd ("Accept", value);
180 get { return actualUri; }
181 internal set { actualUri = value; } // Used by Ftp+proxy
184 public bool AllowAutoRedirect {
185 get { return allowAutoRedirect; }
186 set { this.allowAutoRedirect = value; }
189 public bool AllowWriteStreamBuffering {
190 get { return allowBuffering; }
191 set { allowBuffering = value; }
195 public virtual bool AllowReadStreamBuffering {
196 get { return allowBuffering; }
197 set { allowBuffering = value; }
201 static Exception GetMustImplement ()
203 return new NotImplementedException ();
206 public DecompressionMethods AutomaticDecompression
212 CheckRequestStarted ();
217 internal bool InternalAllowBuffering {
219 return (allowBuffering && (method != "HEAD" && method != "GET" &&
220 method != "MKCOL" && method != "CONNECT" &&
225 public X509CertificateCollection ClientCertificates {
227 if (certificates == null)
228 certificates = new X509CertificateCollection ();
234 throw GetMustImplement ();
238 public string Connection {
239 get { return webHeaders ["Connection"]; }
241 CheckRequestStarted ();
243 if (string.IsNullOrEmpty (value)) {
244 webHeaders.RemoveInternal ("Connection");
248 string val = value.ToLowerInvariant ();
249 if (val.Contains ("keep-alive") || val.Contains ("close"))
250 throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
253 value = value + ", Keep-Alive";
255 webHeaders.RemoveAndAdd ("Connection", value);
259 public override string ConnectionGroupName {
260 get { return connectionGroup; }
261 set { connectionGroup = value; }
264 public override long ContentLength {
265 get { return contentLength; }
267 CheckRequestStarted ();
269 throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
271 contentLength = value;
275 internal long InternalContentLength {
276 set { contentLength = value; }
279 internal bool ThrowOnError { get; set; }
281 public override string ContentType {
282 get { return webHeaders ["Content-Type"]; }
284 if (value == null || value.Trim().Length == 0) {
285 webHeaders.RemoveInternal ("Content-Type");
288 webHeaders.RemoveAndAdd ("Content-Type", value);
292 public HttpContinueDelegate ContinueDelegate {
293 get { return continueDelegate; }
294 set { continueDelegate = value; }
300 public CookieContainer CookieContainer {
301 get { return cookieContainer; }
302 set { cookieContainer = value; }
305 public override ICredentials Credentials {
306 get { return credentials; }
307 set { credentials = value; }
310 public DateTime Date {
312 string date = webHeaders ["Date"];
314 return DateTime.MinValue;
315 return DateTime.ParseExact (date, "r", CultureInfo.InvariantCulture).ToLocalTime ();
318 if (value.Equals (DateTime.MinValue))
319 webHeaders.RemoveInternal ("Date");
321 webHeaders.RemoveAndAdd ("Date", value.ToUniversalTime ().ToString ("r", CultureInfo.InvariantCulture));
328 public static new RequestCachePolicy DefaultCachePolicy
331 throw GetMustImplement ();
334 throw GetMustImplement ();
340 public static int DefaultMaximumErrorResponseLength
343 throw GetMustImplement ();
346 throw GetMustImplement ();
350 public string Expect {
351 get { return webHeaders ["Expect"]; }
353 CheckRequestStarted ();
356 val = val.Trim ().ToLower ();
358 if (val == null || val.Length == 0) {
359 webHeaders.RemoveInternal ("Expect");
363 if (val == "100-continue")
364 throw new ArgumentException ("100-Continue cannot be set with this property.",
366 webHeaders.RemoveAndAdd ("Expect", value);
373 public bool HaveResponse {
374 get { return haveResponse; }
377 public override WebHeaderCollection Headers {
378 get { return webHeaders; }
380 CheckRequestStarted ();
381 WebHeaderCollection newHeaders = new WebHeaderCollection (WebHeaderCollection.HeaderInfo.Request);
382 int count = value.Count;
383 for (int i = 0; i < count; i++)
384 newHeaders.Add (value.GetKey (i), value.Get (i));
386 webHeaders = newHeaders;
398 return actualUri.Authority;
403 throw new ArgumentNullException ("value");
405 if (!CheckValidHost (actualUri.Scheme, value))
406 throw new ArgumentException ("Invalid host: " + value);
412 static bool CheckValidHost (string scheme, string val)
420 int idx = val.IndexOf ('/');
424 string u = scheme + "://" + val + "/";
425 return Uri.IsWellFormedUriString (u, UriKind.Absolute);
428 public DateTime IfModifiedSince {
430 string str = webHeaders ["If-Modified-Since"];
434 return MonoHttpDate.Parse (str);
435 } catch (Exception) {
440 CheckRequestStarted ();
442 webHeaders.SetInternal ("If-Modified-Since",
443 value.ToUniversalTime ().ToString ("r", null));
444 // TODO: check last param when using different locale
448 public bool KeepAlive {
457 public int MaximumAutomaticRedirections {
458 get { return maxAutoRedirect; }
461 throw new ArgumentException ("Must be > 0", "value");
463 maxAutoRedirect = value;
467 [MonoTODO ("Use this")]
468 public int MaximumResponseHeadersLength {
469 get { return maxResponseHeadersLength; }
470 set { maxResponseHeadersLength = value; }
473 [MonoTODO ("Use this")]
474 public static int DefaultMaximumResponseHeadersLength {
475 get { return defaultMaxResponseHeadersLength; }
476 set { defaultMaxResponseHeadersLength = value; }
479 public int ReadWriteTimeout {
480 get { return readWriteTimeout; }
483 throw new InvalidOperationException ("The request has already been sent.");
486 throw new ArgumentOutOfRangeException ("value", "Must be >= -1");
488 readWriteTimeout = value;
494 public int ContinueTimeout {
495 get { throw new NotImplementedException (); }
496 set { throw new NotImplementedException (); }
500 public string MediaType {
501 get { return mediaType; }
507 public override string Method {
508 get { return this.method; }
510 if (value == null || value.Trim () == "")
511 throw new ArgumentException ("not a valid method");
513 method = value.ToUpperInvariant ();
514 if (method != "HEAD" && method != "GET" && method != "POST" && method != "PUT" &&
515 method != "DELETE" && method != "CONNECT" && method != "TRACE" &&
522 public bool Pipelined {
523 get { return pipelined; }
524 set { pipelined = value; }
527 public override bool PreAuthenticate {
528 get { return preAuthenticate; }
529 set { preAuthenticate = value; }
532 public Version ProtocolVersion {
533 get { return version; }
535 if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
536 throw new ArgumentException ("value");
538 force_version = true;
543 public override IWebProxy Proxy {
544 get { return proxy; }
546 CheckRequestStarted ();
548 servicePoint = null; // we may need a new one
552 public string Referer {
553 get { return webHeaders ["Referer"]; }
555 CheckRequestStarted ();
556 if (value == null || value.Trim().Length == 0) {
557 webHeaders.RemoveInternal ("Referer");
560 webHeaders.SetInternal ("Referer", value);
564 public override Uri RequestUri {
565 get { return requestUri; }
568 public bool SendChunked {
569 get { return sendChunked; }
571 CheckRequestStarted ();
576 public ServicePoint ServicePoint {
577 get { return GetServicePoint (); }
580 internal ServicePoint ServicePointNoLock {
581 get { return servicePoint; }
584 [MonoTODO ("for portable library support")]
585 public virtual bool SupportsCookieContainer {
587 throw new NotImplementedException ();
591 public override int Timeout {
592 get { return timeout; }
595 throw new ArgumentOutOfRangeException ("value");
601 public string TransferEncoding {
602 get { return webHeaders ["Transfer-Encoding"]; }
604 CheckRequestStarted ();
607 val = val.Trim ().ToLower ();
609 if (val == null || val.Length == 0) {
610 webHeaders.RemoveInternal ("Transfer-Encoding");
614 if (val == "chunked")
615 throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
618 throw new ArgumentException ("SendChunked must be True", "value");
620 webHeaders.RemoveAndAdd ("Transfer-Encoding", value);
624 public override bool UseDefaultCredentials
626 get { return CredentialCache.DefaultCredentials == Credentials; }
627 set { Credentials = value ? CredentialCache.DefaultCredentials : null; }
630 public string UserAgent {
631 get { return webHeaders ["User-Agent"]; }
632 set { webHeaders.SetInternal ("User-Agent", value); }
635 bool unsafe_auth_blah;
636 public bool UnsafeAuthenticatedConnectionSharing
638 get { return unsafe_auth_blah; }
639 set { unsafe_auth_blah = value; }
642 internal bool GotRequestStream {
643 get { return gotRequestStream; }
646 internal bool ExpectContinue {
647 get { return expectContinue; }
648 set { expectContinue = value; }
651 internal Uri AuthUri {
652 get { return actualUri; }
655 internal bool ProxyQuery {
656 get { return servicePoint.UsesProxy && !servicePoint.UseConnect; }
661 internal ServicePoint GetServicePoint ()
664 if (hostChanged || servicePoint == null) {
665 servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
673 public void AddRange (int range)
675 AddRange ("bytes", (long) range);
678 public void AddRange (int from, int to)
680 AddRange ("bytes", (long) from, (long) to);
683 public void AddRange (string rangeSpecifier, int range)
685 AddRange (rangeSpecifier, (long) range);
688 public void AddRange (string rangeSpecifier, int from, int to)
690 AddRange (rangeSpecifier, (long) from, (long) to);
697 void AddRange (long range)
699 AddRange ("bytes", (long) range);
707 void AddRange (long from, long to)
709 AddRange ("bytes", from, to);
717 void AddRange (string rangeSpecifier, long range)
719 if (rangeSpecifier == null)
720 throw new ArgumentNullException ("rangeSpecifier");
721 if (!WebHeaderCollection.IsHeaderValue (rangeSpecifier))
722 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
724 string r = webHeaders ["Range"];
726 r = rangeSpecifier + "=";
728 string old_specifier = r.Substring (0, r.IndexOf ('='));
729 if (String.Compare (old_specifier, rangeSpecifier, StringComparison.OrdinalIgnoreCase) != 0)
730 throw new InvalidOperationException ("A different range specifier is already in use");
734 string n = range.ToString (CultureInfo.InvariantCulture);
739 webHeaders.RemoveAndAdd ("Range", r);
747 void AddRange (string rangeSpecifier, long from, long to)
749 if (rangeSpecifier == null)
750 throw new ArgumentNullException ("rangeSpecifier");
751 if (!WebHeaderCollection.IsHeaderValue (rangeSpecifier))
752 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
753 if (from > to || from < 0)
754 throw new ArgumentOutOfRangeException ("from");
756 throw new ArgumentOutOfRangeException ("to");
758 string r = webHeaders ["Range"];
760 r = rangeSpecifier + "=";
764 r = String.Format ("{0}{1}-{2}", r, from, to);
765 webHeaders.RemoveAndAdd ("Range", r);
769 public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
772 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
774 bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
776 if (method == null || !send)
777 throw new ProtocolViolationException ("Cannot send data when method is: " + method);
779 if (contentLength == -1 && !sendChunked && !allowBuffering && KeepAlive)
780 throw new ProtocolViolationException ("Content-Length not set");
782 string transferEncoding = TransferEncoding;
783 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
784 throw new ProtocolViolationException ("SendChunked should be true.");
788 if (getResponseCalled)
789 throw new InvalidOperationException ("The operation cannot be performed once the request has been submitted.");
791 if (asyncWrite != null) {
792 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
793 "method while a previous call is still in progress.");
796 asyncWrite = new WebAsyncResult (this, callback, state);
797 initialMethod = method;
799 if (writeStream != null) {
800 asyncWrite.SetCompleted (true, writeStream);
801 asyncWrite.DoCallback ();
806 gotRequestStream = true;
807 WebAsyncResult result = asyncWrite;
811 servicePoint = GetServicePoint ();
812 abortHandler = servicePoint.SendRequest (this, connectionGroup);
818 public override Stream EndGetRequestStream (IAsyncResult asyncResult)
820 if (asyncResult == null)
821 throw new ArgumentNullException ("asyncResult");
823 WebAsyncResult result = asyncResult as WebAsyncResult;
825 throw new ArgumentException ("Invalid IAsyncResult");
828 result.WaitUntilComplete ();
830 Exception e = result.Exception;
834 return result.WriteStream;
837 public override Stream GetRequestStream()
839 IAsyncResult asyncResult = asyncWrite;
840 if (asyncResult == null) {
841 asyncResult = BeginGetRequestStream (null, null);
842 asyncWrite = (WebAsyncResult) asyncResult;
845 if (!asyncResult.IsCompleted && !asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
847 throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
850 return EndGetRequestStream (asyncResult);
853 void CheckIfForceWrite ()
855 if (writeStream == null || writeStream.RequestWritten || !InternalAllowBuffering)
858 if (contentLength < 0 && writeStream.CanWrite == true && writeStream.WriteBufferLength < 0)
861 if (contentLength < 0 && writeStream.WriteBufferLength >= 0)
862 InternalContentLength = writeStream.WriteBufferLength;
864 if (contentLength < 0 && writeStream.CanWrite == true)
868 // This will write the POST/PUT if the write stream already has the expected
869 // amount of bytes in it (ContentLength) (bug #77753) or if the write stream
870 // contains data and it has been closed already (xamarin bug #1512).
872 if (writeStream.WriteBufferLength == contentLength || (contentLength == -1 && writeStream.CanWrite == false))
873 writeStream.WriteRequest ();
876 public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
879 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
882 throw new ProtocolViolationException ("Method is null.");
884 string transferEncoding = TransferEncoding;
885 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
886 throw new ProtocolViolationException ("SendChunked should be true.");
888 Monitor.Enter (locker);
889 getResponseCalled = true;
890 if (asyncRead != null && !haveResponse) {
891 Monitor.Exit (locker);
892 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
893 "method while a previous call is still in progress.");
896 CheckIfForceWrite ();
897 asyncRead = new WebAsyncResult (this, callback, state);
898 WebAsyncResult aread = asyncRead;
899 initialMethod = method;
901 Exception saved = saved_exc;
902 if (webResponse != null) {
903 Monitor.Exit (locker);
905 aread.SetCompleted (true, webResponse);
907 aread.SetCompleted (true, saved);
911 } else if (saved != null) {
912 Monitor.Exit (locker);
913 aread.SetCompleted (true, saved);
922 servicePoint = GetServicePoint ();
923 abortHandler = servicePoint.SendRequest (this, connectionGroup);
926 Monitor.Exit (locker);
930 public override WebResponse EndGetResponse (IAsyncResult asyncResult)
932 if (asyncResult == null)
933 throw new ArgumentNullException ("asyncResult");
935 WebAsyncResult result = asyncResult as WebAsyncResult;
937 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
939 if (!result.WaitUntilComplete (timeout, false)) {
941 throw new WebException("The request timed out", WebExceptionStatus.Timeout);
944 if (result.GotException)
945 throw result.Exception;
947 return result.Response;
950 public override WebResponse GetResponse()
952 WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
953 return EndGetResponse (result);
956 internal bool FinishedReading {
957 get { return finished_reading; }
958 set { finished_reading = value; }
961 internal bool Aborted {
962 get { return Interlocked.CompareExchange (ref aborted, 0, 0) == 1; }
965 public override void Abort ()
967 if (Interlocked.CompareExchange (ref aborted, 1, 0) == 1)
970 if (haveResponse && finished_reading)
974 if (abortHandler != null) {
976 abortHandler (this, EventArgs.Empty);
977 } catch (Exception) {}
981 if (asyncWrite != null) {
982 WebAsyncResult r = asyncWrite;
983 if (!r.IsCompleted) {
985 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
986 r.SetCompleted (false, wexc);
993 if (asyncRead != null) {
994 WebAsyncResult r = asyncRead;
995 if (!r.IsCompleted) {
997 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
998 r.SetCompleted (false, wexc);
1005 if (writeStream != null) {
1007 writeStream.Close ();
1012 if (webResponse != null) {
1014 webResponse.Close ();
1020 void ISerializable.GetObjectData (SerializationInfo serializationInfo,
1021 StreamingContext streamingContext)
1023 GetObjectData (serializationInfo, streamingContext);
1026 protected override void GetObjectData (SerializationInfo serializationInfo,
1027 StreamingContext streamingContext)
1029 SerializationInfo info = serializationInfo;
1031 info.AddValue ("requestUri", requestUri, typeof (Uri));
1032 info.AddValue ("actualUri", actualUri, typeof (Uri));
1033 info.AddValue ("allowAutoRedirect", allowAutoRedirect);
1034 info.AddValue ("allowBuffering", allowBuffering);
1035 info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
1036 info.AddValue ("connectionGroup", connectionGroup);
1037 info.AddValue ("contentLength", contentLength);
1038 info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
1039 info.AddValue ("keepAlive", keepAlive);
1040 info.AddValue ("maxAutoRedirect", maxAutoRedirect);
1041 info.AddValue ("mediaType", mediaType);
1042 info.AddValue ("method", method);
1043 info.AddValue ("initialMethod", initialMethod);
1044 info.AddValue ("pipelined", pipelined);
1045 info.AddValue ("version", version, typeof (Version));
1046 info.AddValue ("proxy", proxy, typeof (IWebProxy));
1047 info.AddValue ("sendChunked", sendChunked);
1048 info.AddValue ("timeout", timeout);
1049 info.AddValue ("redirects", redirects);
1050 info.AddValue ("host", host);
1053 void CheckRequestStarted ()
1056 throw new InvalidOperationException ("request started");
1059 internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
1061 if (continueDelegate != null)
1062 continueDelegate (statusCode, headers);
1065 bool Redirect (WebAsyncResult result, HttpStatusCode code)
1069 string uriString = null;
1072 case HttpStatusCode.Ambiguous: // 300
1073 e = new WebException ("Ambiguous redirect.");
1075 case HttpStatusCode.MovedPermanently: // 301
1076 case HttpStatusCode.Redirect: // 302
1077 case HttpStatusCode.TemporaryRedirect: // 307
1078 /* MS follows the redirect for POST too
1079 if (method != "GET" && method != "HEAD") // 10.3
1084 bodyBufferLength = 0;
1086 if (code != HttpStatusCode.TemporaryRedirect)
1088 uriString = webResponse.Headers ["Location"];
1090 case HttpStatusCode.SeeOther: //303
1092 uriString = webResponse.Headers ["Location"];
1094 case HttpStatusCode.NotModified: // 304
1096 case HttpStatusCode.UseProxy: // 305
1097 e = new NotImplementedException ("Proxy support not available.");
1099 case HttpStatusCode.Unused: // 306
1101 e = new ProtocolViolationException ("Invalid status code: " + (int) code);
1108 if (uriString == null)
1109 throw new WebException ("No Location header found for " + (int) code,
1110 WebExceptionStatus.ProtocolError);
1112 Uri prev = actualUri;
1114 actualUri = new Uri (actualUri, uriString);
1115 } catch (Exception) {
1116 throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
1117 uriString, (int) code),
1118 WebExceptionStatus.ProtocolError);
1121 hostChanged = (actualUri.Scheme != prev.Scheme || Host != prev.Authority);
1125 string GetHeaders ()
1127 bool continue100 = false;
1130 webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
1131 webHeaders.RemoveInternal ("Content-Length");
1132 } else if (contentLength != -1) {
1133 if (ntlm_auth_state != NtlmAuthState.Challenge) {
1134 if (contentLength > 0)
1137 webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
1139 webHeaders.SetInternal ("Content-Length", "0");
1141 webHeaders.RemoveInternal ("Transfer-Encoding");
1143 webHeaders.RemoveInternal ("Content-Length");
1146 if (actualVersion == HttpVersion.Version11 && continue100 &&
1147 servicePoint.SendContinue) { // RFC2616 8.2.3
1148 webHeaders.RemoveAndAdd ("Expect" , "100-continue");
1149 expectContinue = true;
1151 webHeaders.RemoveInternal ("Expect");
1152 expectContinue = false;
1155 bool proxy_query = ProxyQuery;
1156 string connectionHeader = (proxy_query) ? "Proxy-Connection" : "Connection";
1157 webHeaders.RemoveInternal ((!proxy_query) ? "Proxy-Connection" : "Connection");
1158 Version proto_version = servicePoint.ProtocolVersion;
1159 bool spoint10 = (proto_version == null || proto_version == HttpVersion.Version10);
1161 if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
1162 webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
1163 } else if (!keepAlive && version == HttpVersion.Version11) {
1164 webHeaders.RemoveAndAdd (connectionHeader, "close");
1167 webHeaders.SetInternal ("Host", Host);
1168 if (cookieContainer != null) {
1169 string cookieHeader = cookieContainer.GetCookieHeader (actualUri);
1170 if (cookieHeader != "")
1171 webHeaders.RemoveAndAdd ("Cookie", cookieHeader);
1173 webHeaders.RemoveInternal ("Cookie");
1176 string accept_encoding = null;
1177 if ((auto_decomp & DecompressionMethods.GZip) != 0)
1178 accept_encoding = "gzip";
1179 if ((auto_decomp & DecompressionMethods.Deflate) != 0)
1180 accept_encoding = accept_encoding != null ? "gzip, deflate" : "deflate";
1181 if (accept_encoding != null)
1182 webHeaders.RemoveAndAdd ("Accept-Encoding", accept_encoding);
1184 if (!usedPreAuth && preAuthenticate)
1185 DoPreAuthenticate ();
1187 return webHeaders.ToString ();
1190 void DoPreAuthenticate ()
1192 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1193 ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
1194 Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
1198 webHeaders.RemoveInternal ("Proxy-Authorization");
1199 webHeaders.RemoveInternal ("Authorization");
1200 string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
1201 webHeaders [authHeader] = auth.Message;
1205 internal void SetWriteStreamError (WebExceptionStatus status, Exception exc)
1210 WebAsyncResult r = asyncWrite;
1218 msg = "Error: " + status;
1219 wex = new WebException (msg, status);
1221 msg = String.Format ("Error: {0} ({1})", status, exc.Message);
1222 wex = new WebException (msg, exc, status);
1224 r.SetCompleted (false, wex);
1229 internal void SendRequestHeaders (bool propagate_error)
1231 StringBuilder req = new StringBuilder ();
1234 query = actualUri.PathAndQuery;
1236 query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
1238 actualUri.PathAndQuery);
1241 if (!force_version && servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
1242 actualVersion = servicePoint.ProtocolVersion;
1244 actualVersion = version;
1247 req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
1248 actualVersion.Major, actualVersion.Minor);
1249 req.Append (GetHeaders ());
1250 string reqstr = req.ToString ();
1251 byte [] bytes = Encoding.UTF8.GetBytes (reqstr);
1253 writeStream.SetHeaders (bytes);
1254 } catch (WebException wexc) {
1255 SetWriteStreamError (wexc.Status, wexc);
1256 if (propagate_error)
1258 } catch (Exception exc) {
1259 SetWriteStreamError (WebExceptionStatus.SendFailure, exc);
1260 if (propagate_error)
1265 internal void SetWriteStream (WebConnectionStream stream)
1270 writeStream = stream;
1271 if (bodyBuffer != null) {
1272 webHeaders.RemoveInternal ("Transfer-Encoding");
1273 contentLength = bodyBufferLength;
1274 writeStream.SendChunked = false;
1277 SendRequestHeaders (false);
1281 if (bodyBuffer != null) {
1282 // The body has been written and buffered. The request "user"
1283 // won't write it again, so we must do it.
1284 if (ntlm_auth_state != NtlmAuthState.Challenge) {
1285 writeStream.Write (bodyBuffer, 0, bodyBufferLength);
1287 writeStream.Close ();
1289 } else if (method != "HEAD" && method != "GET" && method != "MKCOL" && method != "CONNECT" &&
1290 method != "TRACE") {
1291 if (getResponseCalled && !writeStream.RequestWritten)
1292 writeStream.WriteRequest ();
1295 if (asyncWrite != null) {
1296 asyncWrite.SetCompleted (false, stream);
1297 asyncWrite.DoCallback ();
1302 internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
1307 string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
1308 WebAsyncResult r = asyncRead;
1313 if (e is WebException) {
1314 wexc = (WebException) e;
1316 wexc = new WebException (msg, e, status, null);
1319 if (!r.IsCompleted) {
1320 r.SetCompleted (false, wexc);
1322 } else if (r == asyncWrite) {
1325 haveResponse = true;
1329 haveResponse = true;
1335 void CheckSendError (WebConnectionData data)
1337 // Got here, but no one called GetResponse
1338 int status = data.StatusCode;
1339 if (status < 400 || status == 401 || status == 407)
1342 if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
1343 // The request has not been completely sent and we got here!
1344 // We should probably just close and cause an error in any case,
1345 saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse);
1346 if (allowBuffering || sendChunked || writeStream.totalWritten >= contentLength) {
1347 webResponse.ReadAll ();
1349 writeStream.IgnoreIOErrors = true;
1354 void HandleNtlmAuth (WebAsyncResult r)
1356 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1358 WebConnection cnc = wce.Connection;
1359 cnc.PriorityRequest = this;
1360 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1361 ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1362 if (creds != null) {
1363 cnc.NtlmCredential = creds.GetCredential (requestUri, "NTLM");
1364 cnc.UnsafeAuthenticatedConnectionSharing = unsafe_auth_blah;
1368 finished_reading = false;
1369 haveResponse = false;
1370 webResponse.ReadAll ();
1374 internal void SetResponseData (WebConnectionData data)
1378 if (data.stream != null)
1379 data.stream.Close ();
1383 WebException wexc = null;
1385 webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
1386 } catch (Exception e) {
1387 wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null);
1388 if (data.stream != null)
1389 data.stream.Close ();
1392 if (wexc == null && (method == "POST" || method == "PUT")) {
1393 CheckSendError (data);
1394 if (saved_exc != null)
1395 wexc = (WebException) saved_exc;
1398 WebAsyncResult r = asyncRead;
1400 bool forced = false;
1401 if (r == null && webResponse != null) {
1402 // This is a forced completion (302, 204)...
1404 r = new WebAsyncResult (null, null);
1405 r.SetCompleted (false, webResponse);
1410 haveResponse = true;
1412 r.SetCompleted (false, wexc);
1419 redirected = CheckFinalStatus (r);
1421 if (ntlm_auth_state != NtlmAuthState.None && authCompleted && webResponse != null
1422 && (int)webResponse.StatusCode < 400) {
1423 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1425 WebConnection cnc = wce.Connection;
1426 cnc.NtlmAuthenticated = true;
1430 // clear internal buffer so that it does not
1431 // hold possible big buffer (bug #397627)
1432 if (writeStream != null)
1433 writeStream.KillBuffer ();
1435 haveResponse = true;
1436 r.SetCompleted (false, webResponse);
1439 if (webResponse != null) {
1440 if (ntlm_auth_state != NtlmAuthState.None) {
1444 webResponse.Close ();
1446 finished_reading = false;
1447 haveResponse = false;
1450 servicePoint = GetServicePoint ();
1451 abortHandler = servicePoint.SendRequest (this, connectionGroup);
1453 } catch (WebException wexc2) {
1456 haveResponse = true;
1458 r.SetCompleted (false, wexc2);
1461 } catch (Exception ex) {
1462 wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
1465 haveResponse = true;
1467 r.SetCompleted (false, wexc);
1475 bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1477 authCompleted = false;
1478 if (code == HttpStatusCode.Unauthorized && credentials == null)
1481 bool isProxy = (code == HttpStatusCode.ProxyAuthenticationRequired);
1482 if (isProxy && (proxy == null || proxy.Credentials == null))
1485 string [] authHeaders = response.Headers.GetValues_internal ( (isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate", false);
1486 if (authHeaders == null || authHeaders.Length == 0)
1489 ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1490 Authorization auth = null;
1491 foreach (string authHeader in authHeaders) {
1492 auth = AuthenticationManager.Authenticate (authHeader, this, creds);
1498 webHeaders [(isProxy) ? "Proxy-Authorization" : "Authorization"] = auth.Message;
1499 authCompleted = auth.Complete;
1500 bool is_ntlm = (auth.Module.AuthenticationType == "NTLM");
1502 ntlm_auth_state = (NtlmAuthState)((int) ntlm_auth_state + 1);
1506 // Returns true if redirected
1507 bool CheckFinalStatus (WebAsyncResult result)
1509 if (result.GotException) {
1511 throw result.Exception;
1514 Exception throwMe = result.Exception;
1516 HttpWebResponse resp = result.Response;
1517 WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
1518 HttpStatusCode code = 0;
1519 if (throwMe == null && webResponse != null) {
1520 code = webResponse.StatusCode;
1521 if (!authCompleted && ((code == HttpStatusCode.Unauthorized && credentials != null) ||
1522 (ProxyQuery && code == HttpStatusCode.ProxyAuthenticationRequired))) {
1523 if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
1524 // Keep the written body, so it can be rewritten in the retry
1525 if (InternalAllowBuffering) {
1526 // NTLM: This is to avoid sending data in the 'challenge' request
1527 // We save it in the first request (first 401), don't send anything
1528 // in the challenge request and send it in the response request along
1529 // with the buffers kept form the first request.
1530 if (ntlm_auth_state != NtlmAuthState.Response) {
1531 bodyBuffer = writeStream.WriteBuffer;
1532 bodyBufferLength = writeStream.WriteBufferLength;
1535 } else if (method != "PUT" && method != "POST") {
1543 writeStream.InternalClose ();
1545 webResponse.Close ();
1549 throw new WebException ("This request requires buffering " +
1550 "of data for authentication or " +
1551 "redirection to be sucessful.");
1556 if ((int) code >= 400) {
1557 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1558 (int) code, webResponse.StatusDescription);
1559 throwMe = new WebException (err, null, protoError, webResponse);
1560 webResponse.ReadAll ();
1561 } else if ((int) code == 304 && allowAutoRedirect) {
1562 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1563 (int) code, webResponse.StatusDescription);
1564 throwMe = new WebException (err, null, protoError, webResponse);
1565 } else if ((int) code >= 300 && allowAutoRedirect && redirects >= maxAutoRedirect) {
1566 throwMe = new WebException ("Max. redirections exceeded.", null,
1567 protoError, webResponse);
1568 webResponse.ReadAll ();
1573 if (throwMe == null) {
1576 if (allowAutoRedirect && c >= 300) {
1577 if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
1578 bodyBuffer = writeStream.WriteBuffer;
1579 bodyBufferLength = writeStream.WriteBufferLength;
1581 b = Redirect (result, code);
1582 if (b && ntlm_auth_state != 0)
1583 ntlm_auth_state = 0;
1586 if (resp != null && c >= 300 && c != 304)
1595 if (writeStream != null) {
1596 writeStream.InternalClose ();