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 long contentLength = -1;
60 HttpContinueDelegate continueDelegate;
61 CookieContainer cookieContainer;
62 ICredentials credentials;
66 WebHeaderCollection webHeaders;
67 bool keepAlive = true;
68 int maxAutoRedirect = 50;
69 string mediaType = String.Empty;
70 string method = "GET";
71 string initialMethod = "GET";
72 bool pipelined = true;
75 Version version = HttpVersion.Version11;
77 Version actualVersion;
80 ServicePoint servicePoint;
83 WebConnectionStream writeStream;
84 HttpWebResponse webResponse;
85 WebAsyncResult asyncWrite;
86 WebAsyncResult asyncRead;
87 EventHandler abortHandler;
89 bool gotRequestStream;
94 bool getResponseCalled;
96 object locker = new object ();
97 bool finished_reading;
98 internal WebConnection WebConnection;
99 DecompressionMethods auto_decomp;
100 int maxResponseHeadersLength;
101 static int defaultMaxResponseHeadersLength;
102 int readWriteTimeout = 300000; // ms
109 AuthorizationState auth_state, proxy_auth_state;
113 static HttpWebRequest ()
115 defaultMaxResponseHeadersLength = 64 * 1024;
117 NetConfig config = ConfigurationSettings.GetConfig ("system.net/settings") as NetConfig;
118 if (config != null) {
119 int x = config.MaxResponseHeadersLength;
123 defaultMaxResponseHeadersLength = x;
133 HttpWebRequest (Uri uri)
135 this.requestUri = uri;
136 this.actualUri = uri;
137 this.proxy = GlobalProxySelection.Select;
138 this.webHeaders = new WebHeaderCollection (WebHeaderCollection.HeaderInfo.Request);
140 ResetAuthorization ();
143 [Obsolete ("Serialization is obsoleted for this type", false)]
144 protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
146 SerializationInfo info = serializationInfo;
148 requestUri = (Uri) info.GetValue ("requestUri", typeof (Uri));
149 actualUri = (Uri) info.GetValue ("actualUri", typeof (Uri));
150 allowAutoRedirect = info.GetBoolean ("allowAutoRedirect");
151 allowBuffering = info.GetBoolean ("allowBuffering");
152 certificates = (X509CertificateCollection) info.GetValue ("certificates", typeof (X509CertificateCollection));
153 connectionGroup = info.GetString ("connectionGroup");
154 contentLength = info.GetInt64 ("contentLength");
155 webHeaders = (WebHeaderCollection) info.GetValue ("webHeaders", typeof (WebHeaderCollection));
156 keepAlive = info.GetBoolean ("keepAlive");
157 maxAutoRedirect = info.GetInt32 ("maxAutoRedirect");
158 mediaType = info.GetString ("mediaType");
159 method = info.GetString ("method");
160 initialMethod = info.GetString ("initialMethod");
161 pipelined = info.GetBoolean ("pipelined");
162 version = (Version) info.GetValue ("version", typeof (Version));
163 proxy = (IWebProxy) info.GetValue ("proxy", typeof (IWebProxy));
164 sendChunked = info.GetBoolean ("sendChunked");
165 timeout = info.GetInt32 ("timeout");
166 redirects = info.GetInt32 ("redirects");
167 host = info.GetString ("host");
168 ResetAuthorization ();
171 void ResetAuthorization ()
173 auth_state = new AuthorizationState (this, false);
174 proxy_auth_state = new AuthorizationState (this, true);
179 public string Accept {
180 get { return webHeaders ["Accept"]; }
182 CheckRequestStarted ();
183 webHeaders.RemoveAndAdd ("Accept", value);
188 get { return actualUri; }
189 internal set { actualUri = value; } // Used by Ftp+proxy
192 public bool AllowAutoRedirect {
193 get { return allowAutoRedirect; }
194 set { this.allowAutoRedirect = value; }
197 public bool AllowWriteStreamBuffering {
198 get { return allowBuffering; }
199 set { allowBuffering = value; }
203 public virtual bool AllowReadStreamBuffering {
204 get { return allowBuffering; }
205 set { allowBuffering = value; }
209 static Exception GetMustImplement ()
211 return new NotImplementedException ();
214 public DecompressionMethods AutomaticDecompression
220 CheckRequestStarted ();
225 internal bool InternalAllowBuffering {
227 return (allowBuffering && (method != "HEAD" && method != "GET" &&
228 method != "MKCOL" && method != "CONNECT" &&
233 public X509CertificateCollection ClientCertificates {
235 if (certificates == null)
236 certificates = new X509CertificateCollection ();
242 throw GetMustImplement ();
246 public string Connection {
247 get { return webHeaders ["Connection"]; }
249 CheckRequestStarted ();
251 if (string.IsNullOrEmpty (value)) {
252 webHeaders.RemoveInternal ("Connection");
256 string val = value.ToLowerInvariant ();
257 if (val.Contains ("keep-alive") || val.Contains ("close"))
258 throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
261 value = value + ", Keep-Alive";
263 webHeaders.RemoveAndAdd ("Connection", value);
267 public override string ConnectionGroupName {
268 get { return connectionGroup; }
269 set { connectionGroup = value; }
272 public override long ContentLength {
273 get { return contentLength; }
275 CheckRequestStarted ();
277 throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
279 contentLength = value;
283 internal long InternalContentLength {
284 set { contentLength = value; }
287 internal bool ThrowOnError { get; set; }
289 public override string ContentType {
290 get { return webHeaders ["Content-Type"]; }
292 if (value == null || value.Trim().Length == 0) {
293 webHeaders.RemoveInternal ("Content-Type");
296 webHeaders.RemoveAndAdd ("Content-Type", value);
300 public HttpContinueDelegate ContinueDelegate {
301 get { return continueDelegate; }
302 set { continueDelegate = value; }
308 public CookieContainer CookieContainer {
309 get { return cookieContainer; }
310 set { cookieContainer = value; }
313 public override ICredentials Credentials {
314 get { return credentials; }
315 set { credentials = value; }
318 public DateTime Date {
320 string date = webHeaders ["Date"];
322 return DateTime.MinValue;
323 return DateTime.ParseExact (date, "r", CultureInfo.InvariantCulture).ToLocalTime ();
326 if (value.Equals (DateTime.MinValue))
327 webHeaders.RemoveInternal ("Date");
329 webHeaders.RemoveAndAdd ("Date", value.ToUniversalTime ().ToString ("r", CultureInfo.InvariantCulture));
336 public static new RequestCachePolicy DefaultCachePolicy
339 throw GetMustImplement ();
342 throw GetMustImplement ();
348 public static int DefaultMaximumErrorResponseLength
351 throw GetMustImplement ();
354 throw GetMustImplement ();
358 public string Expect {
359 get { return webHeaders ["Expect"]; }
361 CheckRequestStarted ();
364 val = val.Trim ().ToLower ();
366 if (val == null || val.Length == 0) {
367 webHeaders.RemoveInternal ("Expect");
371 if (val == "100-continue")
372 throw new ArgumentException ("100-Continue cannot be set with this property.",
374 webHeaders.RemoveAndAdd ("Expect", value);
381 public bool HaveResponse {
382 get { return haveResponse; }
385 public override WebHeaderCollection Headers {
386 get { return webHeaders; }
388 CheckRequestStarted ();
389 WebHeaderCollection newHeaders = new WebHeaderCollection (WebHeaderCollection.HeaderInfo.Request);
390 int count = value.Count;
391 for (int i = 0; i < count; i++)
392 newHeaders.Add (value.GetKey (i), value.Get (i));
394 webHeaders = newHeaders;
406 return actualUri.Authority;
411 throw new ArgumentNullException ("value");
413 if (!CheckValidHost (actualUri.Scheme, value))
414 throw new ArgumentException ("Invalid host: " + value);
420 static bool CheckValidHost (string scheme, string val)
428 int idx = val.IndexOf ('/');
433 if (IPAddress.TryParse (val, out ipaddr))
436 string u = scheme + "://" + val + "/";
437 return Uri.IsWellFormedUriString (u, UriKind.Absolute);
440 public DateTime IfModifiedSince {
442 string str = webHeaders ["If-Modified-Since"];
446 return MonoHttpDate.Parse (str);
447 } catch (Exception) {
452 CheckRequestStarted ();
454 webHeaders.SetInternal ("If-Modified-Since",
455 value.ToUniversalTime ().ToString ("r", null));
456 // TODO: check last param when using different locale
460 public bool KeepAlive {
469 public int MaximumAutomaticRedirections {
470 get { return maxAutoRedirect; }
473 throw new ArgumentException ("Must be > 0", "value");
475 maxAutoRedirect = value;
479 [MonoTODO ("Use this")]
480 public int MaximumResponseHeadersLength {
481 get { return maxResponseHeadersLength; }
482 set { maxResponseHeadersLength = value; }
485 [MonoTODO ("Use this")]
486 public static int DefaultMaximumResponseHeadersLength {
487 get { return defaultMaxResponseHeadersLength; }
488 set { defaultMaxResponseHeadersLength = value; }
491 public int ReadWriteTimeout {
492 get { return readWriteTimeout; }
495 throw new InvalidOperationException ("The request has already been sent.");
498 throw new ArgumentOutOfRangeException ("value", "Must be >= -1");
500 readWriteTimeout = value;
506 public int ContinueTimeout {
507 get { throw new NotImplementedException (); }
508 set { throw new NotImplementedException (); }
512 public string MediaType {
513 get { return mediaType; }
519 public override string Method {
520 get { return this.method; }
522 if (value == null || value.Trim () == "")
523 throw new ArgumentException ("not a valid method");
525 method = value.ToUpperInvariant ();
526 if (method != "HEAD" && method != "GET" && method != "POST" && method != "PUT" &&
527 method != "DELETE" && method != "CONNECT" && method != "TRACE" &&
534 public bool Pipelined {
535 get { return pipelined; }
536 set { pipelined = value; }
539 public override bool PreAuthenticate {
540 get { return preAuthenticate; }
541 set { preAuthenticate = value; }
544 public Version ProtocolVersion {
545 get { return version; }
547 if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
548 throw new ArgumentException ("value");
550 force_version = true;
555 public override IWebProxy Proxy {
556 get { return proxy; }
558 CheckRequestStarted ();
560 servicePoint = null; // we may need a new one
564 public string Referer {
565 get { return webHeaders ["Referer"]; }
567 CheckRequestStarted ();
568 if (value == null || value.Trim().Length == 0) {
569 webHeaders.RemoveInternal ("Referer");
572 webHeaders.SetInternal ("Referer", value);
576 public override Uri RequestUri {
577 get { return requestUri; }
580 public bool SendChunked {
581 get { return sendChunked; }
583 CheckRequestStarted ();
588 public ServicePoint ServicePoint {
589 get { return GetServicePoint (); }
592 internal ServicePoint ServicePointNoLock {
593 get { return servicePoint; }
596 [MonoTODO ("for portable library support")]
597 public virtual bool SupportsCookieContainer {
599 throw new NotImplementedException ();
603 public override int Timeout {
604 get { return timeout; }
607 throw new ArgumentOutOfRangeException ("value");
613 public string TransferEncoding {
614 get { return webHeaders ["Transfer-Encoding"]; }
616 CheckRequestStarted ();
619 val = val.Trim ().ToLower ();
621 if (val == null || val.Length == 0) {
622 webHeaders.RemoveInternal ("Transfer-Encoding");
626 if (val == "chunked")
627 throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
630 throw new ArgumentException ("SendChunked must be True", "value");
632 webHeaders.RemoveAndAdd ("Transfer-Encoding", value);
636 public override bool UseDefaultCredentials
638 get { return CredentialCache.DefaultCredentials == Credentials; }
639 set { Credentials = value ? CredentialCache.DefaultCredentials : null; }
642 public string UserAgent {
643 get { return webHeaders ["User-Agent"]; }
644 set { webHeaders.SetInternal ("User-Agent", value); }
647 bool unsafe_auth_blah;
648 public bool UnsafeAuthenticatedConnectionSharing
650 get { return unsafe_auth_blah; }
651 set { unsafe_auth_blah = value; }
654 internal bool GotRequestStream {
655 get { return gotRequestStream; }
658 internal bool ExpectContinue {
659 get { return expectContinue; }
660 set { expectContinue = value; }
663 internal Uri AuthUri {
664 get { return actualUri; }
667 internal bool ProxyQuery {
668 get { return servicePoint.UsesProxy && !servicePoint.UseConnect; }
673 internal ServicePoint GetServicePoint ()
676 if (hostChanged || servicePoint == null) {
677 servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
685 public void AddRange (int range)
687 AddRange ("bytes", (long) range);
690 public void AddRange (int from, int to)
692 AddRange ("bytes", (long) from, (long) to);
695 public void AddRange (string rangeSpecifier, int range)
697 AddRange (rangeSpecifier, (long) range);
700 public void AddRange (string rangeSpecifier, int from, int to)
702 AddRange (rangeSpecifier, (long) from, (long) to);
709 void AddRange (long range)
711 AddRange ("bytes", (long) range);
719 void AddRange (long from, long to)
721 AddRange ("bytes", from, to);
729 void AddRange (string rangeSpecifier, long range)
731 if (rangeSpecifier == null)
732 throw new ArgumentNullException ("rangeSpecifier");
733 if (!WebHeaderCollection.IsHeaderValue (rangeSpecifier))
734 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
736 string r = webHeaders ["Range"];
738 r = rangeSpecifier + "=";
740 string old_specifier = r.Substring (0, r.IndexOf ('='));
741 if (String.Compare (old_specifier, rangeSpecifier, StringComparison.OrdinalIgnoreCase) != 0)
742 throw new InvalidOperationException ("A different range specifier is already in use");
746 string n = range.ToString (CultureInfo.InvariantCulture);
751 webHeaders.RemoveAndAdd ("Range", r);
759 void AddRange (string rangeSpecifier, long from, long to)
761 if (rangeSpecifier == null)
762 throw new ArgumentNullException ("rangeSpecifier");
763 if (!WebHeaderCollection.IsHeaderValue (rangeSpecifier))
764 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
765 if (from > to || from < 0)
766 throw new ArgumentOutOfRangeException ("from");
768 throw new ArgumentOutOfRangeException ("to");
770 string r = webHeaders ["Range"];
772 r = rangeSpecifier + "=";
776 r = String.Format ("{0}{1}-{2}", r, from, to);
777 webHeaders.RemoveAndAdd ("Range", r);
781 public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
784 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
786 bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
788 if (method == null || !send)
789 throw new ProtocolViolationException ("Cannot send data when method is: " + method);
791 if (contentLength == -1 && !sendChunked && !allowBuffering && KeepAlive)
792 throw new ProtocolViolationException ("Content-Length not set");
794 string transferEncoding = TransferEncoding;
795 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
796 throw new ProtocolViolationException ("SendChunked should be true.");
800 if (getResponseCalled)
801 throw new InvalidOperationException ("The operation cannot be performed once the request has been submitted.");
803 if (asyncWrite != null) {
804 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
805 "method while a previous call is still in progress.");
808 asyncWrite = new WebAsyncResult (this, callback, state);
809 initialMethod = method;
811 if (writeStream != null) {
812 asyncWrite.SetCompleted (true, writeStream);
813 asyncWrite.DoCallback ();
818 gotRequestStream = true;
819 WebAsyncResult result = asyncWrite;
823 servicePoint = GetServicePoint ();
824 abortHandler = servicePoint.SendRequest (this, connectionGroup);
830 public override Stream EndGetRequestStream (IAsyncResult asyncResult)
832 if (asyncResult == null)
833 throw new ArgumentNullException ("asyncResult");
835 WebAsyncResult result = asyncResult as WebAsyncResult;
837 throw new ArgumentException ("Invalid IAsyncResult");
840 result.WaitUntilComplete ();
842 Exception e = result.Exception;
846 return result.WriteStream;
849 public override Stream GetRequestStream()
851 IAsyncResult asyncResult = asyncWrite;
852 if (asyncResult == null) {
853 asyncResult = BeginGetRequestStream (null, null);
854 asyncWrite = (WebAsyncResult) asyncResult;
857 if (!asyncResult.IsCompleted && !asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
859 throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
862 return EndGetRequestStream (asyncResult);
865 void CheckIfForceWrite ()
867 if (writeStream == null || writeStream.RequestWritten || !InternalAllowBuffering)
870 if (contentLength < 0 && writeStream.CanWrite == true && writeStream.WriteBufferLength < 0)
873 if (contentLength < 0 && writeStream.WriteBufferLength >= 0)
874 InternalContentLength = writeStream.WriteBufferLength;
876 if (contentLength < 0 && writeStream.CanWrite == true)
880 // This will write the POST/PUT if the write stream already has the expected
881 // amount of bytes in it (ContentLength) (bug #77753) or if the write stream
882 // contains data and it has been closed already (xamarin bug #1512).
884 if (writeStream.WriteBufferLength == contentLength || (contentLength == -1 && writeStream.CanWrite == false))
885 writeStream.WriteRequest ();
888 public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
891 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
894 throw new ProtocolViolationException ("Method is null.");
896 string transferEncoding = TransferEncoding;
897 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
898 throw new ProtocolViolationException ("SendChunked should be true.");
900 Monitor.Enter (locker);
901 getResponseCalled = true;
902 if (asyncRead != null && !haveResponse) {
903 Monitor.Exit (locker);
904 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
905 "method while a previous call is still in progress.");
908 CheckIfForceWrite ();
909 asyncRead = new WebAsyncResult (this, callback, state);
910 WebAsyncResult aread = asyncRead;
911 initialMethod = method;
913 Exception saved = saved_exc;
914 if (webResponse != null) {
915 Monitor.Exit (locker);
917 aread.SetCompleted (true, webResponse);
919 aread.SetCompleted (true, saved);
923 } else if (saved != null) {
924 Monitor.Exit (locker);
925 aread.SetCompleted (true, saved);
934 servicePoint = GetServicePoint ();
935 abortHandler = servicePoint.SendRequest (this, connectionGroup);
938 Monitor.Exit (locker);
942 public override WebResponse EndGetResponse (IAsyncResult asyncResult)
944 if (asyncResult == null)
945 throw new ArgumentNullException ("asyncResult");
947 WebAsyncResult result = asyncResult as WebAsyncResult;
949 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
951 if (!result.WaitUntilComplete (timeout, false)) {
953 throw new WebException("The request timed out", WebExceptionStatus.Timeout);
956 if (result.GotException)
957 throw result.Exception;
959 return result.Response;
963 public Stream EndGetRequestStream (IAsyncResult asyncResult, out TransportContext transportContext)
965 transportContext = null;
966 return EndGetRequestStream (asyncResult);
970 public override WebResponse GetResponse()
972 WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
973 return EndGetResponse (result);
976 internal bool FinishedReading {
977 get { return finished_reading; }
978 set { finished_reading = value; }
981 internal bool Aborted {
982 get { return Interlocked.CompareExchange (ref aborted, 0, 0) == 1; }
985 public override void Abort ()
987 if (Interlocked.CompareExchange (ref aborted, 1, 0) == 1)
990 if (haveResponse && finished_reading)
994 if (abortHandler != null) {
996 abortHandler (this, EventArgs.Empty);
997 } catch (Exception) {}
1001 if (asyncWrite != null) {
1002 WebAsyncResult r = asyncWrite;
1003 if (!r.IsCompleted) {
1005 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
1006 r.SetCompleted (false, wexc);
1013 if (asyncRead != null) {
1014 WebAsyncResult r = asyncRead;
1015 if (!r.IsCompleted) {
1017 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
1018 r.SetCompleted (false, wexc);
1025 if (writeStream != null) {
1027 writeStream.Close ();
1032 if (webResponse != null) {
1034 webResponse.Close ();
1040 void ISerializable.GetObjectData (SerializationInfo serializationInfo,
1041 StreamingContext streamingContext)
1043 GetObjectData (serializationInfo, streamingContext);
1046 protected override void GetObjectData (SerializationInfo serializationInfo,
1047 StreamingContext streamingContext)
1049 SerializationInfo info = serializationInfo;
1051 info.AddValue ("requestUri", requestUri, typeof (Uri));
1052 info.AddValue ("actualUri", actualUri, typeof (Uri));
1053 info.AddValue ("allowAutoRedirect", allowAutoRedirect);
1054 info.AddValue ("allowBuffering", allowBuffering);
1055 info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
1056 info.AddValue ("connectionGroup", connectionGroup);
1057 info.AddValue ("contentLength", contentLength);
1058 info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
1059 info.AddValue ("keepAlive", keepAlive);
1060 info.AddValue ("maxAutoRedirect", maxAutoRedirect);
1061 info.AddValue ("mediaType", mediaType);
1062 info.AddValue ("method", method);
1063 info.AddValue ("initialMethod", initialMethod);
1064 info.AddValue ("pipelined", pipelined);
1065 info.AddValue ("version", version, typeof (Version));
1066 info.AddValue ("proxy", proxy, typeof (IWebProxy));
1067 info.AddValue ("sendChunked", sendChunked);
1068 info.AddValue ("timeout", timeout);
1069 info.AddValue ("redirects", redirects);
1070 info.AddValue ("host", host);
1073 void CheckRequestStarted ()
1076 throw new InvalidOperationException ("request started");
1079 internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
1081 if (continueDelegate != null)
1082 continueDelegate (statusCode, headers);
1085 bool Redirect (WebAsyncResult result, HttpStatusCode code)
1089 string uriString = null;
1091 case HttpStatusCode.Ambiguous: // 300
1092 e = new WebException ("Ambiguous redirect.");
1094 case HttpStatusCode.MovedPermanently: // 301
1095 case HttpStatusCode.Redirect: // 302
1096 if (method == "POST")
1099 case HttpStatusCode.TemporaryRedirect: // 307
1101 case HttpStatusCode.SeeOther: //303
1104 case HttpStatusCode.NotModified: // 304
1106 case HttpStatusCode.UseProxy: // 305
1107 e = new NotImplementedException ("Proxy support not available.");
1109 case HttpStatusCode.Unused: // 306
1111 e = new ProtocolViolationException ("Invalid status code: " + (int) code);
1118 //contentLength = -1;
1119 //bodyBufferLength = 0;
1120 //bodyBuffer = null;
1121 uriString = webResponse.Headers ["Location"];
1123 if (uriString == null)
1124 throw new WebException ("No Location header found for " + (int) code,
1125 WebExceptionStatus.ProtocolError);
1127 Uri prev = actualUri;
1129 actualUri = new Uri (actualUri, uriString);
1130 } catch (Exception) {
1131 throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
1132 uriString, (int) code),
1133 WebExceptionStatus.ProtocolError);
1136 hostChanged = (actualUri.Scheme != prev.Scheme || Host != prev.Authority);
1140 string GetHeaders ()
1142 bool continue100 = false;
1145 webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
1146 webHeaders.RemoveInternal ("Content-Length");
1147 } else if (contentLength != -1) {
1148 if (auth_state.NtlmAuthState == NtlmAuthState.Challenge || proxy_auth_state.NtlmAuthState == NtlmAuthState.Challenge) {
1149 // We don't send any body with the NTLM Challenge request.
1150 webHeaders.SetInternal ("Content-Length", "0");
1152 if (contentLength > 0)
1155 webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
1157 webHeaders.RemoveInternal ("Transfer-Encoding");
1159 webHeaders.RemoveInternal ("Content-Length");
1162 if (actualVersion == HttpVersion.Version11 && continue100 &&
1163 servicePoint.SendContinue) { // RFC2616 8.2.3
1164 webHeaders.RemoveAndAdd ("Expect" , "100-continue");
1165 expectContinue = true;
1167 webHeaders.RemoveInternal ("Expect");
1168 expectContinue = false;
1171 bool proxy_query = ProxyQuery;
1172 string connectionHeader = (proxy_query) ? "Proxy-Connection" : "Connection";
1173 webHeaders.RemoveInternal ((!proxy_query) ? "Proxy-Connection" : "Connection");
1174 Version proto_version = servicePoint.ProtocolVersion;
1175 bool spoint10 = (proto_version == null || proto_version == HttpVersion.Version10);
1177 if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
1178 if (webHeaders[connectionHeader] == null
1179 || webHeaders[connectionHeader].IndexOf ("keep-alive", StringComparison.OrdinalIgnoreCase) == -1)
1180 webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
1181 } else if (!keepAlive && version == HttpVersion.Version11) {
1182 webHeaders.RemoveAndAdd (connectionHeader, "close");
1185 webHeaders.SetInternal ("Host", Host);
1186 if (cookieContainer != null) {
1187 string cookieHeader = cookieContainer.GetCookieHeader (actualUri);
1188 if (cookieHeader != "")
1189 webHeaders.RemoveAndAdd ("Cookie", cookieHeader);
1191 webHeaders.RemoveInternal ("Cookie");
1194 string accept_encoding = null;
1195 if ((auto_decomp & DecompressionMethods.GZip) != 0)
1196 accept_encoding = "gzip";
1197 if ((auto_decomp & DecompressionMethods.Deflate) != 0)
1198 accept_encoding = accept_encoding != null ? "gzip, deflate" : "deflate";
1199 if (accept_encoding != null)
1200 webHeaders.RemoveAndAdd ("Accept-Encoding", accept_encoding);
1202 if (!usedPreAuth && preAuthenticate)
1203 DoPreAuthenticate ();
1205 return webHeaders.ToString ();
1208 void DoPreAuthenticate ()
1210 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1211 ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
1212 Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
1216 webHeaders.RemoveInternal ("Proxy-Authorization");
1217 webHeaders.RemoveInternal ("Authorization");
1218 string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
1219 webHeaders [authHeader] = auth.Message;
1223 internal void SetWriteStreamError (WebExceptionStatus status, Exception exc)
1228 WebAsyncResult r = asyncWrite;
1236 msg = "Error: " + status;
1237 wex = new WebException (msg, status);
1239 msg = String.Format ("Error: {0} ({1})", status, exc.Message);
1240 wex = new WebException (msg, exc, status);
1242 r.SetCompleted (false, wex);
1247 internal byte[] GetRequestHeaders ()
1249 StringBuilder req = new StringBuilder ();
1252 query = actualUri.PathAndQuery;
1254 query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
1256 actualUri.PathAndQuery);
1259 if (!force_version && servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
1260 actualVersion = servicePoint.ProtocolVersion;
1262 actualVersion = version;
1265 req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
1266 actualVersion.Major, actualVersion.Minor);
1267 req.Append (GetHeaders ());
1268 string reqstr = req.ToString ();
1269 return Encoding.UTF8.GetBytes (reqstr);
1272 internal void SetWriteStream (WebConnectionStream stream)
1277 writeStream = stream;
1278 if (bodyBuffer != null) {
1279 webHeaders.RemoveInternal ("Transfer-Encoding");
1280 contentLength = bodyBufferLength;
1281 writeStream.SendChunked = false;
1284 byte[] requestHeaders = GetRequestHeaders ();
1285 WebAsyncResult result = new WebAsyncResult (new AsyncCallback (SetWriteStreamCB), null);
1286 writeStream.SetHeadersAsync (requestHeaders, result);
1289 void SetWriteStreamCB(IAsyncResult ar)
1291 WebAsyncResult result = ar as WebAsyncResult;
1293 if (result.Exception != null) {
1294 WebException wexc = result.Exception as WebException;
1296 SetWriteStreamError (wexc.Status, wexc);
1299 SetWriteStreamError (WebExceptionStatus.SendFailure, result.Exception);
1305 if (bodyBuffer != null) {
1306 // The body has been written and buffered. The request "user"
1307 // won't write it again, so we must do it.
1308 if (auth_state.NtlmAuthState != NtlmAuthState.Challenge && proxy_auth_state.NtlmAuthState != NtlmAuthState.Challenge) {
1309 // FIXME: this is a blocking call on the thread pool that could lead to thread pool exhaustion
1310 writeStream.Write (bodyBuffer, 0, bodyBufferLength);
1312 writeStream.Close ();
1314 } else if (method != "HEAD" && method != "GET" && method != "MKCOL" && method != "CONNECT" &&
1315 method != "TRACE") {
1316 if (getResponseCalled && !writeStream.RequestWritten)
1317 // FIXME: this is a blocking call on the thread pool that could lead to thread pool exhaustion
1318 writeStream.WriteRequest ();
1321 if (asyncWrite != null) {
1322 asyncWrite.SetCompleted (false, writeStream);
1323 asyncWrite.DoCallback ();
1328 internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
1333 string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
1334 WebAsyncResult r = asyncRead;
1339 if (e is WebException) {
1340 wexc = (WebException) e;
1342 wexc = new WebException (msg, e, status, null);
1345 if (!r.IsCompleted) {
1346 r.SetCompleted (false, wexc);
1348 } else if (r == asyncWrite) {
1351 haveResponse = true;
1355 haveResponse = true;
1361 void CheckSendError (WebConnectionData data)
1363 // Got here, but no one called GetResponse
1364 int status = data.StatusCode;
1365 if (status < 400 || status == 401 || status == 407)
1368 if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
1369 // The request has not been completely sent and we got here!
1370 // We should probably just close and cause an error in any case,
1371 saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse);
1372 if (allowBuffering || sendChunked || writeStream.totalWritten >= contentLength) {
1373 webResponse.ReadAll ();
1375 writeStream.IgnoreIOErrors = true;
1380 bool HandleNtlmAuth (WebAsyncResult r)
1382 bool isProxy = webResponse.StatusCode == HttpStatusCode.ProxyAuthenticationRequired;
1383 if ((isProxy ? proxy_auth_state.NtlmAuthState : auth_state.NtlmAuthState) == NtlmAuthState.None)
1386 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1388 WebConnection cnc = wce.Connection;
1389 cnc.PriorityRequest = this;
1390 ICredentials creds = !isProxy ? credentials : proxy.Credentials;
1391 if (creds != null) {
1392 cnc.NtlmCredential = creds.GetCredential (requestUri, "NTLM");
1393 cnc.UnsafeAuthenticatedConnectionSharing = unsafe_auth_blah;
1397 finished_reading = false;
1398 haveResponse = false;
1399 webResponse.ReadAll ();
1404 internal void SetResponseData (WebConnectionData data)
1408 if (data.stream != null)
1409 data.stream.Close ();
1413 WebException wexc = null;
1415 webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
1416 } catch (Exception e) {
1417 wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null);
1418 if (data.stream != null)
1419 data.stream.Close ();
1422 if (wexc == null && (method == "POST" || method == "PUT")) {
1423 CheckSendError (data);
1424 if (saved_exc != null)
1425 wexc = (WebException) saved_exc;
1428 WebAsyncResult r = asyncRead;
1430 bool forced = false;
1431 if (r == null && webResponse != null) {
1432 // This is a forced completion (302, 204)...
1434 r = new WebAsyncResult (null, null);
1435 r.SetCompleted (false, webResponse);
1440 haveResponse = true;
1442 r.SetCompleted (false, wexc);
1447 bool isProxy = ProxyQuery && !proxy.IsBypassed (actualUri);
1451 redirected = CheckFinalStatus (r);
1453 if ((isProxy ? proxy_auth_state.IsNtlmAuthenticated : auth_state.IsNtlmAuthenticated) &&
1454 webResponse != null && (int)webResponse.StatusCode < 400) {
1455 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1457 WebConnection cnc = wce.Connection;
1458 cnc.NtlmAuthenticated = true;
1462 // clear internal buffer so that it does not
1463 // hold possible big buffer (bug #397627)
1464 if (writeStream != null)
1465 writeStream.KillBuffer ();
1467 haveResponse = true;
1468 r.SetCompleted (false, webResponse);
1471 if (webResponse != null) {
1472 if (HandleNtlmAuth (r))
1474 webResponse.Close ();
1476 finished_reading = false;
1477 haveResponse = false;
1480 servicePoint = GetServicePoint ();
1481 abortHandler = servicePoint.SendRequest (this, connectionGroup);
1483 } catch (WebException wexc2) {
1486 haveResponse = true;
1488 r.SetCompleted (false, wexc2);
1491 } catch (Exception ex) {
1492 wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
1495 haveResponse = true;
1497 r.SetCompleted (false, wexc);
1505 struct AuthorizationState
1507 readonly HttpWebRequest request;
1508 readonly bool isProxy;
1510 NtlmAuthState ntlm_auth_state;
1512 public bool IsCompleted {
1513 get { return isCompleted; }
1516 public NtlmAuthState NtlmAuthState {
1517 get { return ntlm_auth_state; }
1520 public bool IsNtlmAuthenticated {
1521 get { return isCompleted && ntlm_auth_state != NtlmAuthState.None; }
1524 public AuthorizationState (HttpWebRequest request, bool isProxy)
1526 this.request = request;
1527 this.isProxy = isProxy;
1528 isCompleted = false;
1529 ntlm_auth_state = NtlmAuthState.None;
1532 public bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1534 isCompleted = false;
1535 if (code == HttpStatusCode.Unauthorized && request.credentials == null)
1538 // FIXME: This should never happen!
1539 if (isProxy != (code == HttpStatusCode.ProxyAuthenticationRequired))
1542 if (isProxy && (request.proxy == null || request.proxy.Credentials == null))
1545 string [] authHeaders = response.Headers.GetValues_internal (isProxy ? "Proxy-Authenticate" : "WWW-Authenticate", false);
1546 if (authHeaders == null || authHeaders.Length == 0)
1549 ICredentials creds = (!isProxy) ? request.credentials : request.proxy.Credentials;
1550 Authorization auth = null;
1551 foreach (string authHeader in authHeaders) {
1552 auth = AuthenticationManager.Authenticate (authHeader, request, creds);
1558 request.webHeaders [isProxy ? "Proxy-Authorization" : "Authorization"] = auth.Message;
1559 isCompleted = auth.Complete;
1560 bool is_ntlm = (auth.Module.AuthenticationType == "NTLM");
1562 ntlm_auth_state = (NtlmAuthState)((int) ntlm_auth_state + 1);
1566 public void Reset ()
1568 isCompleted = false;
1569 ntlm_auth_state = NtlmAuthState.None;
1570 request.webHeaders.RemoveInternal (isProxy ? "Proxy-Authorization" : "Authorization");
1573 public override string ToString ()
1575 return string.Format ("{0}AuthState [{1}:{2}]", isProxy ? "Proxy" : "", isCompleted, ntlm_auth_state);
1579 bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1581 bool isProxy = code == HttpStatusCode.ProxyAuthenticationRequired;
1582 return isProxy ? proxy_auth_state.CheckAuthorization (response, code) : auth_state.CheckAuthorization (response, code);
1585 // Returns true if redirected
1586 bool CheckFinalStatus (WebAsyncResult result)
1588 if (result.GotException) {
1590 throw result.Exception;
1593 Exception throwMe = result.Exception;
1595 HttpWebResponse resp = result.Response;
1596 WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
1597 HttpStatusCode code = 0;
1598 if (throwMe == null && webResponse != null) {
1599 code = webResponse.StatusCode;
1600 if ((!auth_state.IsCompleted && code == HttpStatusCode.Unauthorized && credentials != null) ||
1601 (ProxyQuery && !proxy_auth_state.IsCompleted && code == HttpStatusCode.ProxyAuthenticationRequired)) {
1602 if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
1603 // Keep the written body, so it can be rewritten in the retry
1604 if (InternalAllowBuffering) {
1605 // NTLM: This is to avoid sending data in the 'challenge' request
1606 // We save it in the first request (first 401), don't send anything
1607 // in the challenge request and send it in the response request along
1608 // with the buffers kept form the first request.
1609 if (auth_state.NtlmAuthState == NtlmAuthState.Challenge || proxy_auth_state.NtlmAuthState == NtlmAuthState.Challenge) {
1610 bodyBuffer = writeStream.WriteBuffer;
1611 bodyBufferLength = writeStream.WriteBufferLength;
1614 } else if (method != "PUT" && method != "POST") {
1622 writeStream.InternalClose ();
1624 webResponse.Close ();
1628 throw new WebException ("This request requires buffering " +
1629 "of data for authentication or " +
1630 "redirection to be sucessful.");
1635 if ((int) code >= 400) {
1636 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1637 (int) code, webResponse.StatusDescription);
1638 throwMe = new WebException (err, null, protoError, webResponse);
1639 webResponse.ReadAll ();
1640 } else if ((int) code == 304 && allowAutoRedirect) {
1641 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1642 (int) code, webResponse.StatusDescription);
1643 throwMe = new WebException (err, null, protoError, webResponse);
1644 } else if ((int) code >= 300 && allowAutoRedirect && redirects >= maxAutoRedirect) {
1645 throwMe = new WebException ("Max. redirections exceeded.", null,
1646 protoError, webResponse);
1647 webResponse.ReadAll ();
1652 if (throwMe == null) {
1655 if (allowAutoRedirect && c >= 300) {
1656 b = Redirect (result, code);
1657 if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
1658 bodyBuffer = writeStream.WriteBuffer;
1659 bodyBufferLength = writeStream.WriteBufferLength;
1661 if (b && !unsafe_auth_blah) {
1662 auth_state.Reset ();
1663 proxy_auth_state.Reset ();
1667 if (resp != null && c >= 300 && c != 304)
1676 if (writeStream != null) {
1677 writeStream.InternalClose ();
1686 internal bool ReuseConnection {
1691 internal WebConnection StoredConnection;