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;
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;
142 this.webHeaders = new WebHeaderCollection (WebHeaderCollection.HeaderInfo.Request);
145 [Obsolete ("Serialization is obsoleted for this type", false)]
146 protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
148 SerializationInfo info = serializationInfo;
150 requestUri = (Uri) info.GetValue ("requestUri", typeof (Uri));
151 actualUri = (Uri) info.GetValue ("actualUri", typeof (Uri));
152 allowAutoRedirect = info.GetBoolean ("allowAutoRedirect");
153 allowBuffering = info.GetBoolean ("allowBuffering");
154 certificates = (X509CertificateCollection) info.GetValue ("certificates", typeof (X509CertificateCollection));
155 connectionGroup = info.GetString ("connectionGroup");
156 contentLength = info.GetInt64 ("contentLength");
157 webHeaders = (WebHeaderCollection) info.GetValue ("webHeaders", typeof (WebHeaderCollection));
158 keepAlive = info.GetBoolean ("keepAlive");
159 maxAutoRedirect = info.GetInt32 ("maxAutoRedirect");
160 mediaType = info.GetString ("mediaType");
161 method = info.GetString ("method");
162 initialMethod = info.GetString ("initialMethod");
163 pipelined = info.GetBoolean ("pipelined");
164 version = (Version) info.GetValue ("version", typeof (Version));
165 proxy = (IWebProxy) info.GetValue ("proxy", typeof (IWebProxy));
166 sendChunked = info.GetBoolean ("sendChunked");
167 timeout = info.GetInt32 ("timeout");
168 redirects = info.GetInt32 ("redirects");
169 host = info.GetString ("host");
174 public string Accept {
175 get { return webHeaders ["Accept"]; }
177 CheckRequestStarted ();
178 webHeaders.RemoveAndAdd ("Accept", value);
183 get { return actualUri; }
184 internal set { actualUri = value; } // Used by Ftp+proxy
187 public bool AllowAutoRedirect {
188 get { return allowAutoRedirect; }
189 set { this.allowAutoRedirect = value; }
192 public bool AllowWriteStreamBuffering {
193 get { return allowBuffering; }
194 set { allowBuffering = value; }
197 static Exception GetMustImplement ()
199 return new NotImplementedException ();
202 public DecompressionMethods AutomaticDecompression
208 CheckRequestStarted ();
213 internal bool InternalAllowBuffering {
215 return (allowBuffering && (method != "HEAD" && method != "GET" &&
216 method != "MKCOL" && method != "CONNECT" &&
221 public X509CertificateCollection ClientCertificates {
223 if (certificates == null)
224 certificates = new X509CertificateCollection ();
230 throw GetMustImplement ();
234 public string Connection {
235 get { return webHeaders ["Connection"]; }
237 CheckRequestStarted ();
239 if (string.IsNullOrEmpty (value)) {
240 webHeaders.RemoveInternal ("Connection");
244 string val = value.ToLowerInvariant ();
245 if (val.Contains ("keep-alive") || val.Contains ("close"))
246 throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
249 value = value + ", Keep-Alive";
251 webHeaders.RemoveAndAdd ("Connection", value);
255 public override string ConnectionGroupName {
256 get { return connectionGroup; }
257 set { connectionGroup = value; }
260 public override long ContentLength {
261 get { return contentLength; }
263 CheckRequestStarted ();
265 throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
267 contentLength = value;
271 internal long InternalContentLength {
272 set { contentLength = value; }
275 public override string ContentType {
276 get { return webHeaders ["Content-Type"]; }
278 if (value == null || value.Trim().Length == 0) {
279 webHeaders.RemoveInternal ("Content-Type");
282 webHeaders.RemoveAndAdd ("Content-Type", value);
286 public HttpContinueDelegate ContinueDelegate {
287 get { return continueDelegate; }
288 set { continueDelegate = value; }
291 public CookieContainer CookieContainer {
292 get { return cookieContainer; }
293 set { cookieContainer = value; }
296 public override ICredentials Credentials {
297 get { return credentials; }
298 set { credentials = value; }
301 public DateTime Date {
303 string date = webHeaders ["Date"];
305 return DateTime.MinValue;
306 return DateTime.ParseExact (date, "r", CultureInfo.InvariantCulture).ToLocalTime ();
310 webHeaders.RemoveInternal ("Date");
312 webHeaders.RemoveAndAdd ("Date", value.ToUniversalTime ().ToString ("r", CultureInfo.InvariantCulture));
318 public static new RequestCachePolicy DefaultCachePolicy
321 throw GetMustImplement ();
324 throw GetMustImplement ();
329 public static int DefaultMaximumErrorResponseLength
332 throw GetMustImplement ();
335 throw GetMustImplement ();
339 public string Expect {
340 get { return webHeaders ["Expect"]; }
342 CheckRequestStarted ();
345 val = val.Trim ().ToLower ();
347 if (val == null || val.Length == 0) {
348 webHeaders.RemoveInternal ("Expect");
352 if (val == "100-continue")
353 throw new ArgumentException ("100-Continue cannot be set with this property.",
355 webHeaders.RemoveAndAdd ("Expect", value);
359 public bool HaveResponse {
360 get { return haveResponse; }
363 public override WebHeaderCollection Headers {
364 get { return webHeaders; }
366 CheckRequestStarted ();
367 WebHeaderCollection newHeaders = new WebHeaderCollection (WebHeaderCollection.HeaderInfo.Request);
368 int count = value.Count;
369 for (int i = 0; i < count; i++)
370 newHeaders.Add (value.GetKey (i), value.Get (i));
372 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 && writeStream.CanWrite == true) || !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) or if the write stream
827 // contains data and it has been closed already (xamarin bug #1512).
829 if (writeStream.WriteBufferLength == contentLength || (contentLength == -1 && writeStream.CanWrite == false))
830 writeStream.WriteRequest ();
833 public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
836 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
839 throw new ProtocolViolationException ("Method is null.");
841 string transferEncoding = TransferEncoding;
842 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
843 throw new ProtocolViolationException ("SendChunked should be true.");
845 Monitor.Enter (locker);
846 getResponseCalled = true;
847 if (asyncRead != null && !haveResponse) {
848 Monitor.Exit (locker);
849 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
850 "method while a previous call is still in progress.");
853 CheckIfForceWrite ();
854 asyncRead = new WebAsyncResult (this, callback, state);
855 WebAsyncResult aread = asyncRead;
856 initialMethod = method;
858 Exception saved = saved_exc;
859 if (webResponse != null) {
860 Monitor.Exit (locker);
862 aread.SetCompleted (true, webResponse);
864 aread.SetCompleted (true, saved);
868 } else if (saved != null) {
869 Monitor.Exit (locker);
870 aread.SetCompleted (true, saved);
879 servicePoint = GetServicePoint ();
880 abortHandler = servicePoint.SendRequest (this, connectionGroup);
883 Monitor.Exit (locker);
887 public override WebResponse EndGetResponse (IAsyncResult asyncResult)
889 if (asyncResult == null)
890 throw new ArgumentNullException ("asyncResult");
892 WebAsyncResult result = asyncResult as WebAsyncResult;
894 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
896 if (!result.WaitUntilComplete (timeout, false)) {
898 throw new WebException("The request timed out", WebExceptionStatus.Timeout);
901 if (result.GotException)
902 throw result.Exception;
904 return result.Response;
907 public override WebResponse GetResponse()
909 WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
910 return EndGetResponse (result);
913 internal bool FinishedReading {
914 get { return finished_reading; }
915 set { finished_reading = value; }
918 internal bool Aborted {
919 get { return Interlocked.CompareExchange (ref aborted, 0, 0) == 1; }
922 public override void Abort ()
924 if (Interlocked.CompareExchange (ref aborted, 1, 0) == 1)
927 if (haveResponse && finished_reading)
931 if (abortHandler != null) {
933 abortHandler (this, EventArgs.Empty);
934 } catch (Exception) {}
938 if (asyncWrite != null) {
939 WebAsyncResult r = asyncWrite;
940 if (!r.IsCompleted) {
942 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
943 r.SetCompleted (false, wexc);
950 if (asyncRead != null) {
951 WebAsyncResult r = asyncRead;
952 if (!r.IsCompleted) {
954 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
955 r.SetCompleted (false, wexc);
962 if (writeStream != null) {
964 writeStream.Close ();
969 if (webResponse != null) {
971 webResponse.Close ();
977 void ISerializable.GetObjectData (SerializationInfo serializationInfo,
978 StreamingContext streamingContext)
980 GetObjectData (serializationInfo, streamingContext);
983 protected override void GetObjectData (SerializationInfo serializationInfo,
984 StreamingContext streamingContext)
986 SerializationInfo info = serializationInfo;
988 info.AddValue ("requestUri", requestUri, typeof (Uri));
989 info.AddValue ("actualUri", actualUri, typeof (Uri));
990 info.AddValue ("allowAutoRedirect", allowAutoRedirect);
991 info.AddValue ("allowBuffering", allowBuffering);
992 info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
993 info.AddValue ("connectionGroup", connectionGroup);
994 info.AddValue ("contentLength", contentLength);
995 info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
996 info.AddValue ("keepAlive", keepAlive);
997 info.AddValue ("maxAutoRedirect", maxAutoRedirect);
998 info.AddValue ("mediaType", mediaType);
999 info.AddValue ("method", method);
1000 info.AddValue ("initialMethod", initialMethod);
1001 info.AddValue ("pipelined", pipelined);
1002 info.AddValue ("version", version, typeof (Version));
1003 info.AddValue ("proxy", proxy, typeof (IWebProxy));
1004 info.AddValue ("sendChunked", sendChunked);
1005 info.AddValue ("timeout", timeout);
1006 info.AddValue ("redirects", redirects);
1007 info.AddValue ("host", host);
1010 void CheckRequestStarted ()
1013 throw new InvalidOperationException ("request started");
1016 internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
1018 if (continueDelegate != null)
1019 continueDelegate (statusCode, headers);
1022 bool Redirect (WebAsyncResult result, HttpStatusCode code)
1026 string uriString = null;
1029 case HttpStatusCode.Ambiguous: // 300
1030 e = new WebException ("Ambiguous redirect.");
1032 case HttpStatusCode.MovedPermanently: // 301
1033 case HttpStatusCode.Redirect: // 302
1034 case HttpStatusCode.TemporaryRedirect: // 307
1035 /* MS follows the redirect for POST too
1036 if (method != "GET" && method != "HEAD") // 10.3
1041 bodyBufferLength = 0;
1043 if (code != HttpStatusCode.TemporaryRedirect)
1045 uriString = webResponse.Headers ["Location"];
1047 case HttpStatusCode.SeeOther: //303
1049 uriString = webResponse.Headers ["Location"];
1051 case HttpStatusCode.NotModified: // 304
1053 case HttpStatusCode.UseProxy: // 305
1054 e = new NotImplementedException ("Proxy support not available.");
1056 case HttpStatusCode.Unused: // 306
1058 e = new ProtocolViolationException ("Invalid status code: " + (int) code);
1065 if (uriString == null)
1066 throw new WebException ("No Location header found for " + (int) code,
1067 WebExceptionStatus.ProtocolError);
1069 Uri prev = actualUri;
1071 actualUri = new Uri (actualUri, uriString);
1072 } catch (Exception) {
1073 throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
1074 uriString, (int) code),
1075 WebExceptionStatus.ProtocolError);
1078 hostChanged = (actualUri.Scheme != prev.Scheme || Host != prev.Authority);
1082 string GetHeaders ()
1084 bool continue100 = false;
1087 webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
1088 webHeaders.RemoveInternal ("Content-Length");
1089 } else if (contentLength != -1) {
1090 if (ntlm_auth_state != NtlmAuthState.Challenge) {
1091 if (contentLength > 0)
1094 webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
1096 webHeaders.SetInternal ("Content-Length", "0");
1098 webHeaders.RemoveInternal ("Transfer-Encoding");
1100 webHeaders.RemoveInternal ("Content-Length");
1103 if (actualVersion == HttpVersion.Version11 && continue100 &&
1104 servicePoint.SendContinue) { // RFC2616 8.2.3
1105 webHeaders.RemoveAndAdd ("Expect" , "100-continue");
1106 expectContinue = true;
1108 webHeaders.RemoveInternal ("Expect");
1109 expectContinue = false;
1112 bool proxy_query = ProxyQuery;
1113 string connectionHeader = (proxy_query) ? "Proxy-Connection" : "Connection";
1114 webHeaders.RemoveInternal ((!proxy_query) ? "Proxy-Connection" : "Connection");
1115 Version proto_version = servicePoint.ProtocolVersion;
1116 bool spoint10 = (proto_version == null || proto_version == HttpVersion.Version10);
1118 if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
1119 webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
1120 } else if (!keepAlive && version == HttpVersion.Version11) {
1121 webHeaders.RemoveAndAdd (connectionHeader, "close");
1124 webHeaders.SetInternal ("Host", Host);
1125 if (cookieContainer != null) {
1126 string cookieHeader = cookieContainer.GetCookieHeader (actualUri);
1127 if (cookieHeader != "")
1128 webHeaders.SetInternal ("Cookie", cookieHeader);
1131 string accept_encoding = null;
1132 if ((auto_decomp & DecompressionMethods.GZip) != 0)
1133 accept_encoding = "gzip";
1134 if ((auto_decomp & DecompressionMethods.Deflate) != 0)
1135 accept_encoding = accept_encoding != null ? "gzip, deflate" : "deflate";
1136 if (accept_encoding != null)
1137 webHeaders.RemoveAndAdd ("Accept-Encoding", accept_encoding);
1139 if (!usedPreAuth && preAuthenticate)
1140 DoPreAuthenticate ();
1142 return webHeaders.ToString ();
1145 void DoPreAuthenticate ()
1147 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1148 ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
1149 Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
1153 webHeaders.RemoveInternal ("Proxy-Authorization");
1154 webHeaders.RemoveInternal ("Authorization");
1155 string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
1156 webHeaders [authHeader] = auth.Message;
1160 internal void SetWriteStreamError (WebExceptionStatus status, Exception exc)
1165 WebAsyncResult r = asyncWrite;
1173 msg = "Error: " + status;
1174 wex = new WebException (msg, status);
1176 msg = String.Format ("Error: {0} ({1})", status, exc.Message);
1177 wex = new WebException (msg, exc, status);
1179 r.SetCompleted (false, wex);
1184 internal void SendRequestHeaders (bool propagate_error)
1186 StringBuilder req = new StringBuilder ();
1189 query = actualUri.PathAndQuery;
1191 query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
1193 actualUri.PathAndQuery);
1196 if (!force_version && servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
1197 actualVersion = servicePoint.ProtocolVersion;
1199 actualVersion = version;
1202 req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
1203 actualVersion.Major, actualVersion.Minor);
1204 req.Append (GetHeaders ());
1205 string reqstr = req.ToString ();
1206 byte [] bytes = Encoding.UTF8.GetBytes (reqstr);
1208 writeStream.SetHeaders (bytes);
1209 } catch (WebException wexc) {
1210 SetWriteStreamError (wexc.Status, wexc);
1211 if (propagate_error)
1213 } catch (Exception exc) {
1214 SetWriteStreamError (WebExceptionStatus.SendFailure, exc);
1215 if (propagate_error)
1220 internal void SetWriteStream (WebConnectionStream stream)
1225 writeStream = stream;
1226 if (bodyBuffer != null) {
1227 webHeaders.RemoveInternal ("Transfer-Encoding");
1228 contentLength = bodyBufferLength;
1229 writeStream.SendChunked = false;
1232 SendRequestHeaders (false);
1236 if (bodyBuffer != null) {
1237 // The body has been written and buffered. The request "user"
1238 // won't write it again, so we must do it.
1239 if (ntlm_auth_state != NtlmAuthState.Challenge) {
1240 writeStream.Write (bodyBuffer, 0, bodyBufferLength);
1242 writeStream.Close ();
1244 } else if (method != "HEAD" && method != "GET" && method != "MKCOL" && method != "CONNECT" &&
1245 method != "TRACE") {
1246 if (getResponseCalled && !writeStream.RequestWritten)
1247 writeStream.WriteRequest ();
1250 if (asyncWrite != null) {
1251 asyncWrite.SetCompleted (false, stream);
1252 asyncWrite.DoCallback ();
1257 internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
1262 string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
1263 WebAsyncResult r = asyncRead;
1268 if (e is WebException) {
1269 wexc = (WebException) e;
1271 wexc = new WebException (msg, e, status, null);
1274 if (!r.IsCompleted) {
1275 r.SetCompleted (false, wexc);
1277 } else if (r == asyncWrite) {
1280 haveResponse = true;
1284 haveResponse = true;
1290 void CheckSendError (WebConnectionData data)
1292 // Got here, but no one called GetResponse
1293 int status = data.StatusCode;
1294 if (status < 400 || status == 401 || status == 407)
1297 if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
1298 // The request has not been completely sent and we got here!
1299 // We should probably just close and cause an error in any case,
1300 saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse);
1301 if (allowBuffering || sendChunked || writeStream.totalWritten >= contentLength) {
1302 webResponse.ReadAll ();
1304 writeStream.IgnoreIOErrors = true;
1309 void HandleNtlmAuth (WebAsyncResult r)
1311 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1313 WebConnection cnc = wce.Connection;
1314 cnc.PriorityRequest = this;
1315 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1316 ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1317 if (creds != null) {
1318 cnc.NtlmCredential = creds.GetCredential (requestUri, "NTLM");
1319 cnc.UnsafeAuthenticatedConnectionSharing = unsafe_auth_blah;
1323 finished_reading = false;
1324 haveResponse = false;
1325 webResponse.ReadAll ();
1329 internal void SetResponseData (WebConnectionData data)
1333 if (data.stream != null)
1334 data.stream.Close ();
1338 WebException wexc = null;
1340 webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
1341 } catch (Exception e) {
1342 wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null);
1343 if (data.stream != null)
1344 data.stream.Close ();
1347 if (wexc == null && (method == "POST" || method == "PUT")) {
1348 CheckSendError (data);
1349 if (saved_exc != null)
1350 wexc = (WebException) saved_exc;
1353 WebAsyncResult r = asyncRead;
1355 bool forced = false;
1356 if (r == null && webResponse != null) {
1357 // This is a forced completion (302, 204)...
1359 r = new WebAsyncResult (null, null);
1360 r.SetCompleted (false, webResponse);
1365 haveResponse = true;
1367 r.SetCompleted (false, wexc);
1374 redirected = CheckFinalStatus (r);
1376 if (ntlm_auth_state != NtlmAuthState.None && authCompleted && webResponse != null
1377 && (int)webResponse.StatusCode < 400) {
1378 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1380 WebConnection cnc = wce.Connection;
1381 cnc.NtlmAuthenticated = true;
1385 // clear internal buffer so that it does not
1386 // hold possible big buffer (bug #397627)
1387 if (writeStream != null)
1388 writeStream.KillBuffer ();
1390 haveResponse = true;
1391 r.SetCompleted (false, webResponse);
1394 if (webResponse != null) {
1395 if (ntlm_auth_state != NtlmAuthState.None) {
1399 webResponse.Close ();
1401 finished_reading = false;
1402 haveResponse = false;
1405 servicePoint = GetServicePoint ();
1406 abortHandler = servicePoint.SendRequest (this, connectionGroup);
1408 } catch (WebException wexc2) {
1411 haveResponse = true;
1413 r.SetCompleted (false, wexc2);
1416 } catch (Exception ex) {
1417 wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
1420 haveResponse = true;
1422 r.SetCompleted (false, wexc);
1430 bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1432 authCompleted = false;
1433 if (code == HttpStatusCode.Unauthorized && credentials == null)
1436 bool isProxy = (code == HttpStatusCode.ProxyAuthenticationRequired);
1437 if (isProxy && (proxy == null || proxy.Credentials == null))
1440 string [] authHeaders = response.Headers.GetValues ( (isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate");
1441 if (authHeaders == null || authHeaders.Length == 0)
1444 ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1445 Authorization auth = null;
1446 foreach (string authHeader in authHeaders) {
1447 auth = AuthenticationManager.Authenticate (authHeader, this, creds);
1453 webHeaders [(isProxy) ? "Proxy-Authorization" : "Authorization"] = auth.Message;
1454 authCompleted = auth.Complete;
1455 bool is_ntlm = (auth.Module.AuthenticationType == "NTLM");
1457 ntlm_auth_state = (NtlmAuthState)((int) ntlm_auth_state + 1);
1461 // Returns true if redirected
1462 bool CheckFinalStatus (WebAsyncResult result)
1464 if (result.GotException) {
1466 throw result.Exception;
1469 Exception throwMe = result.Exception;
1471 HttpWebResponse resp = result.Response;
1472 WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
1473 HttpStatusCode code = 0;
1474 if (throwMe == null && webResponse != null) {
1475 code = webResponse.StatusCode;
1476 if (!authCompleted && ((code == HttpStatusCode.Unauthorized && credentials != null) ||
1477 (ProxyQuery && code == HttpStatusCode.ProxyAuthenticationRequired))) {
1478 if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
1479 // Keep the written body, so it can be rewritten in the retry
1480 if (InternalAllowBuffering) {
1481 // NTLM: This is to avoid sending data in the 'challenge' request
1482 // We save it in the first request (first 401), don't send anything
1483 // in the challenge request and send it in the response request along
1484 // with the buffers kept form the first request.
1485 if (ntlm_auth_state != NtlmAuthState.Response) {
1486 bodyBuffer = writeStream.WriteBuffer;
1487 bodyBufferLength = writeStream.WriteBufferLength;
1490 } else if (method != "PUT" && method != "POST") {
1495 writeStream.InternalClose ();
1497 webResponse.Close ();
1501 throw new WebException ("This request requires buffering " +
1502 "of data for authentication or " +
1503 "redirection to be sucessful.");
1508 if ((int) code >= 400) {
1509 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1510 (int) code, webResponse.StatusDescription);
1511 throwMe = new WebException (err, null, protoError, webResponse);
1512 webResponse.ReadAll ();
1513 } else if ((int) code == 304 && allowAutoRedirect) {
1514 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1515 (int) code, webResponse.StatusDescription);
1516 throwMe = new WebException (err, null, protoError, webResponse);
1517 } else if ((int) code >= 300 && allowAutoRedirect && redirects >= maxAutoRedirect) {
1518 throwMe = new WebException ("Max. redirections exceeded.", null,
1519 protoError, webResponse);
1520 webResponse.ReadAll ();
1525 if (throwMe == null) {
1528 if (allowAutoRedirect && c >= 300) {
1529 if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
1530 bodyBuffer = writeStream.WriteBuffer;
1531 bodyBufferLength = writeStream.WriteBufferLength;
1533 b = Redirect (result, code);
1536 if (resp != null && c >= 300 && c != 304)
1542 if (writeStream != null) {
1543 writeStream.InternalClose ();