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 ('/');
425 if (IPAddress.TryParse (val, out ipaddr))
428 string u = scheme + "://" + val + "/";
429 return Uri.IsWellFormedUriString (u, UriKind.Absolute);
432 public DateTime IfModifiedSince {
434 string str = webHeaders ["If-Modified-Since"];
438 return MonoHttpDate.Parse (str);
439 } catch (Exception) {
444 CheckRequestStarted ();
446 webHeaders.SetInternal ("If-Modified-Since",
447 value.ToUniversalTime ().ToString ("r", null));
448 // TODO: check last param when using different locale
452 public bool KeepAlive {
461 public int MaximumAutomaticRedirections {
462 get { return maxAutoRedirect; }
465 throw new ArgumentException ("Must be > 0", "value");
467 maxAutoRedirect = value;
471 [MonoTODO ("Use this")]
472 public int MaximumResponseHeadersLength {
473 get { return maxResponseHeadersLength; }
474 set { maxResponseHeadersLength = value; }
477 [MonoTODO ("Use this")]
478 public static int DefaultMaximumResponseHeadersLength {
479 get { return defaultMaxResponseHeadersLength; }
480 set { defaultMaxResponseHeadersLength = value; }
483 public int ReadWriteTimeout {
484 get { return readWriteTimeout; }
487 throw new InvalidOperationException ("The request has already been sent.");
490 throw new ArgumentOutOfRangeException ("value", "Must be >= -1");
492 readWriteTimeout = value;
498 public int ContinueTimeout {
499 get { throw new NotImplementedException (); }
500 set { throw new NotImplementedException (); }
504 public string MediaType {
505 get { return mediaType; }
511 public override string Method {
512 get { return this.method; }
514 if (value == null || value.Trim () == "")
515 throw new ArgumentException ("not a valid method");
517 method = value.ToUpperInvariant ();
518 if (method != "HEAD" && method != "GET" && method != "POST" && method != "PUT" &&
519 method != "DELETE" && method != "CONNECT" && method != "TRACE" &&
526 public bool Pipelined {
527 get { return pipelined; }
528 set { pipelined = value; }
531 public override bool PreAuthenticate {
532 get { return preAuthenticate; }
533 set { preAuthenticate = value; }
536 public Version ProtocolVersion {
537 get { return version; }
539 if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
540 throw new ArgumentException ("value");
542 force_version = true;
547 public override IWebProxy Proxy {
548 get { return proxy; }
550 CheckRequestStarted ();
552 servicePoint = null; // we may need a new one
556 public string Referer {
557 get { return webHeaders ["Referer"]; }
559 CheckRequestStarted ();
560 if (value == null || value.Trim().Length == 0) {
561 webHeaders.RemoveInternal ("Referer");
564 webHeaders.SetInternal ("Referer", value);
568 public override Uri RequestUri {
569 get { return requestUri; }
572 public bool SendChunked {
573 get { return sendChunked; }
575 CheckRequestStarted ();
580 public ServicePoint ServicePoint {
581 get { return GetServicePoint (); }
584 internal ServicePoint ServicePointNoLock {
585 get { return servicePoint; }
588 [MonoTODO ("for portable library support")]
589 public virtual bool SupportsCookieContainer {
591 throw new NotImplementedException ();
595 public override int Timeout {
596 get { return timeout; }
599 throw new ArgumentOutOfRangeException ("value");
605 public string TransferEncoding {
606 get { return webHeaders ["Transfer-Encoding"]; }
608 CheckRequestStarted ();
611 val = val.Trim ().ToLower ();
613 if (val == null || val.Length == 0) {
614 webHeaders.RemoveInternal ("Transfer-Encoding");
618 if (val == "chunked")
619 throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
622 throw new ArgumentException ("SendChunked must be True", "value");
624 webHeaders.RemoveAndAdd ("Transfer-Encoding", value);
628 public override bool UseDefaultCredentials
630 get { return CredentialCache.DefaultCredentials == Credentials; }
631 set { Credentials = value ? CredentialCache.DefaultCredentials : null; }
634 public string UserAgent {
635 get { return webHeaders ["User-Agent"]; }
636 set { webHeaders.SetInternal ("User-Agent", value); }
639 bool unsafe_auth_blah;
640 public bool UnsafeAuthenticatedConnectionSharing
642 get { return unsafe_auth_blah; }
643 set { unsafe_auth_blah = value; }
646 internal bool GotRequestStream {
647 get { return gotRequestStream; }
650 internal bool ExpectContinue {
651 get { return expectContinue; }
652 set { expectContinue = value; }
655 internal Uri AuthUri {
656 get { return actualUri; }
659 internal bool ProxyQuery {
660 get { return servicePoint.UsesProxy && !servicePoint.UseConnect; }
665 internal ServicePoint GetServicePoint ()
668 if (hostChanged || servicePoint == null) {
669 servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
677 public void AddRange (int range)
679 AddRange ("bytes", (long) range);
682 public void AddRange (int from, int to)
684 AddRange ("bytes", (long) from, (long) to);
687 public void AddRange (string rangeSpecifier, int range)
689 AddRange (rangeSpecifier, (long) range);
692 public void AddRange (string rangeSpecifier, int from, int to)
694 AddRange (rangeSpecifier, (long) from, (long) to);
701 void AddRange (long range)
703 AddRange ("bytes", (long) range);
711 void AddRange (long from, long to)
713 AddRange ("bytes", from, to);
721 void AddRange (string rangeSpecifier, long range)
723 if (rangeSpecifier == null)
724 throw new ArgumentNullException ("rangeSpecifier");
725 if (!WebHeaderCollection.IsHeaderValue (rangeSpecifier))
726 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
728 string r = webHeaders ["Range"];
730 r = rangeSpecifier + "=";
732 string old_specifier = r.Substring (0, r.IndexOf ('='));
733 if (String.Compare (old_specifier, rangeSpecifier, StringComparison.OrdinalIgnoreCase) != 0)
734 throw new InvalidOperationException ("A different range specifier is already in use");
738 string n = range.ToString (CultureInfo.InvariantCulture);
743 webHeaders.RemoveAndAdd ("Range", r);
751 void AddRange (string rangeSpecifier, long from, long to)
753 if (rangeSpecifier == null)
754 throw new ArgumentNullException ("rangeSpecifier");
755 if (!WebHeaderCollection.IsHeaderValue (rangeSpecifier))
756 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
757 if (from > to || from < 0)
758 throw new ArgumentOutOfRangeException ("from");
760 throw new ArgumentOutOfRangeException ("to");
762 string r = webHeaders ["Range"];
764 r = rangeSpecifier + "=";
768 r = String.Format ("{0}{1}-{2}", r, from, to);
769 webHeaders.RemoveAndAdd ("Range", r);
773 public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
776 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
778 bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
780 if (method == null || !send)
781 throw new ProtocolViolationException ("Cannot send data when method is: " + method);
783 if (contentLength == -1 && !sendChunked && !allowBuffering && KeepAlive)
784 throw new ProtocolViolationException ("Content-Length not set");
786 string transferEncoding = TransferEncoding;
787 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
788 throw new ProtocolViolationException ("SendChunked should be true.");
792 if (getResponseCalled)
793 throw new InvalidOperationException ("The operation cannot be performed once the request has been submitted.");
795 if (asyncWrite != null) {
796 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
797 "method while a previous call is still in progress.");
800 asyncWrite = new WebAsyncResult (this, callback, state);
801 initialMethod = method;
803 if (writeStream != null) {
804 asyncWrite.SetCompleted (true, writeStream);
805 asyncWrite.DoCallback ();
810 gotRequestStream = true;
811 WebAsyncResult result = asyncWrite;
815 servicePoint = GetServicePoint ();
816 abortHandler = servicePoint.SendRequest (this, connectionGroup);
822 public override Stream EndGetRequestStream (IAsyncResult asyncResult)
824 if (asyncResult == null)
825 throw new ArgumentNullException ("asyncResult");
827 WebAsyncResult result = asyncResult as WebAsyncResult;
829 throw new ArgumentException ("Invalid IAsyncResult");
832 result.WaitUntilComplete ();
834 Exception e = result.Exception;
838 return result.WriteStream;
841 public override Stream GetRequestStream()
843 IAsyncResult asyncResult = asyncWrite;
844 if (asyncResult == null) {
845 asyncResult = BeginGetRequestStream (null, null);
846 asyncWrite = (WebAsyncResult) asyncResult;
849 if (!asyncResult.IsCompleted && !asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
851 throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
854 return EndGetRequestStream (asyncResult);
857 void CheckIfForceWrite ()
859 if (writeStream == null || writeStream.RequestWritten || !InternalAllowBuffering)
862 if (contentLength < 0 && writeStream.CanWrite == true && writeStream.WriteBufferLength < 0)
865 if (contentLength < 0 && writeStream.WriteBufferLength >= 0)
866 InternalContentLength = writeStream.WriteBufferLength;
868 if (contentLength < 0 && writeStream.CanWrite == true)
872 // This will write the POST/PUT if the write stream already has the expected
873 // amount of bytes in it (ContentLength) (bug #77753) or if the write stream
874 // contains data and it has been closed already (xamarin bug #1512).
876 if (writeStream.WriteBufferLength == contentLength || (contentLength == -1 && writeStream.CanWrite == false))
877 writeStream.WriteRequest ();
880 public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
883 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
886 throw new ProtocolViolationException ("Method is null.");
888 string transferEncoding = TransferEncoding;
889 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
890 throw new ProtocolViolationException ("SendChunked should be true.");
892 Monitor.Enter (locker);
893 getResponseCalled = true;
894 if (asyncRead != null && !haveResponse) {
895 Monitor.Exit (locker);
896 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
897 "method while a previous call is still in progress.");
900 CheckIfForceWrite ();
901 asyncRead = new WebAsyncResult (this, callback, state);
902 WebAsyncResult aread = asyncRead;
903 initialMethod = method;
905 Exception saved = saved_exc;
906 if (webResponse != null) {
907 Monitor.Exit (locker);
909 aread.SetCompleted (true, webResponse);
911 aread.SetCompleted (true, saved);
915 } else if (saved != null) {
916 Monitor.Exit (locker);
917 aread.SetCompleted (true, saved);
926 servicePoint = GetServicePoint ();
927 abortHandler = servicePoint.SendRequest (this, connectionGroup);
930 Monitor.Exit (locker);
934 public override WebResponse EndGetResponse (IAsyncResult asyncResult)
936 if (asyncResult == null)
937 throw new ArgumentNullException ("asyncResult");
939 WebAsyncResult result = asyncResult as WebAsyncResult;
941 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
943 if (!result.WaitUntilComplete (timeout, false)) {
945 throw new WebException("The request timed out", WebExceptionStatus.Timeout);
948 if (result.GotException)
949 throw result.Exception;
951 return result.Response;
954 public override WebResponse GetResponse()
956 WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
957 return EndGetResponse (result);
960 internal bool FinishedReading {
961 get { return finished_reading; }
962 set { finished_reading = value; }
965 internal bool Aborted {
966 get { return Interlocked.CompareExchange (ref aborted, 0, 0) == 1; }
969 public override void Abort ()
971 if (Interlocked.CompareExchange (ref aborted, 1, 0) == 1)
974 if (haveResponse && finished_reading)
978 if (abortHandler != null) {
980 abortHandler (this, EventArgs.Empty);
981 } catch (Exception) {}
985 if (asyncWrite != null) {
986 WebAsyncResult r = asyncWrite;
987 if (!r.IsCompleted) {
989 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
990 r.SetCompleted (false, wexc);
997 if (asyncRead != null) {
998 WebAsyncResult r = asyncRead;
999 if (!r.IsCompleted) {
1001 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
1002 r.SetCompleted (false, wexc);
1009 if (writeStream != null) {
1011 writeStream.Close ();
1016 if (webResponse != null) {
1018 webResponse.Close ();
1024 void ISerializable.GetObjectData (SerializationInfo serializationInfo,
1025 StreamingContext streamingContext)
1027 GetObjectData (serializationInfo, streamingContext);
1030 protected override void GetObjectData (SerializationInfo serializationInfo,
1031 StreamingContext streamingContext)
1033 SerializationInfo info = serializationInfo;
1035 info.AddValue ("requestUri", requestUri, typeof (Uri));
1036 info.AddValue ("actualUri", actualUri, typeof (Uri));
1037 info.AddValue ("allowAutoRedirect", allowAutoRedirect);
1038 info.AddValue ("allowBuffering", allowBuffering);
1039 info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
1040 info.AddValue ("connectionGroup", connectionGroup);
1041 info.AddValue ("contentLength", contentLength);
1042 info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
1043 info.AddValue ("keepAlive", keepAlive);
1044 info.AddValue ("maxAutoRedirect", maxAutoRedirect);
1045 info.AddValue ("mediaType", mediaType);
1046 info.AddValue ("method", method);
1047 info.AddValue ("initialMethod", initialMethod);
1048 info.AddValue ("pipelined", pipelined);
1049 info.AddValue ("version", version, typeof (Version));
1050 info.AddValue ("proxy", proxy, typeof (IWebProxy));
1051 info.AddValue ("sendChunked", sendChunked);
1052 info.AddValue ("timeout", timeout);
1053 info.AddValue ("redirects", redirects);
1054 info.AddValue ("host", host);
1057 void CheckRequestStarted ()
1060 throw new InvalidOperationException ("request started");
1063 internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
1065 if (continueDelegate != null)
1066 continueDelegate (statusCode, headers);
1069 bool Redirect (WebAsyncResult result, HttpStatusCode code)
1073 string uriString = null;
1076 case HttpStatusCode.Ambiguous: // 300
1077 e = new WebException ("Ambiguous redirect.");
1079 case HttpStatusCode.MovedPermanently: // 301
1080 case HttpStatusCode.Redirect: // 302
1081 case HttpStatusCode.TemporaryRedirect: // 307
1082 /* MS follows the redirect for POST too
1083 if (method != "GET" && method != "HEAD") // 10.3
1088 bodyBufferLength = 0;
1090 if (code != HttpStatusCode.TemporaryRedirect)
1092 uriString = webResponse.Headers ["Location"];
1094 case HttpStatusCode.SeeOther: //303
1096 uriString = webResponse.Headers ["Location"];
1098 case HttpStatusCode.NotModified: // 304
1100 case HttpStatusCode.UseProxy: // 305
1101 e = new NotImplementedException ("Proxy support not available.");
1103 case HttpStatusCode.Unused: // 306
1105 e = new ProtocolViolationException ("Invalid status code: " + (int) code);
1112 if (uriString == null)
1113 throw new WebException ("No Location header found for " + (int) code,
1114 WebExceptionStatus.ProtocolError);
1116 Uri prev = actualUri;
1118 actualUri = new Uri (actualUri, uriString);
1119 } catch (Exception) {
1120 throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
1121 uriString, (int) code),
1122 WebExceptionStatus.ProtocolError);
1125 hostChanged = (actualUri.Scheme != prev.Scheme || Host != prev.Authority);
1129 string GetHeaders ()
1131 bool continue100 = false;
1134 webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
1135 webHeaders.RemoveInternal ("Content-Length");
1136 } else if (contentLength != -1) {
1137 if (ntlm_auth_state != NtlmAuthState.Challenge) {
1138 if (contentLength > 0)
1141 webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
1143 webHeaders.SetInternal ("Content-Length", "0");
1145 webHeaders.RemoveInternal ("Transfer-Encoding");
1147 webHeaders.RemoveInternal ("Content-Length");
1150 if (actualVersion == HttpVersion.Version11 && continue100 &&
1151 servicePoint.SendContinue) { // RFC2616 8.2.3
1152 webHeaders.RemoveAndAdd ("Expect" , "100-continue");
1153 expectContinue = true;
1155 webHeaders.RemoveInternal ("Expect");
1156 expectContinue = false;
1159 bool proxy_query = ProxyQuery;
1160 string connectionHeader = (proxy_query) ? "Proxy-Connection" : "Connection";
1161 webHeaders.RemoveInternal ((!proxy_query) ? "Proxy-Connection" : "Connection");
1162 Version proto_version = servicePoint.ProtocolVersion;
1163 bool spoint10 = (proto_version == null || proto_version == HttpVersion.Version10);
1165 if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
1166 if (webHeaders[connectionHeader] == null
1167 || webHeaders[connectionHeader].IndexOf ("keep-alive", StringComparison.OrdinalIgnoreCase) == -1)
1168 webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
1169 } else if (!keepAlive && version == HttpVersion.Version11) {
1170 webHeaders.RemoveAndAdd (connectionHeader, "close");
1173 webHeaders.SetInternal ("Host", Host);
1174 if (cookieContainer != null) {
1175 string cookieHeader = cookieContainer.GetCookieHeader (actualUri);
1176 if (cookieHeader != "")
1177 webHeaders.RemoveAndAdd ("Cookie", cookieHeader);
1179 webHeaders.RemoveInternal ("Cookie");
1182 string accept_encoding = null;
1183 if ((auto_decomp & DecompressionMethods.GZip) != 0)
1184 accept_encoding = "gzip";
1185 if ((auto_decomp & DecompressionMethods.Deflate) != 0)
1186 accept_encoding = accept_encoding != null ? "gzip, deflate" : "deflate";
1187 if (accept_encoding != null)
1188 webHeaders.RemoveAndAdd ("Accept-Encoding", accept_encoding);
1190 if (!usedPreAuth && preAuthenticate)
1191 DoPreAuthenticate ();
1193 return webHeaders.ToString ();
1196 void DoPreAuthenticate ()
1198 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1199 ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
1200 Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
1204 webHeaders.RemoveInternal ("Proxy-Authorization");
1205 webHeaders.RemoveInternal ("Authorization");
1206 string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
1207 webHeaders [authHeader] = auth.Message;
1211 internal void SetWriteStreamError (WebExceptionStatus status, Exception exc)
1216 WebAsyncResult r = asyncWrite;
1224 msg = "Error: " + status;
1225 wex = new WebException (msg, status);
1227 msg = String.Format ("Error: {0} ({1})", status, exc.Message);
1228 wex = new WebException (msg, exc, status);
1230 r.SetCompleted (false, wex);
1235 internal void SendRequestHeaders (bool propagate_error)
1237 StringBuilder req = new StringBuilder ();
1240 query = actualUri.PathAndQuery;
1242 query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
1244 actualUri.PathAndQuery);
1247 if (!force_version && servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
1248 actualVersion = servicePoint.ProtocolVersion;
1250 actualVersion = version;
1253 req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
1254 actualVersion.Major, actualVersion.Minor);
1255 req.Append (GetHeaders ());
1256 string reqstr = req.ToString ();
1257 byte [] bytes = Encoding.UTF8.GetBytes (reqstr);
1259 writeStream.SetHeaders (bytes);
1260 } catch (WebException wexc) {
1261 SetWriteStreamError (wexc.Status, wexc);
1262 if (propagate_error)
1264 } catch (Exception exc) {
1265 SetWriteStreamError (WebExceptionStatus.SendFailure, exc);
1266 if (propagate_error)
1271 internal void SetWriteStream (WebConnectionStream stream)
1276 writeStream = stream;
1277 if (bodyBuffer != null) {
1278 webHeaders.RemoveInternal ("Transfer-Encoding");
1279 contentLength = bodyBufferLength;
1280 writeStream.SendChunked = false;
1283 SendRequestHeaders (false);
1287 if (bodyBuffer != null) {
1288 // The body has been written and buffered. The request "user"
1289 // won't write it again, so we must do it.
1290 if (ntlm_auth_state != NtlmAuthState.Challenge) {
1291 writeStream.Write (bodyBuffer, 0, bodyBufferLength);
1293 writeStream.Close ();
1295 } else if (method != "HEAD" && method != "GET" && method != "MKCOL" && method != "CONNECT" &&
1296 method != "TRACE") {
1297 if (getResponseCalled && !writeStream.RequestWritten)
1298 writeStream.WriteRequest ();
1301 if (asyncWrite != null) {
1302 asyncWrite.SetCompleted (false, stream);
1303 asyncWrite.DoCallback ();
1308 internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
1313 string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
1314 WebAsyncResult r = asyncRead;
1319 if (e is WebException) {
1320 wexc = (WebException) e;
1322 wexc = new WebException (msg, e, status, null);
1325 if (!r.IsCompleted) {
1326 r.SetCompleted (false, wexc);
1328 } else if (r == asyncWrite) {
1331 haveResponse = true;
1335 haveResponse = true;
1341 void CheckSendError (WebConnectionData data)
1343 // Got here, but no one called GetResponse
1344 int status = data.StatusCode;
1345 if (status < 400 || status == 401 || status == 407)
1348 if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
1349 // The request has not been completely sent and we got here!
1350 // We should probably just close and cause an error in any case,
1351 saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse);
1352 if (allowBuffering || sendChunked || writeStream.totalWritten >= contentLength) {
1353 webResponse.ReadAll ();
1355 writeStream.IgnoreIOErrors = true;
1360 void HandleNtlmAuth (WebAsyncResult r)
1362 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1364 WebConnection cnc = wce.Connection;
1365 cnc.PriorityRequest = this;
1366 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1367 ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1368 if (creds != null) {
1369 cnc.NtlmCredential = creds.GetCredential (requestUri, "NTLM");
1370 cnc.UnsafeAuthenticatedConnectionSharing = unsafe_auth_blah;
1374 finished_reading = false;
1375 haveResponse = false;
1376 webResponse.ReadAll ();
1380 internal void SetResponseData (WebConnectionData data)
1384 if (data.stream != null)
1385 data.stream.Close ();
1389 WebException wexc = null;
1391 webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
1392 } catch (Exception e) {
1393 wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null);
1394 if (data.stream != null)
1395 data.stream.Close ();
1398 if (wexc == null && (method == "POST" || method == "PUT")) {
1399 CheckSendError (data);
1400 if (saved_exc != null)
1401 wexc = (WebException) saved_exc;
1404 WebAsyncResult r = asyncRead;
1406 bool forced = false;
1407 if (r == null && webResponse != null) {
1408 // This is a forced completion (302, 204)...
1410 r = new WebAsyncResult (null, null);
1411 r.SetCompleted (false, webResponse);
1416 haveResponse = true;
1418 r.SetCompleted (false, wexc);
1425 redirected = CheckFinalStatus (r);
1427 if (ntlm_auth_state != NtlmAuthState.None && authCompleted && webResponse != null
1428 && (int)webResponse.StatusCode < 400) {
1429 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1431 WebConnection cnc = wce.Connection;
1432 cnc.NtlmAuthenticated = true;
1436 // clear internal buffer so that it does not
1437 // hold possible big buffer (bug #397627)
1438 if (writeStream != null)
1439 writeStream.KillBuffer ();
1441 haveResponse = true;
1442 r.SetCompleted (false, webResponse);
1445 if (webResponse != null) {
1446 if (ntlm_auth_state != NtlmAuthState.None) {
1450 webResponse.Close ();
1452 finished_reading = false;
1453 haveResponse = false;
1456 servicePoint = GetServicePoint ();
1457 abortHandler = servicePoint.SendRequest (this, connectionGroup);
1459 } catch (WebException wexc2) {
1462 haveResponse = true;
1464 r.SetCompleted (false, wexc2);
1467 } catch (Exception ex) {
1468 wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
1471 haveResponse = true;
1473 r.SetCompleted (false, wexc);
1481 bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1483 authCompleted = false;
1484 if (code == HttpStatusCode.Unauthorized && credentials == null)
1487 bool isProxy = (code == HttpStatusCode.ProxyAuthenticationRequired);
1488 if (isProxy && (proxy == null || proxy.Credentials == null))
1491 string [] authHeaders = response.Headers.GetValues_internal ( (isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate", false);
1492 if (authHeaders == null || authHeaders.Length == 0)
1495 ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1496 Authorization auth = null;
1497 foreach (string authHeader in authHeaders) {
1498 auth = AuthenticationManager.Authenticate (authHeader, this, creds);
1504 webHeaders [(isProxy) ? "Proxy-Authorization" : "Authorization"] = auth.Message;
1505 authCompleted = auth.Complete;
1506 bool is_ntlm = (auth.Module.AuthenticationType == "NTLM");
1508 ntlm_auth_state = (NtlmAuthState)((int) ntlm_auth_state + 1);
1512 // Returns true if redirected
1513 bool CheckFinalStatus (WebAsyncResult result)
1515 if (result.GotException) {
1517 throw result.Exception;
1520 Exception throwMe = result.Exception;
1522 HttpWebResponse resp = result.Response;
1523 WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
1524 HttpStatusCode code = 0;
1525 if (throwMe == null && webResponse != null) {
1526 code = webResponse.StatusCode;
1527 if (!authCompleted && ((code == HttpStatusCode.Unauthorized && credentials != null) ||
1528 (ProxyQuery && code == HttpStatusCode.ProxyAuthenticationRequired))) {
1529 if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
1530 // Keep the written body, so it can be rewritten in the retry
1531 if (InternalAllowBuffering) {
1532 // NTLM: This is to avoid sending data in the 'challenge' request
1533 // We save it in the first request (first 401), don't send anything
1534 // in the challenge request and send it in the response request along
1535 // with the buffers kept form the first request.
1536 if (ntlm_auth_state != NtlmAuthState.Response) {
1537 bodyBuffer = writeStream.WriteBuffer;
1538 bodyBufferLength = writeStream.WriteBufferLength;
1541 } else if (method != "PUT" && method != "POST") {
1549 writeStream.InternalClose ();
1551 webResponse.Close ();
1555 throw new WebException ("This request requires buffering " +
1556 "of data for authentication or " +
1557 "redirection to be sucessful.");
1562 if ((int) code >= 400) {
1563 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1564 (int) code, webResponse.StatusDescription);
1565 throwMe = new WebException (err, null, protoError, webResponse);
1566 webResponse.ReadAll ();
1567 } else if ((int) code == 304 && allowAutoRedirect) {
1568 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1569 (int) code, webResponse.StatusDescription);
1570 throwMe = new WebException (err, null, protoError, webResponse);
1571 } else if ((int) code >= 300 && allowAutoRedirect && redirects >= maxAutoRedirect) {
1572 throwMe = new WebException ("Max. redirections exceeded.", null,
1573 protoError, webResponse);
1574 webResponse.ReadAll ();
1579 if (throwMe == null) {
1582 if (allowAutoRedirect && c >= 300) {
1583 if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
1584 bodyBuffer = writeStream.WriteBuffer;
1585 bodyBufferLength = writeStream.WriteBufferLength;
1587 b = Redirect (result, code);
1588 if (b && ntlm_auth_state != 0)
1589 ntlm_auth_state = 0;
1592 if (resp != null && c >= 300 && c != 304)
1601 if (writeStream != null) {
1602 writeStream.InternalClose ();
1611 internal bool ReuseConnection {
1616 internal WebConnection StoredConnection;