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 WebAsyncResult CheckIfForceWrite (AsyncCallback callback, object state)
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 return writeStream.WriteRequestAsync (callback, state);
890 public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
893 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
896 throw new ProtocolViolationException ("Method is null.");
898 string transferEncoding = TransferEncoding;
899 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
900 throw new ProtocolViolationException ("SendChunked should be true.");
902 Monitor.Enter (locker);
903 getResponseCalled = true;
904 if (asyncRead != null && !haveResponse) {
905 Monitor.Exit (locker);
906 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
907 "method while a previous call is still in progress.");
910 asyncRead = new WebAsyncResult (this, callback, state);
911 WebAsyncResult aread = asyncRead;
912 initialMethod = method;
914 aread.InnerAsyncResult = CheckIfForceWrite (GetResponseAsyncCB, aread);
915 if (aread.InnerAsyncResult == null)
916 GetResponseAsyncCB2 (aread);
918 Monitor.Exit (locker);
922 void GetResponseAsyncCB (IAsyncResult ar)
924 var result = (WebAsyncResult)ar;
925 var innerResult = (WebAsyncResult)result.InnerAsyncResult;
926 result.InnerAsyncResult = null;
928 if (innerResult != null && innerResult.GotException) {
929 asyncRead.SetCompleted (true, innerResult.Exception);
930 asyncRead.DoCallback ();
934 Monitor.Enter (locker);
935 GetResponseAsyncCB2 ((WebAsyncResult)ar);
938 void GetResponseAsyncCB2 (WebAsyncResult aread)
941 Exception saved = saved_exc;
942 if (webResponse != null) {
943 Monitor.Exit (locker);
945 aread.SetCompleted (true, webResponse);
947 aread.SetCompleted (true, saved);
951 } else if (saved != null) {
952 Monitor.Exit (locker);
953 aread.SetCompleted (true, saved);
962 servicePoint = GetServicePoint ();
963 abortHandler = servicePoint.SendRequest (this, connectionGroup);
966 Monitor.Exit (locker);
969 public override WebResponse EndGetResponse (IAsyncResult asyncResult)
971 if (asyncResult == null)
972 throw new ArgumentNullException ("asyncResult");
974 WebAsyncResult result = asyncResult as WebAsyncResult;
976 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
978 if (!result.WaitUntilComplete (timeout, false)) {
980 throw new WebException("The request timed out", WebExceptionStatus.Timeout);
983 if (result.GotException)
984 throw result.Exception;
986 return result.Response;
990 public Stream EndGetRequestStream (IAsyncResult asyncResult, out TransportContext transportContext)
992 transportContext = null;
993 return EndGetRequestStream (asyncResult);
997 public override WebResponse GetResponse()
999 WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
1000 return EndGetResponse (result);
1003 internal bool FinishedReading {
1004 get { return finished_reading; }
1005 set { finished_reading = value; }
1008 internal bool Aborted {
1009 get { return Interlocked.CompareExchange (ref aborted, 0, 0) == 1; }
1012 public override void Abort ()
1014 if (Interlocked.CompareExchange (ref aborted, 1, 0) == 1)
1017 if (haveResponse && finished_reading)
1020 haveResponse = true;
1021 if (abortHandler != null) {
1023 abortHandler (this, EventArgs.Empty);
1024 } catch (Exception) {}
1025 abortHandler = null;
1028 if (asyncWrite != null) {
1029 WebAsyncResult r = asyncWrite;
1030 if (!r.IsCompleted) {
1032 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
1033 r.SetCompleted (false, wexc);
1040 if (asyncRead != null) {
1041 WebAsyncResult r = asyncRead;
1042 if (!r.IsCompleted) {
1044 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
1045 r.SetCompleted (false, wexc);
1052 if (writeStream != null) {
1054 writeStream.Close ();
1059 if (webResponse != null) {
1061 webResponse.Close ();
1067 void ISerializable.GetObjectData (SerializationInfo serializationInfo,
1068 StreamingContext streamingContext)
1070 GetObjectData (serializationInfo, streamingContext);
1073 protected override void GetObjectData (SerializationInfo serializationInfo,
1074 StreamingContext streamingContext)
1076 SerializationInfo info = serializationInfo;
1078 info.AddValue ("requestUri", requestUri, typeof (Uri));
1079 info.AddValue ("actualUri", actualUri, typeof (Uri));
1080 info.AddValue ("allowAutoRedirect", allowAutoRedirect);
1081 info.AddValue ("allowBuffering", allowBuffering);
1082 info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
1083 info.AddValue ("connectionGroup", connectionGroup);
1084 info.AddValue ("contentLength", contentLength);
1085 info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
1086 info.AddValue ("keepAlive", keepAlive);
1087 info.AddValue ("maxAutoRedirect", maxAutoRedirect);
1088 info.AddValue ("mediaType", mediaType);
1089 info.AddValue ("method", method);
1090 info.AddValue ("initialMethod", initialMethod);
1091 info.AddValue ("pipelined", pipelined);
1092 info.AddValue ("version", version, typeof (Version));
1093 info.AddValue ("proxy", proxy, typeof (IWebProxy));
1094 info.AddValue ("sendChunked", sendChunked);
1095 info.AddValue ("timeout", timeout);
1096 info.AddValue ("redirects", redirects);
1097 info.AddValue ("host", host);
1100 void CheckRequestStarted ()
1103 throw new InvalidOperationException ("request started");
1106 internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
1108 if (continueDelegate != null)
1109 continueDelegate (statusCode, headers);
1112 bool Redirect (WebAsyncResult result, HttpStatusCode code)
1116 string uriString = null;
1118 case HttpStatusCode.Ambiguous: // 300
1119 e = new WebException ("Ambiguous redirect.");
1121 case HttpStatusCode.MovedPermanently: // 301
1122 case HttpStatusCode.Redirect: // 302
1123 if (method == "POST")
1126 case HttpStatusCode.TemporaryRedirect: // 307
1128 case HttpStatusCode.SeeOther: //303
1131 case HttpStatusCode.NotModified: // 304
1133 case HttpStatusCode.UseProxy: // 305
1134 e = new NotImplementedException ("Proxy support not available.");
1136 case HttpStatusCode.Unused: // 306
1138 e = new ProtocolViolationException ("Invalid status code: " + (int) code);
1146 //bodyBufferLength = 0;
1147 //bodyBuffer = null;
1148 uriString = webResponse.Headers ["Location"];
1150 if (uriString == null)
1151 throw new WebException ("No Location header found for " + (int) code,
1152 WebExceptionStatus.ProtocolError);
1154 Uri prev = actualUri;
1156 actualUri = new Uri (actualUri, uriString);
1157 } catch (Exception) {
1158 throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
1159 uriString, (int) code),
1160 WebExceptionStatus.ProtocolError);
1163 hostChanged = (actualUri.Scheme != prev.Scheme || Host != prev.Authority);
1167 string GetHeaders ()
1169 bool continue100 = false;
1172 webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
1173 webHeaders.RemoveInternal ("Content-Length");
1174 } else if (contentLength != -1) {
1175 if (auth_state.NtlmAuthState == NtlmAuthState.Challenge || proxy_auth_state.NtlmAuthState == NtlmAuthState.Challenge) {
1176 // We don't send any body with the NTLM Challenge request.
1177 webHeaders.SetInternal ("Content-Length", "0");
1179 if (contentLength > 0)
1182 if (gotRequestStream || contentLength > 0)
1183 webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
1185 webHeaders.RemoveInternal ("Transfer-Encoding");
1187 webHeaders.RemoveInternal ("Content-Length");
1190 if (actualVersion == HttpVersion.Version11 && continue100 &&
1191 servicePoint.SendContinue) { // RFC2616 8.2.3
1192 webHeaders.RemoveAndAdd ("Expect" , "100-continue");
1193 expectContinue = true;
1195 webHeaders.RemoveInternal ("Expect");
1196 expectContinue = false;
1199 bool proxy_query = ProxyQuery;
1200 string connectionHeader = (proxy_query) ? "Proxy-Connection" : "Connection";
1201 webHeaders.RemoveInternal ((!proxy_query) ? "Proxy-Connection" : "Connection");
1202 Version proto_version = servicePoint.ProtocolVersion;
1203 bool spoint10 = (proto_version == null || proto_version == HttpVersion.Version10);
1205 if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
1206 if (webHeaders[connectionHeader] == null
1207 || webHeaders[connectionHeader].IndexOf ("keep-alive", StringComparison.OrdinalIgnoreCase) == -1)
1208 webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
1209 } else if (!keepAlive && version == HttpVersion.Version11) {
1210 webHeaders.RemoveAndAdd (connectionHeader, "close");
1213 webHeaders.SetInternal ("Host", Host);
1214 if (cookieContainer != null) {
1215 string cookieHeader = cookieContainer.GetCookieHeader (actualUri);
1216 if (cookieHeader != "")
1217 webHeaders.RemoveAndAdd ("Cookie", cookieHeader);
1219 webHeaders.RemoveInternal ("Cookie");
1222 string accept_encoding = null;
1223 if ((auto_decomp & DecompressionMethods.GZip) != 0)
1224 accept_encoding = "gzip";
1225 if ((auto_decomp & DecompressionMethods.Deflate) != 0)
1226 accept_encoding = accept_encoding != null ? "gzip, deflate" : "deflate";
1227 if (accept_encoding != null)
1228 webHeaders.RemoveAndAdd ("Accept-Encoding", accept_encoding);
1230 if (!usedPreAuth && preAuthenticate)
1231 DoPreAuthenticate ();
1233 return webHeaders.ToString ();
1236 void DoPreAuthenticate ()
1238 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1239 ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
1240 Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
1244 webHeaders.RemoveInternal ("Proxy-Authorization");
1245 webHeaders.RemoveInternal ("Authorization");
1246 string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
1247 webHeaders [authHeader] = auth.Message;
1251 internal void SetWriteStreamError (WebExceptionStatus status, Exception exc)
1256 WebAsyncResult r = asyncWrite;
1264 msg = "Error: " + status;
1265 wex = new WebException (msg, status);
1267 msg = String.Format ("Error: {0} ({1})", status, exc.Message);
1268 wex = new WebException (msg, exc, status);
1270 r.SetCompleted (false, wex);
1275 internal byte[] GetRequestHeaders ()
1277 StringBuilder req = new StringBuilder ();
1280 query = actualUri.PathAndQuery;
1282 query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
1284 actualUri.PathAndQuery);
1287 if (!force_version && servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
1288 actualVersion = servicePoint.ProtocolVersion;
1290 actualVersion = version;
1293 req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
1294 actualVersion.Major, actualVersion.Minor);
1295 req.Append (GetHeaders ());
1296 string reqstr = req.ToString ();
1297 return Encoding.UTF8.GetBytes (reqstr);
1300 internal void SetWriteStream (WebConnectionStream stream)
1305 writeStream = stream;
1306 if (bodyBuffer != null) {
1307 webHeaders.RemoveInternal ("Transfer-Encoding");
1308 contentLength = bodyBufferLength;
1309 writeStream.SendChunked = false;
1313 var result = writeStream.SetHeadersAsync (false, SetWriteStreamCB, null);
1315 SetWriteStreamCB (null);
1316 } catch (Exception exc) {
1317 SetWriteStreamErrorCB (exc);
1321 void SetWriteStreamErrorCB (Exception exc)
1323 WebException wexc = exc as WebException;
1325 SetWriteStreamError (wexc.Status, wexc);
1327 SetWriteStreamError (WebExceptionStatus.SendFailure, exc);
1330 void SetWriteStreamCB (IAsyncResult ar)
1332 WebAsyncResult result = ar as WebAsyncResult;
1334 if (result != null && result.Exception != null) {
1335 SetWriteStreamErrorCB (result.Exception);
1341 WebAsyncResult writeRequestResult = null;
1343 if (bodyBuffer != null) {
1344 // The body has been written and buffered. The request "user"
1345 // won't write it again, so we must do it.
1346 if (auth_state.NtlmAuthState != NtlmAuthState.Challenge && proxy_auth_state.NtlmAuthState != NtlmAuthState.Challenge) {
1347 // FIXME: this is a blocking call on the thread pool that could lead to thread pool exhaustion
1348 writeStream.Write (bodyBuffer, 0, bodyBufferLength);
1350 writeStream.Close ();
1352 } else if (method != "HEAD" && method != "GET" && method != "MKCOL" && method != "CONNECT" &&
1353 method != "TRACE") {
1354 if (getResponseCalled && !writeStream.RequestWritten)
1355 writeRequestResult = writeStream.WriteRequestAsync (SetWriteStreamCB2, null);
1358 if (writeRequestResult == null)
1359 SetWriteStreamCB2 (null);
1362 void SetWriteStreamCB2 (IAsyncResult ar)
1364 var result = (WebAsyncResult)ar;
1365 if (result != null && result.GotException) {
1366 SetWriteStreamErrorCB (result.Exception);
1370 if (asyncWrite != null) {
1371 asyncWrite.SetCompleted (false, writeStream);
1372 asyncWrite.DoCallback ();
1377 internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
1382 string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
1383 WebAsyncResult r = asyncRead;
1388 if (e is WebException) {
1389 wexc = (WebException) e;
1391 wexc = new WebException (msg, e, status, null);
1394 if (!r.IsCompleted) {
1395 r.SetCompleted (false, wexc);
1397 } else if (r == asyncWrite) {
1400 haveResponse = true;
1404 haveResponse = true;
1410 void CheckSendError (WebConnectionData data)
1412 // Got here, but no one called GetResponse
1413 int status = data.StatusCode;
1414 if (status < 400 || status == 401 || status == 407)
1417 if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
1418 // The request has not been completely sent and we got here!
1419 // We should probably just close and cause an error in any case,
1420 saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse);
1421 if (allowBuffering || sendChunked || writeStream.totalWritten >= contentLength) {
1422 webResponse.ReadAll ();
1424 writeStream.IgnoreIOErrors = true;
1429 bool HandleNtlmAuth (WebAsyncResult r)
1431 bool isProxy = webResponse.StatusCode == HttpStatusCode.ProxyAuthenticationRequired;
1432 if ((isProxy ? proxy_auth_state.NtlmAuthState : auth_state.NtlmAuthState) == NtlmAuthState.None)
1435 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1437 WebConnection cnc = wce.Connection;
1438 cnc.PriorityRequest = this;
1439 ICredentials creds = !isProxy ? credentials : proxy.Credentials;
1440 if (creds != null) {
1441 cnc.NtlmCredential = creds.GetCredential (requestUri, "NTLM");
1442 cnc.UnsafeAuthenticatedConnectionSharing = unsafe_auth_blah;
1446 finished_reading = false;
1447 haveResponse = false;
1448 webResponse.ReadAll ();
1453 internal void SetResponseData (WebConnectionData data)
1457 if (data.stream != null)
1458 data.stream.Close ();
1462 WebException wexc = null;
1464 webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
1465 } catch (Exception e) {
1466 wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null);
1467 if (data.stream != null)
1468 data.stream.Close ();
1471 if (wexc == null && (method == "POST" || method == "PUT")) {
1472 CheckSendError (data);
1473 if (saved_exc != null)
1474 wexc = (WebException) saved_exc;
1477 WebAsyncResult r = asyncRead;
1479 bool forced = false;
1480 if (r == null && webResponse != null) {
1481 // This is a forced completion (302, 204)...
1483 r = new WebAsyncResult (null, null);
1484 r.SetCompleted (false, webResponse);
1489 haveResponse = true;
1491 r.SetCompleted (false, wexc);
1496 bool isProxy = ProxyQuery && !proxy.IsBypassed (actualUri);
1500 redirected = CheckFinalStatus (r);
1502 if ((isProxy ? proxy_auth_state.IsNtlmAuthenticated : auth_state.IsNtlmAuthenticated) &&
1503 webResponse != null && (int)webResponse.StatusCode < 400) {
1504 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1506 WebConnection cnc = wce.Connection;
1507 cnc.NtlmAuthenticated = true;
1511 // clear internal buffer so that it does not
1512 // hold possible big buffer (bug #397627)
1513 if (writeStream != null)
1514 writeStream.KillBuffer ();
1516 haveResponse = true;
1517 r.SetCompleted (false, webResponse);
1520 if (webResponse != null) {
1521 if (HandleNtlmAuth (r))
1523 webResponse.Close ();
1525 finished_reading = false;
1526 haveResponse = false;
1529 servicePoint = GetServicePoint ();
1530 abortHandler = servicePoint.SendRequest (this, connectionGroup);
1532 } catch (WebException wexc2) {
1535 haveResponse = true;
1537 r.SetCompleted (false, wexc2);
1540 } catch (Exception ex) {
1541 wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
1544 haveResponse = true;
1546 r.SetCompleted (false, wexc);
1554 struct AuthorizationState
1556 readonly HttpWebRequest request;
1557 readonly bool isProxy;
1559 NtlmAuthState ntlm_auth_state;
1561 public bool IsCompleted {
1562 get { return isCompleted; }
1565 public NtlmAuthState NtlmAuthState {
1566 get { return ntlm_auth_state; }
1569 public bool IsNtlmAuthenticated {
1570 get { return isCompleted && ntlm_auth_state != NtlmAuthState.None; }
1573 public AuthorizationState (HttpWebRequest request, bool isProxy)
1575 this.request = request;
1576 this.isProxy = isProxy;
1577 isCompleted = false;
1578 ntlm_auth_state = NtlmAuthState.None;
1581 public bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1583 isCompleted = false;
1584 if (code == HttpStatusCode.Unauthorized && request.credentials == null)
1587 // FIXME: This should never happen!
1588 if (isProxy != (code == HttpStatusCode.ProxyAuthenticationRequired))
1591 if (isProxy && (request.proxy == null || request.proxy.Credentials == null))
1594 string [] authHeaders = response.Headers.GetValues_internal (isProxy ? "Proxy-Authenticate" : "WWW-Authenticate", false);
1595 if (authHeaders == null || authHeaders.Length == 0)
1598 ICredentials creds = (!isProxy) ? request.credentials : request.proxy.Credentials;
1599 Authorization auth = null;
1600 foreach (string authHeader in authHeaders) {
1601 auth = AuthenticationManager.Authenticate (authHeader, request, creds);
1607 request.webHeaders [isProxy ? "Proxy-Authorization" : "Authorization"] = auth.Message;
1608 isCompleted = auth.Complete;
1609 bool is_ntlm = (auth.Module.AuthenticationType == "NTLM");
1611 ntlm_auth_state = (NtlmAuthState)((int) ntlm_auth_state + 1);
1615 public void Reset ()
1617 isCompleted = false;
1618 ntlm_auth_state = NtlmAuthState.None;
1619 request.webHeaders.RemoveInternal (isProxy ? "Proxy-Authorization" : "Authorization");
1622 public override string ToString ()
1624 return string.Format ("{0}AuthState [{1}:{2}]", isProxy ? "Proxy" : "", isCompleted, ntlm_auth_state);
1628 bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1630 bool isProxy = code == HttpStatusCode.ProxyAuthenticationRequired;
1631 return isProxy ? proxy_auth_state.CheckAuthorization (response, code) : auth_state.CheckAuthorization (response, code);
1634 // Returns true if redirected
1635 bool CheckFinalStatus (WebAsyncResult result)
1637 if (result.GotException) {
1639 throw result.Exception;
1642 Exception throwMe = result.Exception;
1644 HttpWebResponse resp = result.Response;
1645 WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
1646 HttpStatusCode code = 0;
1647 if (throwMe == null && webResponse != null) {
1648 code = webResponse.StatusCode;
1649 if ((!auth_state.IsCompleted && code == HttpStatusCode.Unauthorized && credentials != null) ||
1650 (ProxyQuery && !proxy_auth_state.IsCompleted && code == HttpStatusCode.ProxyAuthenticationRequired)) {
1651 if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
1652 // Keep the written body, so it can be rewritten in the retry
1653 if (InternalAllowBuffering) {
1654 // NTLM: This is to avoid sending data in the 'challenge' request
1655 // We save it in the first request (first 401), don't send anything
1656 // in the challenge request and send it in the response request along
1657 // with the buffers kept form the first request.
1658 if (auth_state.NtlmAuthState == NtlmAuthState.Challenge || proxy_auth_state.NtlmAuthState == NtlmAuthState.Challenge) {
1659 bodyBuffer = writeStream.WriteBuffer;
1660 bodyBufferLength = writeStream.WriteBufferLength;
1663 } else if (method != "PUT" && method != "POST") {
1671 writeStream.InternalClose ();
1673 webResponse.Close ();
1677 throw new WebException ("This request requires buffering " +
1678 "of data for authentication or " +
1679 "redirection to be sucessful.");
1684 if ((int) code >= 400) {
1685 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1686 (int) code, webResponse.StatusDescription);
1687 throwMe = new WebException (err, null, protoError, webResponse);
1688 webResponse.ReadAll ();
1689 } else if ((int) code == 304 && allowAutoRedirect) {
1690 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1691 (int) code, webResponse.StatusDescription);
1692 throwMe = new WebException (err, null, protoError, webResponse);
1693 } else if ((int) code >= 300 && allowAutoRedirect && redirects >= maxAutoRedirect) {
1694 throwMe = new WebException ("Max. redirections exceeded.", null,
1695 protoError, webResponse);
1696 webResponse.ReadAll ();
1701 if (throwMe == null) {
1704 if (allowAutoRedirect && c >= 300) {
1705 b = Redirect (result, code);
1706 if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
1707 bodyBuffer = writeStream.WriteBuffer;
1708 bodyBufferLength = writeStream.WriteBufferLength;
1710 if (b && !unsafe_auth_blah) {
1711 auth_state.Reset ();
1712 proxy_auth_state.Reset ();
1716 if (resp != null && c >= 300 && c != 304)
1725 if (writeStream != null) {
1726 writeStream.InternalClose ();
1735 internal bool ReuseConnection {
1740 internal WebConnection StoredConnection;