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 ();
239 val = val.Trim ().ToLower ();
241 if (val == null || val.Length == 0) {
242 webHeaders.RemoveInternal ("Connection");
246 if (val == "keep-alive" || val == "close")
247 throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
249 if (keepAlive && val.IndexOf ("keep-alive", StringComparison.Ordinal) == -1)
250 value = value + ", Keep-Alive";
252 webHeaders.RemoveAndAdd ("Connection", value);
256 public override string ConnectionGroupName {
257 get { return connectionGroup; }
258 set { connectionGroup = value; }
261 public override long ContentLength {
262 get { return contentLength; }
264 CheckRequestStarted ();
266 throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
268 contentLength = value;
272 internal long InternalContentLength {
273 set { contentLength = value; }
276 public override string ContentType {
277 get { return webHeaders ["Content-Type"]; }
279 if (value == null || value.Trim().Length == 0) {
280 webHeaders.RemoveInternal ("Content-Type");
283 webHeaders.RemoveAndAdd ("Content-Type", value);
287 public HttpContinueDelegate ContinueDelegate {
288 get { return continueDelegate; }
289 set { continueDelegate = value; }
292 public CookieContainer CookieContainer {
293 get { return cookieContainer; }
294 set { cookieContainer = value; }
297 public override ICredentials Credentials {
298 get { return credentials; }
299 set { credentials = value; }
302 public DateTime Date {
304 string date = webHeaders ["Date"];
306 return DateTime.MinValue;
307 return DateTime.ParseExact (date, "r", CultureInfo.InvariantCulture).ToLocalTime ();
311 webHeaders.RemoveInternal ("Date");
313 webHeaders.RemoveAndAdd ("Date", value.ToUniversalTime ().ToString ("r", CultureInfo.InvariantCulture));
319 public static new RequestCachePolicy DefaultCachePolicy
322 throw GetMustImplement ();
325 throw GetMustImplement ();
330 public static int DefaultMaximumErrorResponseLength
333 throw GetMustImplement ();
336 throw GetMustImplement ();
340 public string Expect {
341 get { return webHeaders ["Expect"]; }
343 CheckRequestStarted ();
346 val = val.Trim ().ToLower ();
348 if (val == null || val.Length == 0) {
349 webHeaders.RemoveInternal ("Expect");
353 if (val == "100-continue")
354 throw new ArgumentException ("100-Continue cannot be set with this property.",
356 webHeaders.RemoveAndAdd ("Expect", value);
360 public bool HaveResponse {
361 get { return haveResponse; }
364 public override WebHeaderCollection Headers {
365 get { return webHeaders; }
367 CheckRequestStarted ();
368 WebHeaderCollection newHeaders = new WebHeaderCollection (true);
369 int count = value.Count;
370 for (int i = 0; i < count; i++)
371 newHeaders.Add (value.GetKey (i), value.Get (i));
373 webHeaders = newHeaders;
384 return actualUri.Authority;
389 throw new ArgumentNullException ("value");
391 if (!CheckValidHost (actualUri.Scheme, value))
392 throw new ArgumentException ("Invalid host: " + value);
398 static bool CheckValidHost (string scheme, string val)
401 throw new ArgumentNullException ("value");
409 int idx = val.IndexOf ('/');
413 string u = scheme + "://" + val + "/";
414 return Uri.IsWellFormedUriString (u, UriKind.Absolute);
417 public DateTime IfModifiedSince {
419 string str = webHeaders ["If-Modified-Since"];
423 return MonoHttpDate.Parse (str);
424 } catch (Exception) {
429 CheckRequestStarted ();
431 webHeaders.SetInternal ("If-Modified-Since",
432 value.ToUniversalTime ().ToString ("r", null));
433 // TODO: check last param when using different locale
437 public bool KeepAlive {
446 public int MaximumAutomaticRedirections {
447 get { return maxAutoRedirect; }
450 throw new ArgumentException ("Must be > 0", "value");
452 maxAutoRedirect = value;
456 [MonoTODO ("Use this")]
457 public int MaximumResponseHeadersLength {
458 get { return maxResponseHeadersLength; }
459 set { maxResponseHeadersLength = value; }
462 [MonoTODO ("Use this")]
463 public static int DefaultMaximumResponseHeadersLength {
464 get { return defaultMaxResponseHeadersLength; }
465 set { defaultMaxResponseHeadersLength = value; }
468 public int ReadWriteTimeout {
469 get { return readWriteTimeout; }
472 throw new InvalidOperationException ("The request has already been sent.");
475 throw new ArgumentOutOfRangeException ("value", "Must be >= -1");
477 readWriteTimeout = value;
481 public string MediaType {
482 get { return mediaType; }
488 public override string Method {
489 get { return this.method; }
491 if (value == null || value.Trim () == "")
492 throw new ArgumentException ("not a valid method");
494 method = value.ToUpperInvariant ();
495 if (method != "HEAD" && method != "GET" && method != "POST" && method != "PUT" &&
496 method != "DELETE" && method != "CONNECT" && method != "TRACE" &&
503 public bool Pipelined {
504 get { return pipelined; }
505 set { pipelined = value; }
508 public override bool PreAuthenticate {
509 get { return preAuthenticate; }
510 set { preAuthenticate = value; }
513 public Version ProtocolVersion {
514 get { return version; }
516 if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
517 throw new ArgumentException ("value");
519 force_version = true;
524 public override IWebProxy Proxy {
525 get { return proxy; }
527 CheckRequestStarted ();
529 servicePoint = null; // we may need a new one
533 public string Referer {
534 get { return webHeaders ["Referer"]; }
536 CheckRequestStarted ();
537 if (value == null || value.Trim().Length == 0) {
538 webHeaders.RemoveInternal ("Referer");
541 webHeaders.SetInternal ("Referer", value);
545 public override Uri RequestUri {
546 get { return requestUri; }
549 public bool SendChunked {
550 get { return sendChunked; }
552 CheckRequestStarted ();
557 public ServicePoint ServicePoint {
558 get { return GetServicePoint (); }
561 public override int Timeout {
562 get { return timeout; }
565 throw new ArgumentOutOfRangeException ("value");
571 public string TransferEncoding {
572 get { return webHeaders ["Transfer-Encoding"]; }
574 CheckRequestStarted ();
577 val = val.Trim ().ToLower ();
579 if (val == null || val.Length == 0) {
580 webHeaders.RemoveInternal ("Transfer-Encoding");
584 if (val == "chunked")
585 throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
588 throw new ArgumentException ("SendChunked must be True", "value");
590 webHeaders.RemoveAndAdd ("Transfer-Encoding", value);
594 public override bool UseDefaultCredentials
596 get { return CredentialCache.DefaultCredentials == Credentials; }
597 set { Credentials = value ? CredentialCache.DefaultCredentials : null; }
600 public string UserAgent {
601 get { return webHeaders ["User-Agent"]; }
602 set { webHeaders.SetInternal ("User-Agent", value); }
605 bool unsafe_auth_blah;
606 public bool UnsafeAuthenticatedConnectionSharing
608 get { return unsafe_auth_blah; }
609 set { unsafe_auth_blah = value; }
612 internal bool GotRequestStream {
613 get { return gotRequestStream; }
616 internal bool ExpectContinue {
617 get { return expectContinue; }
618 set { expectContinue = value; }
621 internal Uri AuthUri {
622 get { return actualUri; }
625 internal bool ProxyQuery {
626 get { return servicePoint.UsesProxy && !servicePoint.UseConnect; }
631 internal ServicePoint GetServicePoint ()
634 if (hostChanged || servicePoint == null) {
635 servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
643 public void AddRange (int range)
645 AddRange ("bytes", (long) range);
648 public void AddRange (int from, int to)
650 AddRange ("bytes", (long) from, (long) to);
653 public void AddRange (string rangeSpecifier, int range)
655 AddRange (rangeSpecifier, (long) range);
658 public void AddRange (string rangeSpecifier, int from, int to)
660 AddRange (rangeSpecifier, (long) from, (long) to);
667 void AddRange (long range)
669 AddRange ("bytes", (long) range);
677 void AddRange (long from, long to)
679 AddRange ("bytes", from, to);
687 void AddRange (string rangeSpecifier, long range)
689 if (rangeSpecifier == null)
690 throw new ArgumentNullException ("rangeSpecifier");
691 if (!WebHeaderCollection.IsHeaderValue (rangeSpecifier))
692 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
694 string r = webHeaders ["Range"];
696 r = rangeSpecifier + "=";
698 string old_specifier = r.Substring (0, r.IndexOf ('='));
699 if (String.Compare (old_specifier, rangeSpecifier, StringComparison.OrdinalIgnoreCase) != 0)
700 throw new InvalidOperationException ("A different range specifier is already in use");
704 string n = range.ToString (CultureInfo.InvariantCulture);
709 webHeaders.RemoveAndAdd ("Range", r);
717 void AddRange (string rangeSpecifier, long from, long to)
719 if (rangeSpecifier == null)
720 throw new ArgumentNullException ("rangeSpecifier");
721 if (!WebHeaderCollection.IsHeaderValue (rangeSpecifier))
722 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
723 if (from > to || from < 0)
724 throw new ArgumentOutOfRangeException ("from");
726 throw new ArgumentOutOfRangeException ("to");
728 string r = webHeaders ["Range"];
730 r = rangeSpecifier + "=";
734 r = String.Format ("{0}{1}-{2}", r, from, to);
735 webHeaders.RemoveAndAdd ("Range", r);
739 public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
742 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
744 bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
746 if (method == null || !send)
747 throw new ProtocolViolationException ("Cannot send data when method is: " + method);
749 if (contentLength == -1 && !sendChunked && !allowBuffering && KeepAlive)
750 throw new ProtocolViolationException ("Content-Length not set");
752 string transferEncoding = TransferEncoding;
753 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
754 throw new ProtocolViolationException ("SendChunked should be true.");
758 if (asyncWrite != null) {
759 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
760 "method while a previous call is still in progress.");
763 asyncWrite = new WebAsyncResult (this, callback, state);
764 initialMethod = method;
766 if (writeStream != null) {
767 asyncWrite.SetCompleted (true, writeStream);
768 asyncWrite.DoCallback ();
773 gotRequestStream = true;
774 WebAsyncResult result = asyncWrite;
778 servicePoint = GetServicePoint ();
779 abortHandler = servicePoint.SendRequest (this, connectionGroup);
785 public override Stream EndGetRequestStream (IAsyncResult asyncResult)
787 if (asyncResult == null)
788 throw new ArgumentNullException ("asyncResult");
790 WebAsyncResult result = asyncResult as WebAsyncResult;
792 throw new ArgumentException ("Invalid IAsyncResult");
795 result.WaitUntilComplete ();
797 Exception e = result.Exception;
801 return result.WriteStream;
804 public override Stream GetRequestStream()
806 IAsyncResult asyncResult = asyncWrite;
807 if (asyncResult == null) {
808 asyncResult = BeginGetRequestStream (null, null);
809 asyncWrite = (WebAsyncResult) asyncResult;
812 if (!asyncResult.IsCompleted && !asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
814 throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
817 return EndGetRequestStream (asyncResult);
820 void CheckIfForceWrite ()
822 if (writeStream == null || writeStream.RequestWritten|| contentLength < 0 || !InternalAllowBuffering)
825 // This will write the POST/PUT if the write stream already has the expected
826 // amount of bytes in it (ContentLength) (bug #77753).
827 if (writeStream.WriteBufferLength == contentLength)
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 ();