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 internal class HttpWebRequest : WebRequest, ISerializable {
53 public class HttpWebRequest : WebRequest, ISerializable {
58 bool allowAutoRedirect = true;
59 bool allowBuffering = true;
60 X509CertificateCollection certificates;
61 string connectionGroup;
62 long contentLength = -1;
63 HttpContinueDelegate continueDelegate;
64 CookieContainer cookieContainer;
65 ICredentials credentials;
69 WebHeaderCollection webHeaders = new WebHeaderCollection (true);
70 bool keepAlive = true;
71 int maxAutoRedirect = 50;
72 string mediaType = String.Empty;
73 string method = "GET";
74 string initialMethod = "GET";
75 bool pipelined = true;
78 Version version = HttpVersion.Version11;
80 Version actualVersion;
83 ServicePoint servicePoint;
86 WebConnectionStream writeStream;
87 HttpWebResponse webResponse;
88 WebAsyncResult asyncWrite;
89 WebAsyncResult asyncRead;
90 EventHandler abortHandler;
92 bool gotRequestStream;
98 bool getResponseCalled;
100 object locker = new object ();
101 bool finished_reading;
102 internal WebConnection WebConnection;
103 DecompressionMethods auto_decomp;
104 int maxResponseHeadersLength;
105 static int defaultMaxResponseHeadersLength;
106 int readWriteTimeout = 300000; // ms
113 NtlmAuthState ntlm_auth_state;
117 static HttpWebRequest ()
119 defaultMaxResponseHeadersLength = 64 * 1024;
121 NetConfig config = ConfigurationSettings.GetConfig ("system.net/settings") as NetConfig;
122 if (config != null) {
123 int x = config.MaxResponseHeadersLength;
127 defaultMaxResponseHeadersLength = x;
137 HttpWebRequest (Uri uri)
139 this.requestUri = uri;
140 this.actualUri = uri;
141 this.proxy = GlobalProxySelection.Select;
144 [Obsolete ("Serialization is obsoleted for this type", false)]
145 protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
147 SerializationInfo info = serializationInfo;
149 requestUri = (Uri) info.GetValue ("requestUri", typeof (Uri));
150 actualUri = (Uri) info.GetValue ("actualUri", typeof (Uri));
151 allowAutoRedirect = info.GetBoolean ("allowAutoRedirect");
152 allowBuffering = info.GetBoolean ("allowBuffering");
153 certificates = (X509CertificateCollection) info.GetValue ("certificates", typeof (X509CertificateCollection));
154 connectionGroup = info.GetString ("connectionGroup");
155 contentLength = info.GetInt64 ("contentLength");
156 webHeaders = (WebHeaderCollection) info.GetValue ("webHeaders", typeof (WebHeaderCollection));
157 keepAlive = info.GetBoolean ("keepAlive");
158 maxAutoRedirect = info.GetInt32 ("maxAutoRedirect");
159 mediaType = info.GetString ("mediaType");
160 method = info.GetString ("method");
161 initialMethod = info.GetString ("initialMethod");
162 pipelined = info.GetBoolean ("pipelined");
163 version = (Version) info.GetValue ("version", typeof (Version));
164 proxy = (IWebProxy) info.GetValue ("proxy", typeof (IWebProxy));
165 sendChunked = info.GetBoolean ("sendChunked");
166 timeout = info.GetInt32 ("timeout");
167 redirects = info.GetInt32 ("redirects");
168 host = info.GetString ("host");
173 public string Accept {
174 get { return webHeaders ["Accept"]; }
176 CheckRequestStarted ();
177 webHeaders.RemoveAndAdd ("Accept", value);
182 get { return actualUri; }
183 internal set { actualUri = value; } // Used by Ftp+proxy
186 public bool AllowAutoRedirect {
187 get { return allowAutoRedirect; }
188 set { this.allowAutoRedirect = value; }
191 public bool AllowWriteStreamBuffering {
192 get { return allowBuffering; }
193 set { allowBuffering = value; }
196 static Exception GetMustImplement ()
198 return new NotImplementedException ();
201 public DecompressionMethods AutomaticDecompression
207 CheckRequestStarted ();
212 internal bool InternalAllowBuffering {
214 return (allowBuffering && (method != "HEAD" && method != "GET" &&
215 method != "MKCOL" && method != "CONNECT" &&
220 public X509CertificateCollection ClientCertificates {
222 if (certificates == null)
223 certificates = new X509CertificateCollection ();
229 throw GetMustImplement ();
233 public string Connection {
234 get { return webHeaders ["Connection"]; }
236 CheckRequestStarted ();
238 if (string.IsNullOrEmpty (value)) {
239 webHeaders.RemoveInternal ("Connection");
243 string val = value.ToLowerInvariant ();
244 if (val.Contains ("keep-alive") || val.Contains ("close"))
245 throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
248 value = value + ", Keep-Alive";
250 webHeaders.RemoveAndAdd ("Connection", value);
254 public override string ConnectionGroupName {
255 get { return connectionGroup; }
256 set { connectionGroup = value; }
259 public override long ContentLength {
260 get { return contentLength; }
262 CheckRequestStarted ();
264 throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
266 contentLength = value;
270 internal long InternalContentLength {
271 set { contentLength = value; }
274 public override string ContentType {
275 get { return webHeaders ["Content-Type"]; }
277 if (value == null || value.Trim().Length == 0) {
278 webHeaders.RemoveInternal ("Content-Type");
281 webHeaders.RemoveAndAdd ("Content-Type", value);
285 public HttpContinueDelegate ContinueDelegate {
286 get { return continueDelegate; }
287 set { continueDelegate = value; }
290 public CookieContainer CookieContainer {
291 get { return cookieContainer; }
292 set { cookieContainer = value; }
295 public override ICredentials Credentials {
296 get { return credentials; }
297 set { credentials = value; }
300 public DateTime Date {
302 string date = webHeaders ["Date"];
304 return DateTime.MinValue;
305 return DateTime.ParseExact (date, "r", CultureInfo.InvariantCulture).ToLocalTime ();
309 webHeaders.RemoveInternal ("Date");
311 webHeaders.RemoveAndAdd ("Date", value.ToUniversalTime ().ToString ("r", CultureInfo.InvariantCulture));
317 public static new RequestCachePolicy DefaultCachePolicy
320 throw GetMustImplement ();
323 throw GetMustImplement ();
328 public static int DefaultMaximumErrorResponseLength
331 throw GetMustImplement ();
334 throw GetMustImplement ();
338 public string Expect {
339 get { return webHeaders ["Expect"]; }
341 CheckRequestStarted ();
344 val = val.Trim ().ToLower ();
346 if (val == null || val.Length == 0) {
347 webHeaders.RemoveInternal ("Expect");
351 if (val == "100-continue")
352 throw new ArgumentException ("100-Continue cannot be set with this property.",
354 webHeaders.RemoveAndAdd ("Expect", value);
358 public bool HaveResponse {
359 get { return haveResponse; }
362 public override WebHeaderCollection Headers {
363 get { return webHeaders; }
365 CheckRequestStarted ();
366 WebHeaderCollection newHeaders = new WebHeaderCollection (true);
367 int count = value.Count;
368 for (int i = 0; i < count; i++)
369 newHeaders.Add (value.GetKey (i), value.Get (i));
371 webHeaders = newHeaders;
382 return actualUri.Authority;
387 throw new ArgumentNullException ("value");
389 if (!CheckValidHost (actualUri.Scheme, value))
390 throw new ArgumentException ("Invalid host: " + value);
396 static bool CheckValidHost (string scheme, string val)
399 throw new ArgumentNullException ("value");
407 int idx = val.IndexOf ('/');
411 string u = scheme + "://" + val + "/";
412 return Uri.IsWellFormedUriString (u, UriKind.Absolute);
415 public DateTime IfModifiedSince {
417 string str = webHeaders ["If-Modified-Since"];
421 return MonoHttpDate.Parse (str);
422 } catch (Exception) {
427 CheckRequestStarted ();
429 webHeaders.SetInternal ("If-Modified-Since",
430 value.ToUniversalTime ().ToString ("r", null));
431 // TODO: check last param when using different locale
435 public bool KeepAlive {
444 public int MaximumAutomaticRedirections {
445 get { return maxAutoRedirect; }
448 throw new ArgumentException ("Must be > 0", "value");
450 maxAutoRedirect = value;
454 [MonoTODO ("Use this")]
455 public int MaximumResponseHeadersLength {
456 get { return maxResponseHeadersLength; }
457 set { maxResponseHeadersLength = value; }
460 [MonoTODO ("Use this")]
461 public static int DefaultMaximumResponseHeadersLength {
462 get { return defaultMaxResponseHeadersLength; }
463 set { defaultMaxResponseHeadersLength = value; }
466 public int ReadWriteTimeout {
467 get { return readWriteTimeout; }
470 throw new InvalidOperationException ("The request has already been sent.");
473 throw new ArgumentOutOfRangeException ("value", "Must be >= -1");
475 readWriteTimeout = value;
479 public string MediaType {
480 get { return mediaType; }
486 public override string Method {
487 get { return this.method; }
489 if (value == null || value.Trim () == "")
490 throw new ArgumentException ("not a valid method");
492 method = value.ToUpperInvariant ();
493 if (method != "HEAD" && method != "GET" && method != "POST" && method != "PUT" &&
494 method != "DELETE" && method != "CONNECT" && method != "TRACE" &&
501 public bool Pipelined {
502 get { return pipelined; }
503 set { pipelined = value; }
506 public override bool PreAuthenticate {
507 get { return preAuthenticate; }
508 set { preAuthenticate = value; }
511 public Version ProtocolVersion {
512 get { return version; }
514 if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
515 throw new ArgumentException ("value");
517 force_version = true;
522 public override IWebProxy Proxy {
523 get { return proxy; }
525 CheckRequestStarted ();
527 servicePoint = null; // we may need a new one
531 public string Referer {
532 get { return webHeaders ["Referer"]; }
534 CheckRequestStarted ();
535 if (value == null || value.Trim().Length == 0) {
536 webHeaders.RemoveInternal ("Referer");
539 webHeaders.SetInternal ("Referer", value);
543 public override Uri RequestUri {
544 get { return requestUri; }
547 public bool SendChunked {
548 get { return sendChunked; }
550 CheckRequestStarted ();
555 public ServicePoint ServicePoint {
556 get { return GetServicePoint (); }
559 public override int Timeout {
560 get { return timeout; }
563 throw new ArgumentOutOfRangeException ("value");
569 public string TransferEncoding {
570 get { return webHeaders ["Transfer-Encoding"]; }
572 CheckRequestStarted ();
575 val = val.Trim ().ToLower ();
577 if (val == null || val.Length == 0) {
578 webHeaders.RemoveInternal ("Transfer-Encoding");
582 if (val == "chunked")
583 throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
586 throw new ArgumentException ("SendChunked must be True", "value");
588 webHeaders.RemoveAndAdd ("Transfer-Encoding", value);
592 public override bool UseDefaultCredentials
594 get { return CredentialCache.DefaultCredentials == Credentials; }
595 set { Credentials = value ? CredentialCache.DefaultCredentials : null; }
598 public string UserAgent {
599 get { return webHeaders ["User-Agent"]; }
600 set { webHeaders.SetInternal ("User-Agent", value); }
603 bool unsafe_auth_blah;
604 public bool UnsafeAuthenticatedConnectionSharing
606 get { return unsafe_auth_blah; }
607 set { unsafe_auth_blah = value; }
610 internal bool GotRequestStream {
611 get { return gotRequestStream; }
614 internal bool ExpectContinue {
615 get { return expectContinue; }
616 set { expectContinue = value; }
619 internal Uri AuthUri {
620 get { return actualUri; }
623 internal bool ProxyQuery {
624 get { return servicePoint.UsesProxy && !servicePoint.UseConnect; }
629 internal ServicePoint GetServicePoint ()
632 if (hostChanged || servicePoint == null) {
633 servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
641 public void AddRange (int range)
643 AddRange ("bytes", (long) range);
646 public void AddRange (int from, int to)
648 AddRange ("bytes", (long) from, (long) to);
651 public void AddRange (string rangeSpecifier, int range)
653 AddRange (rangeSpecifier, (long) range);
656 public void AddRange (string rangeSpecifier, int from, int to)
658 AddRange (rangeSpecifier, (long) from, (long) to);
665 void AddRange (long range)
667 AddRange ("bytes", (long) range);
675 void AddRange (long from, long to)
677 AddRange ("bytes", from, to);
685 void AddRange (string rangeSpecifier, long range)
687 if (rangeSpecifier == null)
688 throw new ArgumentNullException ("rangeSpecifier");
689 if (!WebHeaderCollection.IsHeaderValue (rangeSpecifier))
690 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
692 string r = webHeaders ["Range"];
694 r = rangeSpecifier + "=";
696 string old_specifier = r.Substring (0, r.IndexOf ('='));
697 if (String.Compare (old_specifier, rangeSpecifier, StringComparison.OrdinalIgnoreCase) != 0)
698 throw new InvalidOperationException ("A different range specifier is already in use");
702 string n = range.ToString (CultureInfo.InvariantCulture);
707 webHeaders.RemoveAndAdd ("Range", r);
715 void AddRange (string rangeSpecifier, long from, long to)
717 if (rangeSpecifier == null)
718 throw new ArgumentNullException ("rangeSpecifier");
719 if (!WebHeaderCollection.IsHeaderValue (rangeSpecifier))
720 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
721 if (from > to || from < 0)
722 throw new ArgumentOutOfRangeException ("from");
724 throw new ArgumentOutOfRangeException ("to");
726 string r = webHeaders ["Range"];
728 r = rangeSpecifier + "=";
732 r = String.Format ("{0}{1}-{2}", r, from, to);
733 webHeaders.RemoveAndAdd ("Range", r);
737 public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
740 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
742 bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
744 if (method == null || !send)
745 throw new ProtocolViolationException ("Cannot send data when method is: " + method);
747 if (contentLength == -1 && !sendChunked && !allowBuffering && KeepAlive)
748 throw new ProtocolViolationException ("Content-Length not set");
750 string transferEncoding = TransferEncoding;
751 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
752 throw new ProtocolViolationException ("SendChunked should be true.");
756 if (asyncWrite != null) {
757 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
758 "method while a previous call is still in progress.");
761 asyncWrite = new WebAsyncResult (this, callback, state);
762 initialMethod = method;
764 if (writeStream != null) {
765 asyncWrite.SetCompleted (true, writeStream);
766 asyncWrite.DoCallback ();
771 gotRequestStream = true;
772 WebAsyncResult result = asyncWrite;
776 servicePoint = GetServicePoint ();
777 abortHandler = servicePoint.SendRequest (this, connectionGroup);
783 public override Stream EndGetRequestStream (IAsyncResult asyncResult)
785 if (asyncResult == null)
786 throw new ArgumentNullException ("asyncResult");
788 WebAsyncResult result = asyncResult as WebAsyncResult;
790 throw new ArgumentException ("Invalid IAsyncResult");
793 result.WaitUntilComplete ();
795 Exception e = result.Exception;
799 return result.WriteStream;
802 public override Stream GetRequestStream()
804 IAsyncResult asyncResult = asyncWrite;
805 if (asyncResult == null) {
806 asyncResult = BeginGetRequestStream (null, null);
807 asyncWrite = (WebAsyncResult) asyncResult;
810 if (!asyncResult.IsCompleted && !asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
812 throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
815 return EndGetRequestStream (asyncResult);
818 void CheckIfForceWrite ()
820 if (writeStream == null || writeStream.RequestWritten || (contentLength < 0 && writeStream.CanWrite == true) || !InternalAllowBuffering)
823 // This will write the POST/PUT if the write stream already has the expected
824 // amount of bytes in it (ContentLength) (bug #77753) or if the write stream
825 // contains data and it has been closed already (xamarin bug #1512).
827 if (writeStream.WriteBufferLength == contentLength || (contentLength == -1 && writeStream.CanWrite == false))
828 writeStream.WriteRequest ();
831 public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
834 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
837 throw new ProtocolViolationException ("Method is null.");
839 string transferEncoding = TransferEncoding;
840 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
841 throw new ProtocolViolationException ("SendChunked should be true.");
843 Monitor.Enter (locker);
844 getResponseCalled = true;
845 if (asyncRead != null && !haveResponse) {
846 Monitor.Exit (locker);
847 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
848 "method while a previous call is still in progress.");
851 CheckIfForceWrite ();
852 asyncRead = new WebAsyncResult (this, callback, state);
853 WebAsyncResult aread = asyncRead;
854 initialMethod = method;
856 Exception saved = saved_exc;
857 if (webResponse != null) {
858 Monitor.Exit (locker);
860 aread.SetCompleted (true, webResponse);
862 aread.SetCompleted (true, saved);
866 } else if (saved != null) {
867 Monitor.Exit (locker);
868 aread.SetCompleted (true, saved);
877 servicePoint = GetServicePoint ();
878 abortHandler = servicePoint.SendRequest (this, connectionGroup);
881 Monitor.Exit (locker);
885 public override WebResponse EndGetResponse (IAsyncResult asyncResult)
887 if (asyncResult == null)
888 throw new ArgumentNullException ("asyncResult");
890 WebAsyncResult result = asyncResult as WebAsyncResult;
892 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
894 if (!result.WaitUntilComplete (timeout, false)) {
896 throw new WebException("The request timed out", WebExceptionStatus.Timeout);
899 if (result.GotException)
900 throw result.Exception;
902 return result.Response;
905 public override WebResponse GetResponse()
907 WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
908 return EndGetResponse (result);
911 internal bool FinishedReading {
912 get { return finished_reading; }
913 set { finished_reading = value; }
916 internal bool Aborted {
917 get { return Interlocked.CompareExchange (ref aborted, 0, 0) == 1; }
920 public override void Abort ()
922 if (Interlocked.CompareExchange (ref aborted, 1, 0) == 1)
925 if (haveResponse && finished_reading)
929 if (abortHandler != null) {
931 abortHandler (this, EventArgs.Empty);
932 } catch (Exception) {}
936 if (asyncWrite != null) {
937 WebAsyncResult r = asyncWrite;
938 if (!r.IsCompleted) {
940 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
941 r.SetCompleted (false, wexc);
948 if (asyncRead != null) {
949 WebAsyncResult r = asyncRead;
950 if (!r.IsCompleted) {
952 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
953 r.SetCompleted (false, wexc);
960 if (writeStream != null) {
962 writeStream.Close ();
967 if (webResponse != null) {
969 webResponse.Close ();
975 void ISerializable.GetObjectData (SerializationInfo serializationInfo,
976 StreamingContext streamingContext)
978 GetObjectData (serializationInfo, streamingContext);
981 protected override void GetObjectData (SerializationInfo serializationInfo,
982 StreamingContext streamingContext)
984 SerializationInfo info = serializationInfo;
986 info.AddValue ("requestUri", requestUri, typeof (Uri));
987 info.AddValue ("actualUri", actualUri, typeof (Uri));
988 info.AddValue ("allowAutoRedirect", allowAutoRedirect);
989 info.AddValue ("allowBuffering", allowBuffering);
990 info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
991 info.AddValue ("connectionGroup", connectionGroup);
992 info.AddValue ("contentLength", contentLength);
993 info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
994 info.AddValue ("keepAlive", keepAlive);
995 info.AddValue ("maxAutoRedirect", maxAutoRedirect);
996 info.AddValue ("mediaType", mediaType);
997 info.AddValue ("method", method);
998 info.AddValue ("initialMethod", initialMethod);
999 info.AddValue ("pipelined", pipelined);
1000 info.AddValue ("version", version, typeof (Version));
1001 info.AddValue ("proxy", proxy, typeof (IWebProxy));
1002 info.AddValue ("sendChunked", sendChunked);
1003 info.AddValue ("timeout", timeout);
1004 info.AddValue ("redirects", redirects);
1005 info.AddValue ("host", host);
1008 void CheckRequestStarted ()
1011 throw new InvalidOperationException ("request started");
1014 internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
1016 if (continueDelegate != null)
1017 continueDelegate (statusCode, headers);
1020 bool Redirect (WebAsyncResult result, HttpStatusCode code)
1024 string uriString = null;
1027 case HttpStatusCode.Ambiguous: // 300
1028 e = new WebException ("Ambiguous redirect.");
1030 case HttpStatusCode.MovedPermanently: // 301
1031 case HttpStatusCode.Redirect: // 302
1032 case HttpStatusCode.TemporaryRedirect: // 307
1033 /* MS follows the redirect for POST too
1034 if (method != "GET" && method != "HEAD") // 10.3
1039 bodyBufferLength = 0;
1041 if (code != HttpStatusCode.TemporaryRedirect)
1043 uriString = webResponse.Headers ["Location"];
1045 case HttpStatusCode.SeeOther: //303
1047 uriString = webResponse.Headers ["Location"];
1049 case HttpStatusCode.NotModified: // 304
1051 case HttpStatusCode.UseProxy: // 305
1052 e = new NotImplementedException ("Proxy support not available.");
1054 case HttpStatusCode.Unused: // 306
1056 e = new ProtocolViolationException ("Invalid status code: " + (int) code);
1063 if (uriString == null)
1064 throw new WebException ("No Location header found for " + (int) code,
1065 WebExceptionStatus.ProtocolError);
1067 Uri prev = actualUri;
1069 actualUri = new Uri (actualUri, uriString);
1070 } catch (Exception) {
1071 throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
1072 uriString, (int) code),
1073 WebExceptionStatus.ProtocolError);
1076 hostChanged = (actualUri.Scheme != prev.Scheme || Host != prev.Authority);
1080 string GetHeaders ()
1082 bool continue100 = false;
1085 webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
1086 webHeaders.RemoveInternal ("Content-Length");
1087 } else if (contentLength != -1) {
1088 if (ntlm_auth_state != NtlmAuthState.Challenge) {
1089 if (contentLength > 0)
1092 webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
1094 webHeaders.SetInternal ("Content-Length", "0");
1096 webHeaders.RemoveInternal ("Transfer-Encoding");
1098 webHeaders.RemoveInternal ("Content-Length");
1101 if (actualVersion == HttpVersion.Version11 && continue100 &&
1102 servicePoint.SendContinue) { // RFC2616 8.2.3
1103 webHeaders.RemoveAndAdd ("Expect" , "100-continue");
1104 expectContinue = true;
1106 webHeaders.RemoveInternal ("Expect");
1107 expectContinue = false;
1110 bool proxy_query = ProxyQuery;
1111 string connectionHeader = (proxy_query) ? "Proxy-Connection" : "Connection";
1112 webHeaders.RemoveInternal ((!proxy_query) ? "Proxy-Connection" : "Connection");
1113 Version proto_version = servicePoint.ProtocolVersion;
1114 bool spoint10 = (proto_version == null || proto_version == HttpVersion.Version10);
1116 if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
1117 webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
1118 } else if (!keepAlive && version == HttpVersion.Version11) {
1119 webHeaders.RemoveAndAdd (connectionHeader, "close");
1122 webHeaders.SetInternal ("Host", Host);
1123 if (cookieContainer != null) {
1124 string cookieHeader = cookieContainer.GetCookieHeader (actualUri);
1125 if (cookieHeader != "")
1126 webHeaders.SetInternal ("Cookie", cookieHeader);
1129 string accept_encoding = null;
1130 if ((auto_decomp & DecompressionMethods.GZip) != 0)
1131 accept_encoding = "gzip";
1132 if ((auto_decomp & DecompressionMethods.Deflate) != 0)
1133 accept_encoding = accept_encoding != null ? "gzip, deflate" : "deflate";
1134 if (accept_encoding != null)
1135 webHeaders.RemoveAndAdd ("Accept-Encoding", accept_encoding);
1137 if (!usedPreAuth && preAuthenticate)
1138 DoPreAuthenticate ();
1140 return webHeaders.ToString ();
1143 void DoPreAuthenticate ()
1145 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1146 ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
1147 Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
1151 webHeaders.RemoveInternal ("Proxy-Authorization");
1152 webHeaders.RemoveInternal ("Authorization");
1153 string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
1154 webHeaders [authHeader] = auth.Message;
1158 internal void SetWriteStreamError (WebExceptionStatus status, Exception exc)
1163 WebAsyncResult r = asyncWrite;
1171 msg = "Error: " + status;
1172 wex = new WebException (msg, status);
1174 msg = String.Format ("Error: {0} ({1})", status, exc.Message);
1175 wex = new WebException (msg, exc, status);
1177 r.SetCompleted (false, wex);
1182 internal void SendRequestHeaders (bool propagate_error)
1184 StringBuilder req = new StringBuilder ();
1187 query = actualUri.PathAndQuery;
1189 query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
1191 actualUri.PathAndQuery);
1194 if (!force_version && servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
1195 actualVersion = servicePoint.ProtocolVersion;
1197 actualVersion = version;
1200 req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
1201 actualVersion.Major, actualVersion.Minor);
1202 req.Append (GetHeaders ());
1203 string reqstr = req.ToString ();
1204 byte [] bytes = Encoding.UTF8.GetBytes (reqstr);
1206 writeStream.SetHeaders (bytes);
1207 } catch (WebException wexc) {
1208 SetWriteStreamError (wexc.Status, wexc);
1209 if (propagate_error)
1211 } catch (Exception exc) {
1212 SetWriteStreamError (WebExceptionStatus.SendFailure, exc);
1213 if (propagate_error)
1218 internal void SetWriteStream (WebConnectionStream stream)
1223 writeStream = stream;
1224 if (bodyBuffer != null) {
1225 webHeaders.RemoveInternal ("Transfer-Encoding");
1226 contentLength = bodyBufferLength;
1227 writeStream.SendChunked = false;
1230 SendRequestHeaders (false);
1234 if (bodyBuffer != null) {
1235 // The body has been written and buffered. The request "user"
1236 // won't write it again, so we must do it.
1237 if (ntlm_auth_state != NtlmAuthState.Challenge) {
1238 writeStream.Write (bodyBuffer, 0, bodyBufferLength);
1240 writeStream.Close ();
1242 } else if (method != "HEAD" && method != "GET" && method != "MKCOL" && method != "CONNECT" &&
1243 method != "TRACE") {
1244 if (getResponseCalled && !writeStream.RequestWritten)
1245 writeStream.WriteRequest ();
1248 if (asyncWrite != null) {
1249 asyncWrite.SetCompleted (false, stream);
1250 asyncWrite.DoCallback ();
1255 internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
1260 string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
1261 WebAsyncResult r = asyncRead;
1266 if (e is WebException) {
1267 wexc = (WebException) e;
1269 wexc = new WebException (msg, e, status, null);
1272 if (!r.IsCompleted) {
1273 r.SetCompleted (false, wexc);
1275 } else if (r == asyncWrite) {
1278 haveResponse = true;
1282 haveResponse = true;
1288 void CheckSendError (WebConnectionData data)
1290 // Got here, but no one called GetResponse
1291 int status = data.StatusCode;
1292 if (status < 400 || status == 401 || status == 407)
1295 if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
1296 // The request has not been completely sent and we got here!
1297 // We should probably just close and cause an error in any case,
1298 saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse);
1299 if (allowBuffering || sendChunked || writeStream.totalWritten >= contentLength) {
1300 webResponse.ReadAll ();
1302 writeStream.IgnoreIOErrors = true;
1307 void HandleNtlmAuth (WebAsyncResult r)
1309 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1311 WebConnection cnc = wce.Connection;
1312 cnc.PriorityRequest = this;
1313 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1314 ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1315 if (creds != null) {
1316 cnc.NtlmCredential = creds.GetCredential (requestUri, "NTLM");
1317 cnc.UnsafeAuthenticatedConnectionSharing = unsafe_auth_blah;
1321 finished_reading = false;
1322 haveResponse = false;
1323 webResponse.ReadAll ();
1327 internal void SetResponseData (WebConnectionData data)
1331 if (data.stream != null)
1332 data.stream.Close ();
1336 WebException wexc = null;
1338 webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
1339 } catch (Exception e) {
1340 wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null);
1341 if (data.stream != null)
1342 data.stream.Close ();
1345 if (wexc == null && (method == "POST" || method == "PUT")) {
1346 CheckSendError (data);
1347 if (saved_exc != null)
1348 wexc = (WebException) saved_exc;
1351 WebAsyncResult r = asyncRead;
1353 bool forced = false;
1354 if (r == null && webResponse != null) {
1355 // This is a forced completion (302, 204)...
1357 r = new WebAsyncResult (null, null);
1358 r.SetCompleted (false, webResponse);
1363 haveResponse = true;
1365 r.SetCompleted (false, wexc);
1372 redirected = CheckFinalStatus (r);
1374 if (ntlm_auth_state != NtlmAuthState.None && authCompleted && webResponse != null
1375 && (int)webResponse.StatusCode < 400) {
1376 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1378 WebConnection cnc = wce.Connection;
1379 cnc.NtlmAuthenticated = true;
1383 // clear internal buffer so that it does not
1384 // hold possible big buffer (bug #397627)
1385 if (writeStream != null)
1386 writeStream.KillBuffer ();
1388 haveResponse = true;
1389 r.SetCompleted (false, webResponse);
1392 if (webResponse != null) {
1393 if (ntlm_auth_state != NtlmAuthState.None) {
1397 webResponse.Close ();
1399 finished_reading = false;
1400 haveResponse = false;
1403 servicePoint = GetServicePoint ();
1404 abortHandler = servicePoint.SendRequest (this, connectionGroup);
1406 } catch (WebException wexc2) {
1409 haveResponse = true;
1411 r.SetCompleted (false, wexc2);
1414 } catch (Exception ex) {
1415 wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
1418 haveResponse = true;
1420 r.SetCompleted (false, wexc);
1428 bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1430 authCompleted = false;
1431 if (code == HttpStatusCode.Unauthorized && credentials == null)
1434 bool isProxy = (code == HttpStatusCode.ProxyAuthenticationRequired);
1435 if (isProxy && (proxy == null || proxy.Credentials == null))
1438 string [] authHeaders = response.Headers.GetValues ( (isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate");
1439 if (authHeaders == null || authHeaders.Length == 0)
1442 ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1443 Authorization auth = null;
1444 foreach (string authHeader in authHeaders) {
1445 auth = AuthenticationManager.Authenticate (authHeader, this, creds);
1451 webHeaders [(isProxy) ? "Proxy-Authorization" : "Authorization"] = auth.Message;
1452 authCompleted = auth.Complete;
1453 bool is_ntlm = (auth.Module.AuthenticationType == "NTLM");
1455 ntlm_auth_state = (NtlmAuthState)((int) ntlm_auth_state + 1);
1459 // Returns true if redirected
1460 bool CheckFinalStatus (WebAsyncResult result)
1462 if (result.GotException) {
1464 throw result.Exception;
1467 Exception throwMe = result.Exception;
1469 HttpWebResponse resp = result.Response;
1470 WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
1471 HttpStatusCode code = 0;
1472 if (throwMe == null && webResponse != null) {
1473 code = webResponse.StatusCode;
1474 if (!authCompleted && ((code == HttpStatusCode.Unauthorized && credentials != null) ||
1475 (ProxyQuery && code == HttpStatusCode.ProxyAuthenticationRequired))) {
1476 if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
1477 // Keep the written body, so it can be rewritten in the retry
1478 if (InternalAllowBuffering) {
1479 // NTLM: This is to avoid sending data in the 'challenge' request
1480 // We save it in the first request (first 401), don't send anything
1481 // in the challenge request and send it in the response request along
1482 // with the buffers kept form the first request.
1483 if (ntlm_auth_state != NtlmAuthState.Response) {
1484 bodyBuffer = writeStream.WriteBuffer;
1485 bodyBufferLength = writeStream.WriteBufferLength;
1488 } else if (method != "PUT" && method != "POST") {
1493 writeStream.InternalClose ();
1495 webResponse.Close ();
1499 throw new WebException ("This request requires buffering " +
1500 "of data for authentication or " +
1501 "redirection to be sucessful.");
1506 if ((int) code >= 400) {
1507 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1508 (int) code, webResponse.StatusDescription);
1509 throwMe = new WebException (err, null, protoError, webResponse);
1510 webResponse.ReadAll ();
1511 } else if ((int) code == 304 && allowAutoRedirect) {
1512 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1513 (int) code, webResponse.StatusDescription);
1514 throwMe = new WebException (err, null, protoError, webResponse);
1515 } else if ((int) code >= 300 && allowAutoRedirect && redirects >= maxAutoRedirect) {
1516 throwMe = new WebException ("Max. redirections exceeded.", null,
1517 protoError, webResponse);
1518 webResponse.ReadAll ();
1523 if (throwMe == null) {
1526 if (allowAutoRedirect && c >= 300) {
1527 if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
1528 bodyBuffer = writeStream.WriteBuffer;
1529 bodyBufferLength = writeStream.WriteBufferLength;
1531 b = Redirect (result, code);
1534 if (resp != null && c >= 300 && c != 304)
1540 if (writeStream != null) {
1541 writeStream.InternalClose ();