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;
40 using System.Net.Cache;
41 using System.Net.Sockets;
42 using System.Runtime.Remoting.Messaging;
43 using System.Runtime.Serialization;
44 using System.Security.Cryptography.X509Certificates;
46 using System.Threading;
51 public class HttpWebRequest : WebRequest, ISerializable {
55 bool allowAutoRedirect = true;
56 bool allowBuffering = true;
57 X509CertificateCollection certificates;
58 string connectionGroup;
59 bool haveContentLength;
60 long contentLength = -1;
61 HttpContinueDelegate continueDelegate;
62 CookieContainer cookieContainer;
63 ICredentials credentials;
67 WebHeaderCollection webHeaders;
68 bool keepAlive = true;
69 int maxAutoRedirect = 50;
70 string mediaType = String.Empty;
71 string method = "GET";
72 string initialMethod = "GET";
73 bool pipelined = true;
76 Version version = HttpVersion.Version11;
78 Version actualVersion;
81 ServicePoint servicePoint;
84 WebConnectionStream writeStream;
85 HttpWebResponse webResponse;
86 WebAsyncResult asyncWrite;
87 WebAsyncResult asyncRead;
88 EventHandler abortHandler;
90 bool gotRequestStream;
95 bool getResponseCalled;
97 object locker = new object ();
98 bool finished_reading;
99 internal WebConnection WebConnection;
100 DecompressionMethods auto_decomp;
101 int maxResponseHeadersLength;
102 static int defaultMaxResponseHeadersLength;
103 int readWriteTimeout = 300000; // ms
110 AuthorizationState auth_state, proxy_auth_state;
114 static HttpWebRequest ()
116 defaultMaxResponseHeadersLength = 64 * 1024;
118 NetConfig config = ConfigurationSettings.GetConfig ("system.net/settings") as NetConfig;
119 if (config != null) {
120 int x = config.MaxResponseHeadersLength;
124 defaultMaxResponseHeadersLength = x;
134 HttpWebRequest (Uri uri)
136 this.requestUri = uri;
137 this.actualUri = uri;
138 this.proxy = GlobalProxySelection.Select;
139 this.webHeaders = new WebHeaderCollection (WebHeaderCollection.HeaderInfo.Request);
141 ResetAuthorization ();
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");
169 ResetAuthorization ();
172 void ResetAuthorization ()
174 auth_state = new AuthorizationState (this, false);
175 proxy_auth_state = new AuthorizationState (this, true);
180 public string Accept {
181 get { return webHeaders ["Accept"]; }
183 CheckRequestStarted ();
184 webHeaders.RemoveAndAdd ("Accept", value);
189 get { return actualUri; }
190 internal set { actualUri = value; } // Used by Ftp+proxy
193 public bool AllowAutoRedirect {
194 get { return allowAutoRedirect; }
195 set { this.allowAutoRedirect = value; }
198 public bool AllowWriteStreamBuffering {
199 get { return allowBuffering; }
200 set { allowBuffering = value; }
204 public virtual bool AllowReadStreamBuffering {
205 get { return allowBuffering; }
206 set { allowBuffering = value; }
210 static Exception GetMustImplement ()
212 return new NotImplementedException ();
215 public DecompressionMethods AutomaticDecompression
221 CheckRequestStarted ();
226 internal bool InternalAllowBuffering {
228 return (allowBuffering && (method != "HEAD" && method != "GET" &&
229 method != "MKCOL" && method != "CONNECT" &&
234 public X509CertificateCollection ClientCertificates {
236 if (certificates == null)
237 certificates = new X509CertificateCollection ();
243 throw GetMustImplement ();
247 public string Connection {
248 get { return webHeaders ["Connection"]; }
250 CheckRequestStarted ();
252 if (string.IsNullOrEmpty (value)) {
253 webHeaders.RemoveInternal ("Connection");
257 string val = value.ToLowerInvariant ();
258 if (val.Contains ("keep-alive") || val.Contains ("close"))
259 throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
262 value = value + ", Keep-Alive";
264 webHeaders.RemoveAndAdd ("Connection", value);
268 public override string ConnectionGroupName {
269 get { return connectionGroup; }
270 set { connectionGroup = value; }
273 public override long ContentLength {
274 get { return contentLength; }
276 CheckRequestStarted ();
278 throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
280 contentLength = value;
281 haveContentLength = true;
285 internal long InternalContentLength {
286 set { contentLength = value; }
289 internal bool ThrowOnError { get; set; }
291 public override string ContentType {
292 get { return webHeaders ["Content-Type"]; }
294 if (value == null || value.Trim().Length == 0) {
295 webHeaders.RemoveInternal ("Content-Type");
298 webHeaders.RemoveAndAdd ("Content-Type", value);
302 public HttpContinueDelegate ContinueDelegate {
303 get { return continueDelegate; }
304 set { continueDelegate = value; }
310 public CookieContainer CookieContainer {
311 get { return cookieContainer; }
312 set { cookieContainer = value; }
315 public override ICredentials Credentials {
316 get { return credentials; }
317 set { credentials = value; }
320 public DateTime Date {
322 string date = webHeaders ["Date"];
324 return DateTime.MinValue;
325 return DateTime.ParseExact (date, "r", CultureInfo.InvariantCulture).ToLocalTime ();
328 if (value.Equals (DateTime.MinValue))
329 webHeaders.RemoveInternal ("Date");
331 webHeaders.RemoveAndAdd ("Date", value.ToUniversalTime ().ToString ("r", CultureInfo.InvariantCulture));
338 public static new RequestCachePolicy DefaultCachePolicy
341 throw GetMustImplement ();
344 throw GetMustImplement ();
350 public static int DefaultMaximumErrorResponseLength
353 throw GetMustImplement ();
356 throw GetMustImplement ();
360 public string Expect {
361 get { return webHeaders ["Expect"]; }
363 CheckRequestStarted ();
366 val = val.Trim ().ToLower ();
368 if (val == null || val.Length == 0) {
369 webHeaders.RemoveInternal ("Expect");
373 if (val == "100-continue")
374 throw new ArgumentException ("100-Continue cannot be set with this property.",
376 webHeaders.RemoveAndAdd ("Expect", value);
383 public bool HaveResponse {
384 get { return haveResponse; }
387 public override WebHeaderCollection Headers {
388 get { return webHeaders; }
390 CheckRequestStarted ();
391 WebHeaderCollection newHeaders = new WebHeaderCollection (WebHeaderCollection.HeaderInfo.Request);
392 int count = value.Count;
393 for (int i = 0; i < count; i++)
394 newHeaders.Add (value.GetKey (i), value.Get (i));
396 webHeaders = newHeaders;
408 return actualUri.Authority;
413 throw new ArgumentNullException ("value");
415 if (!CheckValidHost (actualUri.Scheme, value))
416 throw new ArgumentException ("Invalid host: " + value);
422 static bool CheckValidHost (string scheme, string val)
430 int idx = val.IndexOf ('/');
435 if (IPAddress.TryParse (val, out ipaddr))
438 string u = scheme + "://" + val + "/";
439 return Uri.IsWellFormedUriString (u, UriKind.Absolute);
442 public DateTime IfModifiedSince {
444 string str = webHeaders ["If-Modified-Since"];
448 return MonoHttpDate.Parse (str);
449 } catch (Exception) {
454 CheckRequestStarted ();
456 webHeaders.SetInternal ("If-Modified-Since",
457 value.ToUniversalTime ().ToString ("r", null));
458 // TODO: check last param when using different locale
462 public bool KeepAlive {
471 public int MaximumAutomaticRedirections {
472 get { return maxAutoRedirect; }
475 throw new ArgumentException ("Must be > 0", "value");
477 maxAutoRedirect = value;
481 [MonoTODO ("Use this")]
482 public int MaximumResponseHeadersLength {
483 get { return maxResponseHeadersLength; }
484 set { maxResponseHeadersLength = value; }
487 [MonoTODO ("Use this")]
488 public static int DefaultMaximumResponseHeadersLength {
489 get { return defaultMaxResponseHeadersLength; }
490 set { defaultMaxResponseHeadersLength = value; }
493 public int ReadWriteTimeout {
494 get { return readWriteTimeout; }
497 throw new InvalidOperationException ("The request has already been sent.");
500 throw new ArgumentOutOfRangeException ("value", "Must be >= -1");
502 readWriteTimeout = value;
508 public int ContinueTimeout {
509 get { throw new NotImplementedException (); }
510 set { throw new NotImplementedException (); }
514 public string MediaType {
515 get { return mediaType; }
521 public override string Method {
522 get { return this.method; }
524 if (value == null || value.Trim () == "")
525 throw new ArgumentException ("not a valid method");
527 method = value.ToUpperInvariant ();
528 if (method != "HEAD" && method != "GET" && method != "POST" && method != "PUT" &&
529 method != "DELETE" && method != "CONNECT" && method != "TRACE" &&
536 public bool Pipelined {
537 get { return pipelined; }
538 set { pipelined = value; }
541 public override bool PreAuthenticate {
542 get { return preAuthenticate; }
543 set { preAuthenticate = value; }
546 public Version ProtocolVersion {
547 get { return version; }
549 if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
550 throw new ArgumentException ("value");
552 force_version = true;
557 public override IWebProxy Proxy {
558 get { return proxy; }
560 CheckRequestStarted ();
562 servicePoint = null; // we may need a new one
566 public string Referer {
567 get { return webHeaders ["Referer"]; }
569 CheckRequestStarted ();
570 if (value == null || value.Trim().Length == 0) {
571 webHeaders.RemoveInternal ("Referer");
574 webHeaders.SetInternal ("Referer", value);
578 public override Uri RequestUri {
579 get { return requestUri; }
582 public bool SendChunked {
583 get { return sendChunked; }
585 CheckRequestStarted ();
590 public ServicePoint ServicePoint {
591 get { return GetServicePoint (); }
594 internal ServicePoint ServicePointNoLock {
595 get { return servicePoint; }
598 public virtual bool SupportsCookieContainer {
600 // The managed implementation supports the cookie container
601 // it is only Silverlight that returns false here
606 public override int Timeout {
607 get { return timeout; }
610 throw new ArgumentOutOfRangeException ("value");
616 public string TransferEncoding {
617 get { return webHeaders ["Transfer-Encoding"]; }
619 CheckRequestStarted ();
622 val = val.Trim ().ToLower ();
624 if (val == null || val.Length == 0) {
625 webHeaders.RemoveInternal ("Transfer-Encoding");
629 if (val == "chunked")
630 throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
633 throw new ArgumentException ("SendChunked must be True", "value");
635 webHeaders.RemoveAndAdd ("Transfer-Encoding", value);
639 public override bool UseDefaultCredentials
641 get { return CredentialCache.DefaultCredentials == Credentials; }
642 set { Credentials = value ? CredentialCache.DefaultCredentials : null; }
645 public string UserAgent {
646 get { return webHeaders ["User-Agent"]; }
647 set { webHeaders.SetInternal ("User-Agent", value); }
650 bool unsafe_auth_blah;
651 public bool UnsafeAuthenticatedConnectionSharing
653 get { return unsafe_auth_blah; }
654 set { unsafe_auth_blah = value; }
657 internal bool GotRequestStream {
658 get { return gotRequestStream; }
661 internal bool ExpectContinue {
662 get { return expectContinue; }
663 set { expectContinue = value; }
666 internal Uri AuthUri {
667 get { return actualUri; }
670 internal bool ProxyQuery {
671 get { return servicePoint.UsesProxy && !servicePoint.UseConnect; }
676 internal ServicePoint GetServicePoint ()
679 if (hostChanged || servicePoint == null) {
680 servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
688 public void AddRange (int range)
690 AddRange ("bytes", (long) range);
693 public void AddRange (int from, int to)
695 AddRange ("bytes", (long) from, (long) to);
698 public void AddRange (string rangeSpecifier, int range)
700 AddRange (rangeSpecifier, (long) range);
703 public void AddRange (string rangeSpecifier, int from, int to)
705 AddRange (rangeSpecifier, (long) from, (long) to);
712 void AddRange (long range)
714 AddRange ("bytes", (long) range);
722 void AddRange (long from, long to)
724 AddRange ("bytes", from, to);
732 void AddRange (string rangeSpecifier, long range)
734 if (rangeSpecifier == null)
735 throw new ArgumentNullException ("rangeSpecifier");
736 if (!WebHeaderCollection.IsHeaderValue (rangeSpecifier))
737 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
739 string r = webHeaders ["Range"];
741 r = rangeSpecifier + "=";
743 string old_specifier = r.Substring (0, r.IndexOf ('='));
744 if (String.Compare (old_specifier, rangeSpecifier, StringComparison.OrdinalIgnoreCase) != 0)
745 throw new InvalidOperationException ("A different range specifier is already in use");
749 string n = range.ToString (CultureInfo.InvariantCulture);
754 webHeaders.RemoveAndAdd ("Range", r);
762 void AddRange (string rangeSpecifier, long from, long to)
764 if (rangeSpecifier == null)
765 throw new ArgumentNullException ("rangeSpecifier");
766 if (!WebHeaderCollection.IsHeaderValue (rangeSpecifier))
767 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
768 if (from > to || from < 0)
769 throw new ArgumentOutOfRangeException ("from");
771 throw new ArgumentOutOfRangeException ("to");
773 string r = webHeaders ["Range"];
775 r = rangeSpecifier + "=";
779 r = String.Format ("{0}{1}-{2}", r, from, to);
780 webHeaders.RemoveAndAdd ("Range", r);
784 public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
787 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
789 bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
791 if (method == null || !send)
792 throw new ProtocolViolationException ("Cannot send data when method is: " + method);
794 if (contentLength == -1 && !sendChunked && !allowBuffering && KeepAlive)
795 throw new ProtocolViolationException ("Content-Length not set");
797 string transferEncoding = TransferEncoding;
798 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
799 throw new ProtocolViolationException ("SendChunked should be true.");
803 if (getResponseCalled)
804 throw new InvalidOperationException ("The operation cannot be performed once the request has been submitted.");
806 if (asyncWrite != null) {
807 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
808 "method while a previous call is still in progress.");
811 asyncWrite = new WebAsyncResult (this, callback, state);
812 initialMethod = method;
814 if (writeStream != null) {
815 asyncWrite.SetCompleted (true, writeStream);
816 asyncWrite.DoCallback ();
821 gotRequestStream = true;
822 WebAsyncResult result = asyncWrite;
826 servicePoint = GetServicePoint ();
827 abortHandler = servicePoint.SendRequest (this, connectionGroup);
833 public override Stream EndGetRequestStream (IAsyncResult asyncResult)
835 if (asyncResult == null)
836 throw new ArgumentNullException ("asyncResult");
838 WebAsyncResult result = asyncResult as WebAsyncResult;
840 throw new ArgumentException ("Invalid IAsyncResult");
843 result.WaitUntilComplete ();
845 Exception e = result.Exception;
849 return result.WriteStream;
852 public override Stream GetRequestStream()
854 IAsyncResult asyncResult = asyncWrite;
855 if (asyncResult == null) {
856 asyncResult = BeginGetRequestStream (null, null);
857 asyncWrite = (WebAsyncResult) asyncResult;
860 if (!asyncResult.IsCompleted && !asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
862 throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
865 return EndGetRequestStream (asyncResult);
868 bool CheckIfForceWrite (SimpleAsyncResult result)
870 if (writeStream == null || writeStream.RequestWritten || !InternalAllowBuffering)
873 if (contentLength < 0 && writeStream.CanWrite == true && writeStream.WriteBufferLength < 0)
876 if (contentLength < 0 && writeStream.WriteBufferLength >= 0)
877 InternalContentLength = writeStream.WriteBufferLength;
879 if (contentLength < 0 && writeStream.CanWrite == true)
883 // This will write the POST/PUT if the write stream already has the expected
884 // amount of bytes in it (ContentLength) (bug #77753) or if the write stream
885 // contains data and it has been closed already (xamarin bug #1512).
887 if (writeStream.WriteBufferLength == contentLength || (contentLength == -1 && writeStream.CanWrite == false))
888 return writeStream.WriteRequestAsync (result);
893 public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
896 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
899 throw new ProtocolViolationException ("Method is null.");
901 string transferEncoding = TransferEncoding;
902 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
903 throw new ProtocolViolationException ("SendChunked should be true.");
905 Monitor.Enter (locker);
906 getResponseCalled = true;
907 if (asyncRead != null && !haveResponse) {
908 Monitor.Exit (locker);
909 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
910 "method while a previous call is still in progress.");
913 asyncRead = new WebAsyncResult (this, callback, state);
914 WebAsyncResult aread = asyncRead;
915 initialMethod = method;
917 SimpleAsyncResult.RunWithLock (locker, CheckIfForceWrite, inner => {
918 var synch = inner.CompletedSynchronously;
920 if (inner.GotException) {
921 aread.SetCompleted (synch, inner.Exception);
927 Exception saved = saved_exc;
928 if (webResponse != null) {
930 aread.SetCompleted (synch, webResponse);
932 aread.SetCompleted (synch, saved);
936 } else if (saved != null) {
937 aread.SetCompleted (synch, saved);
946 servicePoint = GetServicePoint ();
947 abortHandler = servicePoint.SendRequest (this, connectionGroup);
954 public override WebResponse EndGetResponse (IAsyncResult asyncResult)
956 if (asyncResult == null)
957 throw new ArgumentNullException ("asyncResult");
959 WebAsyncResult result = asyncResult as WebAsyncResult;
961 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
963 if (!result.WaitUntilComplete (timeout, false)) {
965 throw new WebException("The request timed out", WebExceptionStatus.Timeout);
968 if (result.GotException)
969 throw result.Exception;
971 return result.Response;
975 public Stream EndGetRequestStream (IAsyncResult asyncResult, out TransportContext transportContext)
977 transportContext = null;
978 return EndGetRequestStream (asyncResult);
982 public override WebResponse GetResponse()
984 WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
985 return EndGetResponse (result);
988 internal bool FinishedReading {
989 get { return finished_reading; }
990 set { finished_reading = value; }
993 internal bool Aborted {
994 get { return Interlocked.CompareExchange (ref aborted, 0, 0) == 1; }
997 public override void Abort ()
999 if (Interlocked.CompareExchange (ref aborted, 1, 0) == 1)
1002 if (haveResponse && finished_reading)
1005 haveResponse = true;
1006 if (abortHandler != null) {
1008 abortHandler (this, EventArgs.Empty);
1009 } catch (Exception) {}
1010 abortHandler = null;
1013 if (asyncWrite != null) {
1014 WebAsyncResult r = asyncWrite;
1015 if (!r.IsCompleted) {
1017 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
1018 r.SetCompleted (false, wexc);
1025 if (asyncRead != null) {
1026 WebAsyncResult r = asyncRead;
1027 if (!r.IsCompleted) {
1029 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
1030 r.SetCompleted (false, wexc);
1037 if (writeStream != null) {
1039 writeStream.Close ();
1044 if (webResponse != null) {
1046 webResponse.Close ();
1052 void ISerializable.GetObjectData (SerializationInfo serializationInfo,
1053 StreamingContext streamingContext)
1055 GetObjectData (serializationInfo, streamingContext);
1058 protected override void GetObjectData (SerializationInfo serializationInfo,
1059 StreamingContext streamingContext)
1061 SerializationInfo info = serializationInfo;
1063 info.AddValue ("requestUri", requestUri, typeof (Uri));
1064 info.AddValue ("actualUri", actualUri, typeof (Uri));
1065 info.AddValue ("allowAutoRedirect", allowAutoRedirect);
1066 info.AddValue ("allowBuffering", allowBuffering);
1067 info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
1068 info.AddValue ("connectionGroup", connectionGroup);
1069 info.AddValue ("contentLength", contentLength);
1070 info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
1071 info.AddValue ("keepAlive", keepAlive);
1072 info.AddValue ("maxAutoRedirect", maxAutoRedirect);
1073 info.AddValue ("mediaType", mediaType);
1074 info.AddValue ("method", method);
1075 info.AddValue ("initialMethod", initialMethod);
1076 info.AddValue ("pipelined", pipelined);
1077 info.AddValue ("version", version, typeof (Version));
1078 info.AddValue ("proxy", proxy, typeof (IWebProxy));
1079 info.AddValue ("sendChunked", sendChunked);
1080 info.AddValue ("timeout", timeout);
1081 info.AddValue ("redirects", redirects);
1082 info.AddValue ("host", host);
1085 void CheckRequestStarted ()
1088 throw new InvalidOperationException ("request started");
1091 internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
1093 if (continueDelegate != null)
1094 continueDelegate (statusCode, headers);
1097 void RewriteRedirectToGet ()
1100 webHeaders.RemoveInternal ("Transfer-Encoding");
1101 sendChunked = false;
1104 bool Redirect (WebAsyncResult result, HttpStatusCode code, WebResponse response)
1108 string uriString = null;
1110 case HttpStatusCode.Ambiguous: // 300
1111 e = new WebException ("Ambiguous redirect.");
1113 case HttpStatusCode.MovedPermanently: // 301
1114 case HttpStatusCode.Redirect: // 302
1115 if (method == "POST")
1116 RewriteRedirectToGet ();
1118 case HttpStatusCode.TemporaryRedirect: // 307
1120 case HttpStatusCode.SeeOther: //303
1121 RewriteRedirectToGet ();
1123 case HttpStatusCode.NotModified: // 304
1125 case HttpStatusCode.UseProxy: // 305
1126 e = new NotImplementedException ("Proxy support not available.");
1128 case HttpStatusCode.Unused: // 306
1130 e = new ProtocolViolationException ("Invalid status code: " + (int) code);
1134 if (method != "GET" && !InternalAllowBuffering)
1135 e = new WebException ("The request requires buffering data to succeed.", null, WebExceptionStatus.ProtocolError, webResponse);
1141 uriString = webResponse.Headers ["Location"];
1143 if (uriString == null)
1144 throw new WebException ("No Location header found for " + (int) code,
1145 WebExceptionStatus.ProtocolError);
1147 Uri prev = actualUri;
1149 actualUri = new Uri (actualUri, uriString);
1150 } catch (Exception) {
1151 throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
1152 uriString, (int) code),
1153 WebExceptionStatus.ProtocolError);
1156 hostChanged = (actualUri.Scheme != prev.Scheme || Host != prev.Authority);
1160 string GetHeaders ()
1162 bool continue100 = false;
1165 webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
1166 webHeaders.RemoveInternal ("Content-Length");
1167 } else if (contentLength != -1) {
1168 if (auth_state.NtlmAuthState == NtlmAuthState.Challenge || proxy_auth_state.NtlmAuthState == NtlmAuthState.Challenge) {
1169 // We don't send any body with the NTLM Challenge request.
1170 if (haveContentLength || gotRequestStream || contentLength > 0)
1171 webHeaders.SetInternal ("Content-Length", "0");
1173 webHeaders.RemoveInternal ("Content-Length");
1175 if (contentLength > 0)
1178 if (haveContentLength || gotRequestStream || contentLength > 0)
1179 webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
1181 webHeaders.RemoveInternal ("Transfer-Encoding");
1183 webHeaders.RemoveInternal ("Content-Length");
1186 if (actualVersion == HttpVersion.Version11 && continue100 &&
1187 servicePoint.SendContinue) { // RFC2616 8.2.3
1188 webHeaders.RemoveAndAdd ("Expect" , "100-continue");
1189 expectContinue = true;
1191 webHeaders.RemoveInternal ("Expect");
1192 expectContinue = false;
1195 bool proxy_query = ProxyQuery;
1196 string connectionHeader = (proxy_query) ? "Proxy-Connection" : "Connection";
1197 webHeaders.RemoveInternal ((!proxy_query) ? "Proxy-Connection" : "Connection");
1198 Version proto_version = servicePoint.ProtocolVersion;
1199 bool spoint10 = (proto_version == null || proto_version == HttpVersion.Version10);
1201 if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
1202 if (webHeaders[connectionHeader] == null
1203 || webHeaders[connectionHeader].IndexOf ("keep-alive", StringComparison.OrdinalIgnoreCase) == -1)
1204 webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
1205 } else if (!keepAlive && version == HttpVersion.Version11) {
1206 webHeaders.RemoveAndAdd (connectionHeader, "close");
1209 webHeaders.SetInternal ("Host", Host);
1210 if (cookieContainer != null) {
1211 string cookieHeader = cookieContainer.GetCookieHeader (actualUri);
1212 if (cookieHeader != "")
1213 webHeaders.RemoveAndAdd ("Cookie", cookieHeader);
1215 webHeaders.RemoveInternal ("Cookie");
1218 string accept_encoding = null;
1219 if ((auto_decomp & DecompressionMethods.GZip) != 0)
1220 accept_encoding = "gzip";
1221 if ((auto_decomp & DecompressionMethods.Deflate) != 0)
1222 accept_encoding = accept_encoding != null ? "gzip, deflate" : "deflate";
1223 if (accept_encoding != null)
1224 webHeaders.RemoveAndAdd ("Accept-Encoding", accept_encoding);
1226 if (!usedPreAuth && preAuthenticate)
1227 DoPreAuthenticate ();
1229 return webHeaders.ToString ();
1232 void DoPreAuthenticate ()
1234 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1235 ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
1236 Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
1240 webHeaders.RemoveInternal ("Proxy-Authorization");
1241 webHeaders.RemoveInternal ("Authorization");
1242 string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
1243 webHeaders [authHeader] = auth.Message;
1247 internal void SetWriteStreamError (WebExceptionStatus status, Exception exc)
1252 WebAsyncResult r = asyncWrite;
1260 msg = "Error: " + status;
1261 wex = new WebException (msg, status);
1263 msg = String.Format ("Error: {0} ({1})", status, exc.Message);
1264 wex = new WebException (msg, exc, status);
1266 r.SetCompleted (false, wex);
1271 internal byte[] GetRequestHeaders ()
1273 StringBuilder req = new StringBuilder ();
1276 query = actualUri.PathAndQuery;
1278 query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
1280 actualUri.PathAndQuery);
1283 if (!force_version && servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
1284 actualVersion = servicePoint.ProtocolVersion;
1286 actualVersion = version;
1289 req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
1290 actualVersion.Major, actualVersion.Minor);
1291 req.Append (GetHeaders ());
1292 string reqstr = req.ToString ();
1293 return Encoding.UTF8.GetBytes (reqstr);
1296 internal void SetWriteStream (WebConnectionStream stream)
1301 writeStream = stream;
1302 if (bodyBuffer != null) {
1303 webHeaders.RemoveInternal ("Transfer-Encoding");
1304 contentLength = bodyBufferLength;
1305 writeStream.SendChunked = false;
1308 writeStream.SetHeadersAsync (false, result => {
1309 if (result.GotException) {
1310 SetWriteStreamError (result.Exception);
1316 SetWriteStreamInner (inner => {
1317 if (inner.GotException) {
1318 SetWriteStreamError (inner.Exception);
1322 if (asyncWrite != null) {
1323 asyncWrite.SetCompleted (inner.CompletedSynchronously, writeStream);
1324 asyncWrite.DoCallback ();
1331 SimpleAsyncResult SetWriteStreamInner (SimpleAsyncCallback callback)
1333 return SimpleAsyncResult.Run (result => {
1334 if (bodyBuffer != null) {
1335 // The body has been written and buffered. The request "user"
1336 // won't write it again, so we must do it.
1337 if (auth_state.NtlmAuthState != NtlmAuthState.Challenge && proxy_auth_state.NtlmAuthState != NtlmAuthState.Challenge) {
1338 // FIXME: this is a blocking call on the thread pool that could lead to thread pool exhaustion
1339 writeStream.Write (bodyBuffer, 0, bodyBufferLength);
1341 writeStream.Close ();
1343 } else if (method != "HEAD" && method != "GET" && method != "MKCOL" && method != "CONNECT" &&
1344 method != "TRACE") {
1345 if (getResponseCalled && !writeStream.RequestWritten)
1346 return writeStream.WriteRequestAsync (result);
1353 void SetWriteStreamError (Exception exc)
1355 WebException wexc = exc as WebException;
1357 SetWriteStreamError (wexc.Status, wexc);
1359 SetWriteStreamError (WebExceptionStatus.SendFailure, exc);
1362 internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
1367 string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
1368 WebAsyncResult r = asyncRead;
1373 if (e is WebException) {
1374 wexc = (WebException) e;
1376 wexc = new WebException (msg, e, status, null);
1379 if (!r.IsCompleted) {
1380 r.SetCompleted (false, wexc);
1382 } else if (r == asyncWrite) {
1385 haveResponse = true;
1389 haveResponse = true;
1395 void CheckSendError (WebConnectionData data)
1397 // Got here, but no one called GetResponse
1398 int status = data.StatusCode;
1399 if (status < 400 || status == 401 || status == 407)
1402 if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
1403 // The request has not been completely sent and we got here!
1404 // We should probably just close and cause an error in any case,
1405 saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse);
1406 if (allowBuffering || sendChunked || writeStream.totalWritten >= contentLength) {
1407 webResponse.ReadAll ();
1409 writeStream.IgnoreIOErrors = true;
1414 bool HandleNtlmAuth (WebAsyncResult r)
1416 bool isProxy = webResponse.StatusCode == HttpStatusCode.ProxyAuthenticationRequired;
1417 if ((isProxy ? proxy_auth_state.NtlmAuthState : auth_state.NtlmAuthState) == NtlmAuthState.None)
1420 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1422 WebConnection cnc = wce.Connection;
1423 cnc.PriorityRequest = this;
1424 ICredentials creds = !isProxy ? credentials : proxy.Credentials;
1425 if (creds != null) {
1426 cnc.NtlmCredential = creds.GetCredential (requestUri, "NTLM");
1427 cnc.UnsafeAuthenticatedConnectionSharing = unsafe_auth_blah;
1431 finished_reading = false;
1432 haveResponse = false;
1433 webResponse.ReadAll ();
1438 internal void SetResponseData (WebConnectionData data)
1442 if (data.stream != null)
1443 data.stream.Close ();
1447 WebException wexc = null;
1449 webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
1450 } catch (Exception e) {
1451 wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null);
1452 if (data.stream != null)
1453 data.stream.Close ();
1456 if (wexc == null && (method == "POST" || method == "PUT")) {
1457 CheckSendError (data);
1458 if (saved_exc != null)
1459 wexc = (WebException) saved_exc;
1462 WebAsyncResult r = asyncRead;
1464 bool forced = false;
1465 if (r == null && webResponse != null) {
1466 // This is a forced completion (302, 204)...
1468 r = new WebAsyncResult (null, null);
1469 r.SetCompleted (false, webResponse);
1474 haveResponse = true;
1476 r.SetCompleted (false, wexc);
1481 bool isProxy = ProxyQuery && !proxy.IsBypassed (actualUri);
1485 redirected = CheckFinalStatus (r);
1487 if ((isProxy ? proxy_auth_state.IsNtlmAuthenticated : auth_state.IsNtlmAuthenticated) &&
1488 webResponse != null && (int)webResponse.StatusCode < 400) {
1489 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1491 WebConnection cnc = wce.Connection;
1492 cnc.NtlmAuthenticated = true;
1496 // clear internal buffer so that it does not
1497 // hold possible big buffer (bug #397627)
1498 if (writeStream != null)
1499 writeStream.KillBuffer ();
1501 haveResponse = true;
1502 r.SetCompleted (false, webResponse);
1506 sendChunked = false;
1507 webHeaders.RemoveInternal ("Transfer-Encoding");
1510 if (webResponse != null) {
1511 if (HandleNtlmAuth (r))
1513 webResponse.Close ();
1515 finished_reading = false;
1516 haveResponse = false;
1519 servicePoint = GetServicePoint ();
1520 abortHandler = servicePoint.SendRequest (this, connectionGroup);
1522 } catch (WebException wexc2) {
1525 haveResponse = true;
1527 r.SetCompleted (false, wexc2);
1530 } catch (Exception ex) {
1531 wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
1534 haveResponse = true;
1536 r.SetCompleted (false, wexc);
1544 struct AuthorizationState
1546 readonly HttpWebRequest request;
1547 readonly bool isProxy;
1549 NtlmAuthState ntlm_auth_state;
1551 public bool IsCompleted {
1552 get { return isCompleted; }
1555 public NtlmAuthState NtlmAuthState {
1556 get { return ntlm_auth_state; }
1559 public bool IsNtlmAuthenticated {
1560 get { return isCompleted && ntlm_auth_state != NtlmAuthState.None; }
1563 public AuthorizationState (HttpWebRequest request, bool isProxy)
1565 this.request = request;
1566 this.isProxy = isProxy;
1567 isCompleted = false;
1568 ntlm_auth_state = NtlmAuthState.None;
1571 public bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1573 isCompleted = false;
1574 if (code == HttpStatusCode.Unauthorized && request.credentials == null)
1577 // FIXME: This should never happen!
1578 if (isProxy != (code == HttpStatusCode.ProxyAuthenticationRequired))
1581 if (isProxy && (request.proxy == null || request.proxy.Credentials == null))
1584 string [] authHeaders = response.Headers.GetValues_internal (isProxy ? "Proxy-Authenticate" : "WWW-Authenticate", false);
1585 if (authHeaders == null || authHeaders.Length == 0)
1588 ICredentials creds = (!isProxy) ? request.credentials : request.proxy.Credentials;
1589 Authorization auth = null;
1590 foreach (string authHeader in authHeaders) {
1591 auth = AuthenticationManager.Authenticate (authHeader, request, creds);
1597 request.webHeaders [isProxy ? "Proxy-Authorization" : "Authorization"] = auth.Message;
1598 isCompleted = auth.Complete;
1599 bool is_ntlm = (auth.Module.AuthenticationType == "NTLM");
1601 ntlm_auth_state = (NtlmAuthState)((int) ntlm_auth_state + 1);
1605 public void Reset ()
1607 isCompleted = false;
1608 ntlm_auth_state = NtlmAuthState.None;
1609 request.webHeaders.RemoveInternal (isProxy ? "Proxy-Authorization" : "Authorization");
1612 public override string ToString ()
1614 return string.Format ("{0}AuthState [{1}:{2}]", isProxy ? "Proxy" : "", isCompleted, ntlm_auth_state);
1618 bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1620 bool isProxy = code == HttpStatusCode.ProxyAuthenticationRequired;
1621 return isProxy ? proxy_auth_state.CheckAuthorization (response, code) : auth_state.CheckAuthorization (response, code);
1624 // Returns true if redirected
1625 bool CheckFinalStatus (WebAsyncResult result)
1627 if (result.GotException) {
1629 throw result.Exception;
1632 Exception throwMe = result.Exception;
1634 HttpWebResponse resp = result.Response;
1635 WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
1636 HttpStatusCode code = 0;
1637 if (throwMe == null && webResponse != null) {
1638 code = webResponse.StatusCode;
1639 if ((!auth_state.IsCompleted && code == HttpStatusCode.Unauthorized && credentials != null) ||
1640 (ProxyQuery && !proxy_auth_state.IsCompleted && code == HttpStatusCode.ProxyAuthenticationRequired)) {
1641 if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
1642 // Keep the written body, so it can be rewritten in the retry
1643 if (InternalAllowBuffering) {
1644 if (writeStream.WriteBufferLength > 0) {
1645 bodyBuffer = writeStream.WriteBuffer;
1646 bodyBufferLength = writeStream.WriteBufferLength;
1649 } else if (method != "PUT" && method != "POST") {
1657 writeStream.InternalClose ();
1659 webResponse.Close ();
1663 throw new WebException ("This request requires buffering " +
1664 "of data for authentication or " +
1665 "redirection to be sucessful.");
1670 if ((int) code >= 400) {
1671 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1672 (int) code, webResponse.StatusDescription);
1673 throwMe = new WebException (err, null, protoError, webResponse);
1674 webResponse.ReadAll ();
1675 } else if ((int) code == 304 && allowAutoRedirect) {
1676 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1677 (int) code, webResponse.StatusDescription);
1678 throwMe = new WebException (err, null, protoError, webResponse);
1679 } else if ((int) code >= 300 && allowAutoRedirect && redirects >= maxAutoRedirect) {
1680 throwMe = new WebException ("Max. redirections exceeded.", null,
1681 protoError, webResponse);
1682 webResponse.ReadAll ();
1687 if (throwMe == null) {
1690 if (allowAutoRedirect && c >= 300) {
1691 b = Redirect (result, code, webResponse);
1692 if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
1693 bodyBuffer = writeStream.WriteBuffer;
1694 bodyBufferLength = writeStream.WriteBufferLength;
1696 if (b && !unsafe_auth_blah) {
1697 auth_state.Reset ();
1698 proxy_auth_state.Reset ();
1702 if (resp != null && c >= 300 && c != 304)
1711 if (writeStream != null) {
1712 writeStream.InternalClose ();
1721 internal bool ReuseConnection {
1726 internal WebConnection StoredConnection;