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; }
203 public virtual bool AllowReadStreamBuffering {
204 get { return false; }
207 throw new InvalidOperationException ();
211 static Exception GetMustImplement ()
213 return new NotImplementedException ();
216 public DecompressionMethods AutomaticDecompression
222 CheckRequestStarted ();
227 internal bool InternalAllowBuffering {
229 return (allowBuffering && (method != "HEAD" && method != "GET" &&
230 method != "MKCOL" && method != "CONNECT" &&
235 public X509CertificateCollection ClientCertificates {
237 if (certificates == null)
238 certificates = new X509CertificateCollection ();
244 throw GetMustImplement ();
248 public string Connection {
249 get { return webHeaders ["Connection"]; }
251 CheckRequestStarted ();
253 if (string.IsNullOrEmpty (value)) {
254 webHeaders.RemoveInternal ("Connection");
258 string val = value.ToLowerInvariant ();
259 if (val.Contains ("keep-alive") || val.Contains ("close"))
260 throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
263 value = value + ", Keep-Alive";
265 webHeaders.RemoveAndAdd ("Connection", value);
269 public override string ConnectionGroupName {
270 get { return connectionGroup; }
271 set { connectionGroup = value; }
274 public override long ContentLength {
275 get { return contentLength; }
277 CheckRequestStarted ();
279 throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
281 contentLength = value;
282 haveContentLength = true;
286 internal long InternalContentLength {
287 set { contentLength = value; }
290 internal bool ThrowOnError { get; set; }
292 public override string ContentType {
293 get { return webHeaders ["Content-Type"]; }
295 if (value == null || value.Trim().Length == 0) {
296 webHeaders.RemoveInternal ("Content-Type");
299 webHeaders.RemoveAndAdd ("Content-Type", value);
303 public HttpContinueDelegate ContinueDelegate {
304 get { return continueDelegate; }
305 set { continueDelegate = value; }
309 public CookieContainer CookieContainer {
310 get { return cookieContainer; }
311 set { cookieContainer = value; }
314 public override ICredentials Credentials {
315 get { return credentials; }
316 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));
335 public static new RequestCachePolicy DefaultCachePolicy
338 throw GetMustImplement ();
341 throw GetMustImplement ();
347 public static int DefaultMaximumErrorResponseLength
350 throw GetMustImplement ();
353 throw GetMustImplement ();
357 public string Expect {
358 get { return webHeaders ["Expect"]; }
360 CheckRequestStarted ();
363 val = val.Trim ().ToLower ();
365 if (val == null || val.Length == 0) {
366 webHeaders.RemoveInternal ("Expect");
370 if (val == "100-continue")
371 throw new ArgumentException ("100-Continue cannot be set with this property.",
373 webHeaders.RemoveAndAdd ("Expect", value);
378 public bool HaveResponse {
379 get { return haveResponse; }
382 public override WebHeaderCollection Headers {
383 get { return webHeaders; }
385 CheckRequestStarted ();
386 WebHeaderCollection newHeaders = new WebHeaderCollection (WebHeaderCollection.HeaderInfo.Request);
387 int count = value.Count;
388 for (int i = 0; i < count; i++)
389 newHeaders.Add (value.GetKey (i), value.Get (i));
391 webHeaders = newHeaders;
399 return actualUri.Authority;
404 throw new ArgumentNullException ("value");
406 if (!CheckValidHost (actualUri.Scheme, value))
407 throw new ArgumentException ("Invalid host: " + value);
413 static bool CheckValidHost (string scheme, string val)
421 int idx = val.IndexOf ('/');
426 if (IPAddress.TryParse (val, out ipaddr))
429 string u = scheme + "://" + val + "/";
430 return Uri.IsWellFormedUriString (u, UriKind.Absolute);
433 public DateTime IfModifiedSince {
435 string str = webHeaders ["If-Modified-Since"];
439 return MonoHttpDate.Parse (str);
440 } catch (Exception) {
445 CheckRequestStarted ();
447 webHeaders.SetInternal ("If-Modified-Since",
448 value.ToUniversalTime ().ToString ("r", null));
449 // TODO: check last param when using different locale
453 public bool KeepAlive {
462 public int MaximumAutomaticRedirections {
463 get { return maxAutoRedirect; }
466 throw new ArgumentException ("Must be > 0", "value");
468 maxAutoRedirect = value;
472 [MonoTODO ("Use this")]
473 public int MaximumResponseHeadersLength {
474 get { return maxResponseHeadersLength; }
475 set { maxResponseHeadersLength = value; }
478 [MonoTODO ("Use this")]
479 public static int DefaultMaximumResponseHeadersLength {
480 get { return defaultMaxResponseHeadersLength; }
481 set { defaultMaxResponseHeadersLength = value; }
484 public int ReadWriteTimeout {
485 get { return readWriteTimeout; }
488 throw new InvalidOperationException ("The request has already been sent.");
491 throw new ArgumentOutOfRangeException ("value", "Must be >= -1");
493 readWriteTimeout = value;
498 public int ContinueTimeout {
499 get { throw new NotImplementedException (); }
500 set { throw new NotImplementedException (); }
503 public string MediaType {
504 get { return mediaType; }
510 public override string Method {
511 get { return this.method; }
513 if (value == null || value.Trim () == "")
514 throw new ArgumentException ("not a valid method");
516 method = value.ToUpperInvariant ();
517 if (method != "HEAD" && method != "GET" && method != "POST" && method != "PUT" &&
518 method != "DELETE" && method != "CONNECT" && method != "TRACE" &&
525 public bool Pipelined {
526 get { return pipelined; }
527 set { pipelined = value; }
530 public override bool PreAuthenticate {
531 get { return preAuthenticate; }
532 set { preAuthenticate = value; }
535 public Version ProtocolVersion {
536 get { return version; }
538 if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
539 throw new ArgumentException ("value");
541 force_version = true;
546 public override IWebProxy Proxy {
547 get { return proxy; }
549 CheckRequestStarted ();
551 servicePoint = null; // we may need a new one
555 public string Referer {
556 get { return webHeaders ["Referer"]; }
558 CheckRequestStarted ();
559 if (value == null || value.Trim().Length == 0) {
560 webHeaders.RemoveInternal ("Referer");
563 webHeaders.SetInternal ("Referer", value);
567 public override Uri RequestUri {
568 get { return requestUri; }
571 public bool SendChunked {
572 get { return sendChunked; }
574 CheckRequestStarted ();
579 public ServicePoint ServicePoint {
580 get { return GetServicePoint (); }
583 internal ServicePoint ServicePointNoLock {
584 get { return servicePoint; }
586 public virtual bool SupportsCookieContainer {
588 // The managed implementation supports the cookie container
589 // it is only Silverlight that returns false here
593 public override int Timeout {
594 get { return timeout; }
597 throw new ArgumentOutOfRangeException ("value");
603 public string TransferEncoding {
604 get { return webHeaders ["Transfer-Encoding"]; }
606 CheckRequestStarted ();
609 val = val.Trim ().ToLower ();
611 if (val == null || val.Length == 0) {
612 webHeaders.RemoveInternal ("Transfer-Encoding");
616 if (val == "chunked")
617 throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
620 throw new ArgumentException ("SendChunked must be True", "value");
622 webHeaders.RemoveAndAdd ("Transfer-Encoding", value);
626 public override bool UseDefaultCredentials
628 get { return CredentialCache.DefaultCredentials == Credentials; }
629 set { Credentials = value ? CredentialCache.DefaultCredentials : null; }
632 public string UserAgent {
633 get { return webHeaders ["User-Agent"]; }
634 set { webHeaders.SetInternal ("User-Agent", value); }
637 bool unsafe_auth_blah;
638 public bool UnsafeAuthenticatedConnectionSharing
640 get { return unsafe_auth_blah; }
641 set { unsafe_auth_blah = value; }
644 internal bool GotRequestStream {
645 get { return gotRequestStream; }
648 internal bool ExpectContinue {
649 get { return expectContinue; }
650 set { expectContinue = value; }
653 internal Uri AuthUri {
654 get { return actualUri; }
657 internal bool ProxyQuery {
658 get { return servicePoint.UsesProxy && !servicePoint.UseConnect; }
663 internal ServicePoint GetServicePoint ()
666 if (hostChanged || servicePoint == null) {
667 servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
675 public void AddRange (int range)
677 AddRange ("bytes", (long) range);
680 public void AddRange (int from, int to)
682 AddRange ("bytes", (long) from, (long) to);
685 public void AddRange (string rangeSpecifier, int range)
687 AddRange (rangeSpecifier, (long) range);
690 public void AddRange (string rangeSpecifier, int from, int to)
692 AddRange (rangeSpecifier, (long) from, (long) to);
695 void AddRange (long range)
697 AddRange ("bytes", (long) range);
701 void AddRange (long from, long to)
703 AddRange ("bytes", from, to);
707 void AddRange (string rangeSpecifier, long range)
709 if (rangeSpecifier == null)
710 throw new ArgumentNullException ("rangeSpecifier");
711 if (!WebHeaderCollection.IsHeaderValue (rangeSpecifier))
712 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
714 string r = webHeaders ["Range"];
716 r = rangeSpecifier + "=";
718 string old_specifier = r.Substring (0, r.IndexOf ('='));
719 if (String.Compare (old_specifier, rangeSpecifier, StringComparison.OrdinalIgnoreCase) != 0)
720 throw new InvalidOperationException ("A different range specifier is already in use");
724 string n = range.ToString (CultureInfo.InvariantCulture);
729 webHeaders.RemoveAndAdd ("Range", r);
733 void AddRange (string rangeSpecifier, long from, long to)
735 if (rangeSpecifier == null)
736 throw new ArgumentNullException ("rangeSpecifier");
737 if (!WebHeaderCollection.IsHeaderValue (rangeSpecifier))
738 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
739 if (from > to || from < 0)
740 throw new ArgumentOutOfRangeException ("from");
742 throw new ArgumentOutOfRangeException ("to");
744 string r = webHeaders ["Range"];
746 r = rangeSpecifier + "=";
750 r = String.Format ("{0}{1}-{2}", r, from, to);
751 webHeaders.RemoveAndAdd ("Range", r);
755 public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
758 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
760 bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
762 if (method == null || !send)
763 throw new ProtocolViolationException ("Cannot send data when method is: " + method);
765 if (contentLength == -1 && !sendChunked && !allowBuffering && KeepAlive)
766 throw new ProtocolViolationException ("Content-Length not set");
768 string transferEncoding = TransferEncoding;
769 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
770 throw new ProtocolViolationException ("SendChunked should be true.");
774 if (getResponseCalled)
775 throw new InvalidOperationException ("The operation cannot be performed once the request has been submitted.");
777 if (asyncWrite != null) {
778 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
779 "method while a previous call is still in progress.");
782 asyncWrite = new WebAsyncResult (this, callback, state);
783 initialMethod = method;
785 if (writeStream != null) {
786 asyncWrite.SetCompleted (true, writeStream);
787 asyncWrite.DoCallback ();
792 gotRequestStream = true;
793 WebAsyncResult result = asyncWrite;
797 servicePoint = GetServicePoint ();
798 abortHandler = servicePoint.SendRequest (this, connectionGroup);
804 public override Stream EndGetRequestStream (IAsyncResult asyncResult)
806 if (asyncResult == null)
807 throw new ArgumentNullException ("asyncResult");
809 WebAsyncResult result = asyncResult as WebAsyncResult;
811 throw new ArgumentException ("Invalid IAsyncResult");
814 result.WaitUntilComplete ();
816 Exception e = result.Exception;
820 return result.WriteStream;
823 public override Stream GetRequestStream()
825 IAsyncResult asyncResult = asyncWrite;
826 if (asyncResult == null) {
827 asyncResult = BeginGetRequestStream (null, null);
828 asyncWrite = (WebAsyncResult) asyncResult;
831 if (!asyncResult.IsCompleted && !asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
833 throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
836 return EndGetRequestStream (asyncResult);
839 bool CheckIfForceWrite (SimpleAsyncResult result)
841 if (writeStream == null || writeStream.RequestWritten || !InternalAllowBuffering)
843 if (contentLength < 0 && writeStream.CanWrite == true && writeStream.WriteBufferLength < 0)
846 if (contentLength < 0 && writeStream.WriteBufferLength >= 0)
847 InternalContentLength = writeStream.WriteBufferLength;
849 // This will write the POST/PUT if the write stream already has the expected
850 // amount of bytes in it (ContentLength) (bug #77753) or if the write stream
851 // contains data and it has been closed already (xamarin bug #1512).
853 if (writeStream.WriteBufferLength == contentLength || (contentLength == -1 && writeStream.CanWrite == false))
854 return writeStream.WriteRequestAsync (result);
859 public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
862 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
865 throw new ProtocolViolationException ("Method is null.");
867 string transferEncoding = TransferEncoding;
868 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
869 throw new ProtocolViolationException ("SendChunked should be true.");
871 Monitor.Enter (locker);
872 getResponseCalled = true;
873 if (asyncRead != null && !haveResponse) {
874 Monitor.Exit (locker);
875 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
876 "method while a previous call is still in progress.");
879 asyncRead = new WebAsyncResult (this, callback, state);
880 WebAsyncResult aread = asyncRead;
881 initialMethod = method;
883 SimpleAsyncResult.RunWithLock (locker, CheckIfForceWrite, inner => {
884 var synch = inner.CompletedSynchronously;
886 if (inner.GotException) {
887 aread.SetCompleted (synch, inner.Exception);
893 Exception saved = saved_exc;
894 if (webResponse != null) {
896 aread.SetCompleted (synch, webResponse);
898 aread.SetCompleted (synch, saved);
902 } else if (saved != null) {
903 aread.SetCompleted (synch, saved);
912 servicePoint = GetServicePoint ();
913 abortHandler = servicePoint.SendRequest (this, connectionGroup);
920 public override WebResponse EndGetResponse (IAsyncResult asyncResult)
922 if (asyncResult == null)
923 throw new ArgumentNullException ("asyncResult");
925 WebAsyncResult result = asyncResult as WebAsyncResult;
927 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
929 if (!result.WaitUntilComplete (timeout, false)) {
931 throw new WebException("The request timed out", WebExceptionStatus.Timeout);
934 if (result.GotException)
935 throw result.Exception;
937 return result.Response;
940 public Stream EndGetRequestStream (IAsyncResult asyncResult, out TransportContext transportContext)
942 transportContext = null;
943 return EndGetRequestStream (asyncResult);
946 public override WebResponse GetResponse()
948 WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
949 return EndGetResponse (result);
952 internal bool FinishedReading {
953 get { return finished_reading; }
954 set { finished_reading = value; }
957 internal bool Aborted {
958 get { return Interlocked.CompareExchange (ref aborted, 0, 0) == 1; }
961 public override void Abort ()
963 if (Interlocked.CompareExchange (ref aborted, 1, 0) == 1)
966 if (haveResponse && finished_reading)
970 if (abortHandler != null) {
972 abortHandler (this, EventArgs.Empty);
973 } catch (Exception) {}
977 if (asyncWrite != null) {
978 WebAsyncResult r = asyncWrite;
979 if (!r.IsCompleted) {
981 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
982 r.SetCompleted (false, wexc);
989 if (asyncRead != null) {
990 WebAsyncResult r = asyncRead;
991 if (!r.IsCompleted) {
993 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
994 r.SetCompleted (false, wexc);
1001 if (writeStream != null) {
1003 writeStream.Close ();
1008 if (webResponse != null) {
1010 webResponse.Close ();
1016 void ISerializable.GetObjectData (SerializationInfo serializationInfo,
1017 StreamingContext streamingContext)
1019 GetObjectData (serializationInfo, streamingContext);
1022 protected override void GetObjectData (SerializationInfo serializationInfo,
1023 StreamingContext streamingContext)
1025 SerializationInfo info = serializationInfo;
1027 info.AddValue ("requestUri", requestUri, typeof (Uri));
1028 info.AddValue ("actualUri", actualUri, typeof (Uri));
1029 info.AddValue ("allowAutoRedirect", allowAutoRedirect);
1030 info.AddValue ("allowBuffering", allowBuffering);
1031 info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
1032 info.AddValue ("connectionGroup", connectionGroup);
1033 info.AddValue ("contentLength", contentLength);
1034 info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
1035 info.AddValue ("keepAlive", keepAlive);
1036 info.AddValue ("maxAutoRedirect", maxAutoRedirect);
1037 info.AddValue ("mediaType", mediaType);
1038 info.AddValue ("method", method);
1039 info.AddValue ("initialMethod", initialMethod);
1040 info.AddValue ("pipelined", pipelined);
1041 info.AddValue ("version", version, typeof (Version));
1042 info.AddValue ("proxy", proxy, typeof (IWebProxy));
1043 info.AddValue ("sendChunked", sendChunked);
1044 info.AddValue ("timeout", timeout);
1045 info.AddValue ("redirects", redirects);
1046 info.AddValue ("host", host);
1049 void CheckRequestStarted ()
1052 throw new InvalidOperationException ("request started");
1055 internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
1057 if (continueDelegate != null)
1058 continueDelegate (statusCode, headers);
1061 void RewriteRedirectToGet ()
1064 webHeaders.RemoveInternal ("Transfer-Encoding");
1065 sendChunked = false;
1068 bool Redirect (WebAsyncResult result, HttpStatusCode code, WebResponse response)
1072 string uriString = null;
1074 case HttpStatusCode.Ambiguous: // 300
1075 e = new WebException ("Ambiguous redirect.");
1077 case HttpStatusCode.MovedPermanently: // 301
1078 case HttpStatusCode.Redirect: // 302
1079 if (method == "POST")
1080 RewriteRedirectToGet ();
1082 case HttpStatusCode.TemporaryRedirect: // 307
1084 case HttpStatusCode.SeeOther: //303
1085 RewriteRedirectToGet ();
1087 case HttpStatusCode.NotModified: // 304
1089 case HttpStatusCode.UseProxy: // 305
1090 e = new NotImplementedException ("Proxy support not available.");
1092 case HttpStatusCode.Unused: // 306
1094 e = new ProtocolViolationException ("Invalid status code: " + (int) code);
1098 if (method != "GET" && !InternalAllowBuffering && writeStream.WriteBufferLength > 0)
1099 e = new WebException ("The request requires buffering data to succeed.", null, WebExceptionStatus.ProtocolError, webResponse);
1104 if (AllowWriteStreamBuffering)
1107 uriString = webResponse.Headers ["Location"];
1109 if (uriString == null)
1110 throw new WebException ("No Location header found for " + (int) code,
1111 WebExceptionStatus.ProtocolError);
1113 Uri prev = actualUri;
1115 actualUri = new Uri (actualUri, uriString);
1116 } catch (Exception) {
1117 throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
1118 uriString, (int) code),
1119 WebExceptionStatus.ProtocolError);
1122 hostChanged = (actualUri.Scheme != prev.Scheme || Host != prev.Authority);
1126 string GetHeaders ()
1128 bool continue100 = false;
1131 webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
1132 webHeaders.RemoveInternal ("Content-Length");
1133 } else if (contentLength != -1) {
1134 if (auth_state.NtlmAuthState == NtlmAuthState.Challenge || proxy_auth_state.NtlmAuthState == NtlmAuthState.Challenge) {
1135 // We don't send any body with the NTLM Challenge request.
1136 if (haveContentLength || gotRequestStream || contentLength > 0)
1137 webHeaders.SetInternal ("Content-Length", "0");
1139 webHeaders.RemoveInternal ("Content-Length");
1141 if (contentLength > 0)
1144 if (haveContentLength || gotRequestStream || contentLength > 0)
1145 webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
1147 webHeaders.RemoveInternal ("Transfer-Encoding");
1149 webHeaders.RemoveInternal ("Content-Length");
1152 if (actualVersion == HttpVersion.Version11 && continue100 &&
1153 servicePoint.SendContinue) { // RFC2616 8.2.3
1154 webHeaders.RemoveAndAdd ("Expect" , "100-continue");
1155 expectContinue = true;
1157 webHeaders.RemoveInternal ("Expect");
1158 expectContinue = false;
1161 bool proxy_query = ProxyQuery;
1162 string connectionHeader = (proxy_query) ? "Proxy-Connection" : "Connection";
1163 webHeaders.RemoveInternal ((!proxy_query) ? "Proxy-Connection" : "Connection");
1164 Version proto_version = servicePoint.ProtocolVersion;
1165 bool spoint10 = (proto_version == null || proto_version == HttpVersion.Version10);
1167 if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
1168 if (webHeaders[connectionHeader] == null
1169 || webHeaders[connectionHeader].IndexOf ("keep-alive", StringComparison.OrdinalIgnoreCase) == -1)
1170 webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
1171 } else if (!keepAlive && version == HttpVersion.Version11) {
1172 webHeaders.RemoveAndAdd (connectionHeader, "close");
1175 webHeaders.SetInternal ("Host", Host);
1176 if (cookieContainer != null) {
1177 string cookieHeader = cookieContainer.GetCookieHeader (actualUri);
1178 if (cookieHeader != "")
1179 webHeaders.RemoveAndAdd ("Cookie", cookieHeader);
1181 webHeaders.RemoveInternal ("Cookie");
1184 string accept_encoding = null;
1185 if ((auto_decomp & DecompressionMethods.GZip) != 0)
1186 accept_encoding = "gzip";
1187 if ((auto_decomp & DecompressionMethods.Deflate) != 0)
1188 accept_encoding = accept_encoding != null ? "gzip, deflate" : "deflate";
1189 if (accept_encoding != null)
1190 webHeaders.RemoveAndAdd ("Accept-Encoding", accept_encoding);
1192 if (!usedPreAuth && preAuthenticate)
1193 DoPreAuthenticate ();
1195 return webHeaders.ToString ();
1198 void DoPreAuthenticate ()
1200 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1201 ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
1202 Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
1206 webHeaders.RemoveInternal ("Proxy-Authorization");
1207 webHeaders.RemoveInternal ("Authorization");
1208 string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
1209 webHeaders [authHeader] = auth.Message;
1213 internal void SetWriteStreamError (WebExceptionStatus status, Exception exc)
1218 WebAsyncResult r = asyncWrite;
1226 msg = "Error: " + status;
1227 wex = new WebException (msg, status);
1229 msg = String.Format ("Error: {0} ({1})", status, exc.Message);
1230 wex = new WebException (msg, exc, status);
1232 r.SetCompleted (false, wex);
1237 internal byte[] GetRequestHeaders ()
1239 StringBuilder req = new StringBuilder ();
1242 query = actualUri.PathAndQuery;
1244 query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
1246 actualUri.PathAndQuery);
1249 if (!force_version && servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
1250 actualVersion = servicePoint.ProtocolVersion;
1252 actualVersion = version;
1255 req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
1256 actualVersion.Major, actualVersion.Minor);
1257 req.Append (GetHeaders ());
1258 string reqstr = req.ToString ();
1259 return Encoding.UTF8.GetBytes (reqstr);
1262 internal void SetWriteStream (WebConnectionStream stream)
1267 writeStream = stream;
1268 if (bodyBuffer != null) {
1269 webHeaders.RemoveInternal ("Transfer-Encoding");
1270 contentLength = bodyBufferLength;
1271 writeStream.SendChunked = false;
1274 writeStream.SetHeadersAsync (false, result => {
1275 if (result.GotException) {
1276 SetWriteStreamError (result.Exception);
1282 SetWriteStreamInner (inner => {
1283 if (inner.GotException) {
1284 SetWriteStreamError (inner.Exception);
1288 if (asyncWrite != null) {
1289 asyncWrite.SetCompleted (inner.CompletedSynchronously, writeStream);
1290 asyncWrite.DoCallback ();
1297 void SetWriteStreamInner (SimpleAsyncCallback callback)
1299 SimpleAsyncResult.Run (result => {
1300 if (bodyBuffer != null) {
1301 // The body has been written and buffered. The request "user"
1302 // won't write it again, so we must do it.
1303 if (auth_state.NtlmAuthState != NtlmAuthState.Challenge && proxy_auth_state.NtlmAuthState != NtlmAuthState.Challenge) {
1304 // FIXME: this is a blocking call on the thread pool that could lead to thread pool exhaustion
1305 writeStream.Write (bodyBuffer, 0, bodyBufferLength);
1307 writeStream.Close ();
1309 } else if (method != "HEAD" && method != "GET" && method != "MKCOL" && method != "CONNECT" &&
1310 method != "TRACE") {
1311 if (getResponseCalled && !writeStream.RequestWritten)
1312 return writeStream.WriteRequestAsync (result);
1319 void SetWriteStreamError (Exception exc)
1321 WebException wexc = exc as WebException;
1323 SetWriteStreamError (wexc.Status, wexc);
1325 SetWriteStreamError (WebExceptionStatus.SendFailure, exc);
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);
1472 sendChunked = false;
1473 webHeaders.RemoveInternal ("Transfer-Encoding");
1476 if (webResponse != null) {
1477 if (HandleNtlmAuth (r))
1479 webResponse.Close ();
1481 finished_reading = false;
1482 haveResponse = false;
1485 servicePoint = GetServicePoint ();
1486 abortHandler = servicePoint.SendRequest (this, connectionGroup);
1488 } catch (WebException wexc2) {
1491 haveResponse = true;
1493 r.SetCompleted (false, wexc2);
1496 } catch (Exception ex) {
1497 wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
1500 haveResponse = true;
1502 r.SetCompleted (false, wexc);
1510 struct AuthorizationState
1512 readonly HttpWebRequest request;
1513 readonly bool isProxy;
1515 NtlmAuthState ntlm_auth_state;
1517 public bool IsCompleted {
1518 get { return isCompleted; }
1521 public NtlmAuthState NtlmAuthState {
1522 get { return ntlm_auth_state; }
1525 public bool IsNtlmAuthenticated {
1526 get { return isCompleted && ntlm_auth_state != NtlmAuthState.None; }
1529 public AuthorizationState (HttpWebRequest request, bool isProxy)
1531 this.request = request;
1532 this.isProxy = isProxy;
1533 isCompleted = false;
1534 ntlm_auth_state = NtlmAuthState.None;
1537 public bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1539 isCompleted = false;
1540 if (code == HttpStatusCode.Unauthorized && request.credentials == null)
1543 // FIXME: This should never happen!
1544 if (isProxy != (code == HttpStatusCode.ProxyAuthenticationRequired))
1547 if (isProxy && (request.proxy == null || request.proxy.Credentials == null))
1550 string [] authHeaders = response.Headers.GetValues_internal (isProxy ? "Proxy-Authenticate" : "WWW-Authenticate", false);
1551 if (authHeaders == null || authHeaders.Length == 0)
1554 ICredentials creds = (!isProxy) ? request.credentials : request.proxy.Credentials;
1555 Authorization auth = null;
1556 foreach (string authHeader in authHeaders) {
1557 auth = AuthenticationManager.Authenticate (authHeader, request, creds);
1563 request.webHeaders [isProxy ? "Proxy-Authorization" : "Authorization"] = auth.Message;
1564 isCompleted = auth.Complete;
1565 bool is_ntlm = (auth.Module.AuthenticationType == "NTLM");
1567 ntlm_auth_state = (NtlmAuthState)((int) ntlm_auth_state + 1);
1571 public void Reset ()
1573 isCompleted = false;
1574 ntlm_auth_state = NtlmAuthState.None;
1575 request.webHeaders.RemoveInternal (isProxy ? "Proxy-Authorization" : "Authorization");
1578 public override string ToString ()
1580 return string.Format ("{0}AuthState [{1}:{2}]", isProxy ? "Proxy" : "", isCompleted, ntlm_auth_state);
1584 bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1586 bool isProxy = code == HttpStatusCode.ProxyAuthenticationRequired;
1587 return isProxy ? proxy_auth_state.CheckAuthorization (response, code) : auth_state.CheckAuthorization (response, code);
1590 // Returns true if redirected
1591 bool CheckFinalStatus (WebAsyncResult result)
1593 if (result.GotException) {
1595 throw result.Exception;
1598 Exception throwMe = result.Exception;
1600 HttpWebResponse resp = result.Response;
1601 WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
1602 HttpStatusCode code = 0;
1603 if (throwMe == null && webResponse != null) {
1604 code = webResponse.StatusCode;
1605 if ((!auth_state.IsCompleted && code == HttpStatusCode.Unauthorized && credentials != null) ||
1606 (ProxyQuery && !proxy_auth_state.IsCompleted && code == HttpStatusCode.ProxyAuthenticationRequired)) {
1607 if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
1608 // Keep the written body, so it can be rewritten in the retry
1609 if (InternalAllowBuffering) {
1610 if (writeStream.WriteBufferLength > 0) {
1611 bodyBuffer = writeStream.WriteBuffer;
1612 bodyBufferLength = writeStream.WriteBufferLength;
1615 } else if (method != "PUT" && method != "POST") {
1623 writeStream.InternalClose ();
1625 webResponse.Close ();
1629 throw new WebException ("This request requires buffering " +
1630 "of data for authentication or " +
1631 "redirection to be sucessful.");
1636 if ((int) code >= 400) {
1637 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1638 (int) code, webResponse.StatusDescription);
1639 throwMe = new WebException (err, null, protoError, webResponse);
1640 webResponse.ReadAll ();
1641 } else if ((int) code == 304 && allowAutoRedirect) {
1642 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1643 (int) code, webResponse.StatusDescription);
1644 throwMe = new WebException (err, null, protoError, webResponse);
1645 } else if ((int) code >= 300 && allowAutoRedirect && redirects >= maxAutoRedirect) {
1646 throwMe = new WebException ("Max. redirections exceeded.", null,
1647 protoError, webResponse);
1648 webResponse.ReadAll ();
1653 if (throwMe == null) {
1656 if (allowAutoRedirect && c >= 300) {
1657 b = Redirect (result, code, webResponse);
1658 if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
1659 bodyBuffer = writeStream.WriteBuffer;
1660 bodyBufferLength = writeStream.WriteBufferLength;
1662 if (b && !unsafe_auth_blah) {
1663 auth_state.Reset ();
1664 proxy_auth_state.Reset ();
1668 if (resp != null && c >= 300 && c != 304)
1677 if (writeStream != null) {
1678 writeStream.InternalClose ();
1687 internal bool ReuseConnection {
1692 internal WebConnection StoredConnection;