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 #if MONO_SECURITY_ALIAS
36 extern alias MonoSecurity;
37 using MonoSecurity::Mono.Security.Interface;
39 using Mono.Security.Interface;
44 using System.Collections;
45 using System.Configuration;
46 using System.Globalization;
49 using System.Net.Cache;
50 using System.Net.Sockets;
51 using System.Net.Security;
52 using System.Runtime.Remoting.Messaging;
53 using System.Runtime.Serialization;
54 using System.Security.Cryptography.X509Certificates;
56 using System.Threading;
57 using Mono.Net.Security;
62 public class HttpWebRequest : WebRequest, ISerializable {
66 bool allowAutoRedirect = true;
67 bool allowBuffering = true;
68 X509CertificateCollection certificates;
69 string connectionGroup;
70 bool haveContentLength;
71 long contentLength = -1;
72 HttpContinueDelegate continueDelegate;
73 CookieContainer cookieContainer;
74 ICredentials credentials;
78 WebHeaderCollection webHeaders;
79 bool keepAlive = true;
80 int maxAutoRedirect = 50;
81 string mediaType = String.Empty;
82 string method = "GET";
83 string initialMethod = "GET";
84 bool pipelined = true;
87 Version version = HttpVersion.Version11;
89 Version actualVersion;
92 ServicePoint servicePoint;
95 WebConnectionStream writeStream;
96 HttpWebResponse webResponse;
97 WebAsyncResult asyncWrite;
98 WebAsyncResult asyncRead;
99 EventHandler abortHandler;
101 bool gotRequestStream;
105 int bodyBufferLength;
106 bool getResponseCalled;
108 object locker = new object ();
109 bool finished_reading;
110 internal WebConnection WebConnection;
111 DecompressionMethods auto_decomp;
112 int maxResponseHeadersLength;
113 static int defaultMaxResponseHeadersLength;
114 int readWriteTimeout = 300000; // ms
115 IMonoTlsProvider tlsProvider;
117 MonoTlsSettings tlsSettings;
119 ServerCertValidationCallback certValidationCallback;
126 AuthorizationState auth_state, proxy_auth_state;
130 internal Action<Stream> ResendContentFactory;
133 static HttpWebRequest ()
135 defaultMaxResponseHeadersLength = 64 * 1024;
137 NetConfig config = ConfigurationSettings.GetConfig ("system.net/settings") as NetConfig;
138 if (config != null) {
139 int x = config.MaxResponseHeadersLength;
143 defaultMaxResponseHeadersLength = x;
153 HttpWebRequest (Uri uri)
155 this.requestUri = uri;
156 this.actualUri = uri;
157 this.proxy = GlobalProxySelection.Select;
158 this.webHeaders = new WebHeaderCollection (WebHeaderCollection.HeaderInfo.Request);
160 ResetAuthorization ();
164 internal HttpWebRequest (Uri uri, IMonoTlsProvider tlsProvider, MonoTlsSettings settings = null)
167 this.tlsProvider = tlsProvider;
168 this.tlsSettings = settings;
172 [Obsolete ("Serialization is obsoleted for this type", false)]
173 protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
175 SerializationInfo info = serializationInfo;
177 requestUri = (Uri) info.GetValue ("requestUri", typeof (Uri));
178 actualUri = (Uri) info.GetValue ("actualUri", typeof (Uri));
179 allowAutoRedirect = info.GetBoolean ("allowAutoRedirect");
180 allowBuffering = info.GetBoolean ("allowBuffering");
181 certificates = (X509CertificateCollection) info.GetValue ("certificates", typeof (X509CertificateCollection));
182 connectionGroup = info.GetString ("connectionGroup");
183 contentLength = info.GetInt64 ("contentLength");
184 webHeaders = (WebHeaderCollection) info.GetValue ("webHeaders", typeof (WebHeaderCollection));
185 keepAlive = info.GetBoolean ("keepAlive");
186 maxAutoRedirect = info.GetInt32 ("maxAutoRedirect");
187 mediaType = info.GetString ("mediaType");
188 method = info.GetString ("method");
189 initialMethod = info.GetString ("initialMethod");
190 pipelined = info.GetBoolean ("pipelined");
191 version = (Version) info.GetValue ("version", typeof (Version));
192 proxy = (IWebProxy) info.GetValue ("proxy", typeof (IWebProxy));
193 sendChunked = info.GetBoolean ("sendChunked");
194 timeout = info.GetInt32 ("timeout");
195 redirects = info.GetInt32 ("redirects");
196 host = info.GetString ("host");
197 ResetAuthorization ();
200 void ResetAuthorization ()
202 auth_state = new AuthorizationState (this, false);
203 proxy_auth_state = new AuthorizationState (this, true);
208 public string Accept {
209 get { return webHeaders ["Accept"]; }
211 CheckRequestStarted ();
212 webHeaders.RemoveAndAdd ("Accept", value);
217 get { return actualUri; }
218 internal set { actualUri = value; } // Used by Ftp+proxy
221 public bool AllowAutoRedirect {
222 get { return allowAutoRedirect; }
223 set { this.allowAutoRedirect = value; }
226 public bool AllowWriteStreamBuffering {
227 get { return allowBuffering; }
228 set { allowBuffering = value; }
231 public virtual bool AllowReadStreamBuffering {
232 get { return false; }
235 throw new InvalidOperationException ();
239 static Exception GetMustImplement ()
241 return new NotImplementedException ();
244 public DecompressionMethods AutomaticDecompression
250 CheckRequestStarted ();
255 internal bool InternalAllowBuffering {
257 return allowBuffering && MethodWithBuffer;
261 bool MethodWithBuffer {
263 return method != "HEAD" && method != "GET" &&
264 method != "MKCOL" && method != "CONNECT" &&
269 internal IMonoTlsProvider TlsProvider {
270 get { return tlsProvider; }
274 internal MonoTlsSettings TlsSettings {
275 get { return tlsSettings; }
279 public X509CertificateCollection ClientCertificates {
281 if (certificates == null)
282 certificates = new X509CertificateCollection ();
287 throw new ArgumentNullException ("value");
288 certificates = value;
292 public string Connection {
293 get { return webHeaders ["Connection"]; }
295 CheckRequestStarted ();
297 if (string.IsNullOrEmpty (value)) {
298 webHeaders.RemoveInternal ("Connection");
302 string val = value.ToLowerInvariant ();
303 if (val.Contains ("keep-alive") || val.Contains ("close"))
304 throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
307 value = value + ", Keep-Alive";
309 webHeaders.RemoveAndAdd ("Connection", value);
313 public override string ConnectionGroupName {
314 get { return connectionGroup; }
315 set { connectionGroup = value; }
318 public override long ContentLength {
319 get { return contentLength; }
321 CheckRequestStarted ();
323 throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
325 contentLength = value;
326 haveContentLength = true;
330 internal long InternalContentLength {
331 set { contentLength = value; }
334 internal bool ThrowOnError { get; set; }
336 public override string ContentType {
337 get { return webHeaders ["Content-Type"]; }
339 if (value == null || value.Trim().Length == 0) {
340 webHeaders.RemoveInternal ("Content-Type");
343 webHeaders.RemoveAndAdd ("Content-Type", value);
347 public HttpContinueDelegate ContinueDelegate {
348 get { return continueDelegate; }
349 set { continueDelegate = value; }
353 public CookieContainer CookieContainer {
354 get { return cookieContainer; }
355 set { cookieContainer = value; }
358 public override ICredentials Credentials {
359 get { return credentials; }
360 set { credentials = value; }
362 public DateTime Date {
364 string date = webHeaders ["Date"];
366 return DateTime.MinValue;
367 return DateTime.ParseExact (date, "r", CultureInfo.InvariantCulture).ToLocalTime ();
370 if (value.Equals (DateTime.MinValue))
371 webHeaders.RemoveInternal ("Date");
373 webHeaders.RemoveAndAdd ("Date", value.ToUniversalTime ().ToString ("r", CultureInfo.InvariantCulture));
379 public static new RequestCachePolicy DefaultCachePolicy
382 throw GetMustImplement ();
385 throw GetMustImplement ();
391 public static int DefaultMaximumErrorResponseLength
394 throw GetMustImplement ();
397 throw GetMustImplement ();
401 public string Expect {
402 get { return webHeaders ["Expect"]; }
404 CheckRequestStarted ();
407 val = val.Trim ().ToLower ();
409 if (val == null || val.Length == 0) {
410 webHeaders.RemoveInternal ("Expect");
414 if (val == "100-continue")
415 throw new ArgumentException ("100-Continue cannot be set with this property.",
417 webHeaders.RemoveAndAdd ("Expect", value);
422 public bool HaveResponse {
423 get { return haveResponse; }
426 public override WebHeaderCollection Headers {
427 get { return webHeaders; }
429 CheckRequestStarted ();
430 WebHeaderCollection newHeaders = new WebHeaderCollection (WebHeaderCollection.HeaderInfo.Request);
431 int count = value.Count;
432 for (int i = 0; i < count; i++)
433 newHeaders.Add (value.GetKey (i), value.Get (i));
435 webHeaders = newHeaders;
443 return actualUri.Authority;
448 throw new ArgumentNullException ("value");
450 if (!CheckValidHost (actualUri.Scheme, value))
451 throw new ArgumentException ("Invalid host: " + value);
457 static bool CheckValidHost (string scheme, string val)
465 int idx = val.IndexOf ('/');
470 if (IPAddress.TryParse (val, out ipaddr))
473 string u = scheme + "://" + val + "/";
474 return Uri.IsWellFormedUriString (u, UriKind.Absolute);
477 public DateTime IfModifiedSince {
479 string str = webHeaders ["If-Modified-Since"];
483 return MonoHttpDate.Parse (str);
484 } catch (Exception) {
489 CheckRequestStarted ();
491 webHeaders.SetInternal ("If-Modified-Since",
492 value.ToUniversalTime ().ToString ("r", null));
493 // TODO: check last param when using different locale
497 public bool KeepAlive {
506 public int MaximumAutomaticRedirections {
507 get { return maxAutoRedirect; }
510 throw new ArgumentException ("Must be > 0", "value");
512 maxAutoRedirect = value;
516 [MonoTODO ("Use this")]
517 public int MaximumResponseHeadersLength {
518 get { return maxResponseHeadersLength; }
519 set { maxResponseHeadersLength = value; }
522 [MonoTODO ("Use this")]
523 public static int DefaultMaximumResponseHeadersLength {
524 get { return defaultMaxResponseHeadersLength; }
525 set { defaultMaxResponseHeadersLength = value; }
528 public int ReadWriteTimeout {
529 get { return readWriteTimeout; }
532 throw new InvalidOperationException ("The request has already been sent.");
535 throw new ArgumentOutOfRangeException ("value", "Must be >= -1");
537 readWriteTimeout = value;
542 public int ContinueTimeout {
543 get { throw new NotImplementedException (); }
544 set { throw new NotImplementedException (); }
547 public string MediaType {
548 get { return mediaType; }
554 public override string Method {
555 get { return this.method; }
557 if (value == null || value.Trim () == "")
558 throw new ArgumentException ("not a valid method");
560 method = value.ToUpperInvariant ();
561 if (method != "HEAD" && method != "GET" && method != "POST" && method != "PUT" &&
562 method != "DELETE" && method != "CONNECT" && method != "TRACE" &&
569 public bool Pipelined {
570 get { return pipelined; }
571 set { pipelined = value; }
574 public override bool PreAuthenticate {
575 get { return preAuthenticate; }
576 set { preAuthenticate = value; }
579 public Version ProtocolVersion {
580 get { return version; }
582 if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
583 throw new ArgumentException ("value");
585 force_version = true;
590 public override IWebProxy Proxy {
591 get { return proxy; }
593 CheckRequestStarted ();
595 servicePoint = null; // we may need a new one
599 public string Referer {
600 get { return webHeaders ["Referer"]; }
602 CheckRequestStarted ();
603 if (value == null || value.Trim().Length == 0) {
604 webHeaders.RemoveInternal ("Referer");
607 webHeaders.SetInternal ("Referer", value);
611 public override Uri RequestUri {
612 get { return requestUri; }
615 public bool SendChunked {
616 get { return sendChunked; }
618 CheckRequestStarted ();
623 public ServicePoint ServicePoint {
624 get { return GetServicePoint (); }
627 internal ServicePoint ServicePointNoLock {
628 get { return servicePoint; }
630 public virtual bool SupportsCookieContainer {
632 // The managed implementation supports the cookie container
633 // it is only Silverlight that returns false here
637 public override int Timeout {
638 get { return timeout; }
641 throw new ArgumentOutOfRangeException ("value");
647 public string TransferEncoding {
648 get { return webHeaders ["Transfer-Encoding"]; }
650 CheckRequestStarted ();
653 val = val.Trim ().ToLower ();
655 if (val == null || val.Length == 0) {
656 webHeaders.RemoveInternal ("Transfer-Encoding");
660 if (val == "chunked")
661 throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
664 throw new ArgumentException ("SendChunked must be True", "value");
666 webHeaders.RemoveAndAdd ("Transfer-Encoding", value);
670 public override bool UseDefaultCredentials
672 get { return CredentialCache.DefaultCredentials == Credentials; }
673 set { Credentials = value ? CredentialCache.DefaultCredentials : null; }
676 public string UserAgent {
677 get { return webHeaders ["User-Agent"]; }
678 set { webHeaders.SetInternal ("User-Agent", value); }
681 bool unsafe_auth_blah;
682 public bool UnsafeAuthenticatedConnectionSharing
684 get { return unsafe_auth_blah; }
685 set { unsafe_auth_blah = value; }
688 internal bool GotRequestStream {
689 get { return gotRequestStream; }
692 internal bool ExpectContinue {
693 get { return expectContinue; }
694 set { expectContinue = value; }
697 internal Uri AuthUri {
698 get { return actualUri; }
701 internal bool ProxyQuery {
702 get { return servicePoint.UsesProxy && !servicePoint.UseConnect; }
705 internal ServerCertValidationCallback ServerCertValidationCallback {
706 get { return certValidationCallback; }
709 public RemoteCertificateValidationCallback ServerCertificateValidationCallback {
711 if (certValidationCallback == null)
713 return certValidationCallback.ValidationCallback;
718 certValidationCallback = null;
720 certValidationCallback = new ServerCertValidationCallback (value);
726 internal ServicePoint GetServicePoint ()
729 if (hostChanged || servicePoint == null) {
730 servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
738 public void AddRange (int range)
740 AddRange ("bytes", (long) range);
743 public void AddRange (int from, int to)
745 AddRange ("bytes", (long) from, (long) to);
748 public void AddRange (string rangeSpecifier, int range)
750 AddRange (rangeSpecifier, (long) range);
753 public void AddRange (string rangeSpecifier, int from, int to)
755 AddRange (rangeSpecifier, (long) from, (long) to);
758 void AddRange (long range)
760 AddRange ("bytes", (long) range);
764 void AddRange (long from, long to)
766 AddRange ("bytes", from, to);
770 void AddRange (string rangeSpecifier, long range)
772 if (rangeSpecifier == null)
773 throw new ArgumentNullException ("rangeSpecifier");
774 if (!WebHeaderCollection.IsHeaderValue (rangeSpecifier))
775 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
777 string r = webHeaders ["Range"];
779 r = rangeSpecifier + "=";
781 string old_specifier = r.Substring (0, r.IndexOf ('='));
782 if (String.Compare (old_specifier, rangeSpecifier, StringComparison.OrdinalIgnoreCase) != 0)
783 throw new InvalidOperationException ("A different range specifier is already in use");
787 string n = range.ToString (CultureInfo.InvariantCulture);
792 webHeaders.RemoveAndAdd ("Range", r);
796 void AddRange (string rangeSpecifier, long from, long to)
798 if (rangeSpecifier == null)
799 throw new ArgumentNullException ("rangeSpecifier");
800 if (!WebHeaderCollection.IsHeaderValue (rangeSpecifier))
801 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
802 if (from > to || from < 0)
803 throw new ArgumentOutOfRangeException ("from");
805 throw new ArgumentOutOfRangeException ("to");
807 string r = webHeaders ["Range"];
809 r = rangeSpecifier + "=";
813 r = String.Format ("{0}{1}-{2}", r, from, to);
814 webHeaders.RemoveAndAdd ("Range", r);
818 public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
821 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
823 bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
825 if (method == null || !send)
826 throw new ProtocolViolationException ("Cannot send data when method is: " + method);
828 if (contentLength == -1 && !sendChunked && !allowBuffering && KeepAlive)
829 throw new ProtocolViolationException ("Content-Length not set");
831 string transferEncoding = TransferEncoding;
832 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
833 throw new ProtocolViolationException ("SendChunked should be true.");
837 if (getResponseCalled)
838 throw new InvalidOperationException ("The operation cannot be performed once the request has been submitted.");
840 if (asyncWrite != null) {
841 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
842 "method while a previous call is still in progress.");
845 asyncWrite = new WebAsyncResult (this, callback, state);
846 initialMethod = method;
848 if (writeStream != null) {
849 asyncWrite.SetCompleted (true, writeStream);
850 asyncWrite.DoCallback ();
855 gotRequestStream = true;
856 WebAsyncResult result = asyncWrite;
860 servicePoint = GetServicePoint ();
861 abortHandler = servicePoint.SendRequest (this, connectionGroup);
867 public override Stream EndGetRequestStream (IAsyncResult asyncResult)
869 if (asyncResult == null)
870 throw new ArgumentNullException ("asyncResult");
872 WebAsyncResult result = asyncResult as WebAsyncResult;
874 throw new ArgumentException ("Invalid IAsyncResult");
877 result.WaitUntilComplete ();
879 Exception e = result.Exception;
883 return result.WriteStream;
886 public override Stream GetRequestStream()
888 IAsyncResult asyncResult = asyncWrite;
889 if (asyncResult == null) {
890 asyncResult = BeginGetRequestStream (null, null);
891 asyncWrite = (WebAsyncResult) asyncResult;
894 if (!asyncResult.IsCompleted && !asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
896 throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
899 return EndGetRequestStream (asyncResult);
902 bool CheckIfForceWrite (SimpleAsyncResult result)
904 if (writeStream == null || writeStream.RequestWritten || !InternalAllowBuffering)
906 if (contentLength < 0 && writeStream.CanWrite == true && writeStream.WriteBufferLength < 0)
909 if (contentLength < 0 && writeStream.WriteBufferLength >= 0)
910 InternalContentLength = writeStream.WriteBufferLength;
912 // This will write the POST/PUT if the write stream already has the expected
913 // amount of bytes in it (ContentLength) (bug #77753) or if the write stream
914 // contains data and it has been closed already (xamarin bug #1512).
916 if (writeStream.WriteBufferLength == contentLength || (contentLength == -1 && writeStream.CanWrite == false))
917 return writeStream.WriteRequestAsync (result);
922 public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
925 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
928 throw new ProtocolViolationException ("Method is null.");
930 string transferEncoding = TransferEncoding;
931 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
932 throw new ProtocolViolationException ("SendChunked should be true.");
934 Monitor.Enter (locker);
935 getResponseCalled = true;
936 if (asyncRead != null && !haveResponse) {
937 Monitor.Exit (locker);
938 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
939 "method while a previous call is still in progress.");
942 asyncRead = new WebAsyncResult (this, callback, state);
943 WebAsyncResult aread = asyncRead;
944 initialMethod = method;
946 SimpleAsyncResult.RunWithLock (locker, CheckIfForceWrite, inner => {
947 var synch = inner.CompletedSynchronously;
949 if (inner.GotException) {
950 aread.SetCompleted (synch, inner.Exception);
956 Exception saved = saved_exc;
957 if (webResponse != null) {
959 aread.SetCompleted (synch, webResponse);
961 aread.SetCompleted (synch, saved);
965 } else if (saved != null) {
966 aread.SetCompleted (synch, saved);
975 servicePoint = GetServicePoint ();
976 abortHandler = servicePoint.SendRequest (this, connectionGroup);
983 public override WebResponse EndGetResponse (IAsyncResult asyncResult)
985 if (asyncResult == null)
986 throw new ArgumentNullException ("asyncResult");
988 WebAsyncResult result = asyncResult as WebAsyncResult;
990 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
992 if (!result.WaitUntilComplete (timeout, false)) {
994 throw new WebException("The request timed out", WebExceptionStatus.Timeout);
997 if (result.GotException)
998 throw result.Exception;
1000 return result.Response;
1003 public Stream EndGetRequestStream (IAsyncResult asyncResult, out TransportContext transportContext)
1005 transportContext = null;
1006 return EndGetRequestStream (asyncResult);
1009 public override WebResponse GetResponse()
1011 WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
1012 return EndGetResponse (result);
1015 internal bool FinishedReading {
1016 get { return finished_reading; }
1017 set { finished_reading = value; }
1020 internal bool Aborted {
1021 get { return Interlocked.CompareExchange (ref aborted, 0, 0) == 1; }
1024 public override void Abort ()
1026 if (Interlocked.CompareExchange (ref aborted, 1, 0) == 1)
1029 if (haveResponse && finished_reading)
1032 haveResponse = true;
1033 if (abortHandler != null) {
1035 abortHandler (this, EventArgs.Empty);
1036 } catch (Exception) {}
1037 abortHandler = null;
1040 if (asyncWrite != null) {
1041 WebAsyncResult r = asyncWrite;
1042 if (!r.IsCompleted) {
1044 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
1045 r.SetCompleted (false, wexc);
1052 if (asyncRead != null) {
1053 WebAsyncResult r = asyncRead;
1054 if (!r.IsCompleted) {
1056 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
1057 r.SetCompleted (false, wexc);
1064 if (writeStream != null) {
1066 writeStream.Close ();
1071 if (webResponse != null) {
1073 webResponse.Close ();
1079 void ISerializable.GetObjectData (SerializationInfo serializationInfo,
1080 StreamingContext streamingContext)
1082 GetObjectData (serializationInfo, streamingContext);
1085 protected override void GetObjectData (SerializationInfo serializationInfo,
1086 StreamingContext streamingContext)
1088 SerializationInfo info = serializationInfo;
1090 info.AddValue ("requestUri", requestUri, typeof (Uri));
1091 info.AddValue ("actualUri", actualUri, typeof (Uri));
1092 info.AddValue ("allowAutoRedirect", allowAutoRedirect);
1093 info.AddValue ("allowBuffering", allowBuffering);
1094 info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
1095 info.AddValue ("connectionGroup", connectionGroup);
1096 info.AddValue ("contentLength", contentLength);
1097 info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
1098 info.AddValue ("keepAlive", keepAlive);
1099 info.AddValue ("maxAutoRedirect", maxAutoRedirect);
1100 info.AddValue ("mediaType", mediaType);
1101 info.AddValue ("method", method);
1102 info.AddValue ("initialMethod", initialMethod);
1103 info.AddValue ("pipelined", pipelined);
1104 info.AddValue ("version", version, typeof (Version));
1105 info.AddValue ("proxy", proxy, typeof (IWebProxy));
1106 info.AddValue ("sendChunked", sendChunked);
1107 info.AddValue ("timeout", timeout);
1108 info.AddValue ("redirects", redirects);
1109 info.AddValue ("host", host);
1112 void CheckRequestStarted ()
1115 throw new InvalidOperationException ("request started");
1118 internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
1120 if (continueDelegate != null)
1121 continueDelegate (statusCode, headers);
1124 void RewriteRedirectToGet ()
1127 webHeaders.RemoveInternal ("Transfer-Encoding");
1128 sendChunked = false;
1131 bool Redirect (WebAsyncResult result, HttpStatusCode code, WebResponse response)
1135 string uriString = null;
1137 case HttpStatusCode.Ambiguous: // 300
1138 e = new WebException ("Ambiguous redirect.");
1140 case HttpStatusCode.MovedPermanently: // 301
1141 case HttpStatusCode.Redirect: // 302
1142 if (method == "POST")
1143 RewriteRedirectToGet ();
1145 case HttpStatusCode.TemporaryRedirect: // 307
1147 case HttpStatusCode.SeeOther: //303
1148 RewriteRedirectToGet ();
1150 case HttpStatusCode.NotModified: // 304
1152 case HttpStatusCode.UseProxy: // 305
1153 e = new NotImplementedException ("Proxy support not available.");
1155 case HttpStatusCode.Unused: // 306
1157 e = new ProtocolViolationException ("Invalid status code: " + (int) code);
1161 if (method != "GET" && !InternalAllowBuffering && (writeStream.WriteBufferLength > 0 || contentLength > 0))
1162 e = new WebException ("The request requires buffering data to succeed.", null, WebExceptionStatus.ProtocolError, webResponse);
1167 if (AllowWriteStreamBuffering || method == "GET")
1170 uriString = webResponse.Headers ["Location"];
1172 if (uriString == null)
1173 throw new WebException ("No Location header found for " + (int) code,
1174 WebExceptionStatus.ProtocolError);
1176 Uri prev = actualUri;
1178 actualUri = new Uri (actualUri, uriString);
1179 } catch (Exception) {
1180 throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
1181 uriString, (int) code),
1182 WebExceptionStatus.ProtocolError);
1185 hostChanged = (actualUri.Scheme != prev.Scheme || Host != prev.Authority);
1189 string GetHeaders ()
1191 bool continue100 = false;
1194 webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
1195 webHeaders.RemoveInternal ("Content-Length");
1196 } else if (contentLength != -1) {
1197 if (auth_state.NtlmAuthState == NtlmAuthState.Challenge || proxy_auth_state.NtlmAuthState == NtlmAuthState.Challenge) {
1198 // We don't send any body with the NTLM Challenge request.
1199 if (haveContentLength || gotRequestStream || contentLength > 0)
1200 webHeaders.SetInternal ("Content-Length", "0");
1202 webHeaders.RemoveInternal ("Content-Length");
1204 if (contentLength > 0)
1207 if (haveContentLength || gotRequestStream || contentLength > 0)
1208 webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
1210 webHeaders.RemoveInternal ("Transfer-Encoding");
1212 webHeaders.RemoveInternal ("Content-Length");
1215 if (actualVersion == HttpVersion.Version11 && continue100 &&
1216 servicePoint.SendContinue) { // RFC2616 8.2.3
1217 webHeaders.RemoveAndAdd ("Expect" , "100-continue");
1218 expectContinue = true;
1220 webHeaders.RemoveInternal ("Expect");
1221 expectContinue = false;
1224 bool proxy_query = ProxyQuery;
1225 string connectionHeader = (proxy_query) ? "Proxy-Connection" : "Connection";
1226 webHeaders.RemoveInternal ((!proxy_query) ? "Proxy-Connection" : "Connection");
1227 Version proto_version = servicePoint.ProtocolVersion;
1228 bool spoint10 = (proto_version == null || proto_version == HttpVersion.Version10);
1230 if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
1231 if (webHeaders[connectionHeader] == null
1232 || webHeaders[connectionHeader].IndexOf ("keep-alive", StringComparison.OrdinalIgnoreCase) == -1)
1233 webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
1234 } else if (!keepAlive && version == HttpVersion.Version11) {
1235 webHeaders.RemoveAndAdd (connectionHeader, "close");
1238 webHeaders.SetInternal ("Host", Host);
1239 if (cookieContainer != null) {
1240 string cookieHeader = cookieContainer.GetCookieHeader (actualUri);
1241 if (cookieHeader != "")
1242 webHeaders.RemoveAndAdd ("Cookie", cookieHeader);
1244 webHeaders.RemoveInternal ("Cookie");
1247 string accept_encoding = null;
1248 if ((auto_decomp & DecompressionMethods.GZip) != 0)
1249 accept_encoding = "gzip";
1250 if ((auto_decomp & DecompressionMethods.Deflate) != 0)
1251 accept_encoding = accept_encoding != null ? "gzip, deflate" : "deflate";
1252 if (accept_encoding != null)
1253 webHeaders.RemoveAndAdd ("Accept-Encoding", accept_encoding);
1255 if (!usedPreAuth && preAuthenticate)
1256 DoPreAuthenticate ();
1258 return webHeaders.ToString ();
1261 void DoPreAuthenticate ()
1263 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1264 ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
1265 Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
1269 webHeaders.RemoveInternal ("Proxy-Authorization");
1270 webHeaders.RemoveInternal ("Authorization");
1271 string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
1272 webHeaders [authHeader] = auth.Message;
1276 internal void SetWriteStreamError (WebExceptionStatus status, Exception exc)
1281 WebAsyncResult r = asyncWrite;
1289 msg = "Error: " + status;
1290 wex = new WebException (msg, status);
1292 msg = String.Format ("Error: {0} ({1})", status, exc.Message);
1293 wex = new WebException (msg, exc, status);
1295 r.SetCompleted (false, wex);
1300 internal byte[] GetRequestHeaders ()
1302 StringBuilder req = new StringBuilder ();
1305 query = actualUri.PathAndQuery;
1307 query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
1309 actualUri.PathAndQuery);
1312 if (!force_version && servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
1313 actualVersion = servicePoint.ProtocolVersion;
1315 actualVersion = version;
1318 req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
1319 actualVersion.Major, actualVersion.Minor);
1320 req.Append (GetHeaders ());
1321 string reqstr = req.ToString ();
1322 return Encoding.UTF8.GetBytes (reqstr);
1325 internal void SetWriteStream (WebConnectionStream stream)
1330 writeStream = stream;
1331 if (bodyBuffer != null) {
1332 webHeaders.RemoveInternal ("Transfer-Encoding");
1333 contentLength = bodyBufferLength;
1334 writeStream.SendChunked = false;
1337 writeStream.SetHeadersAsync (false, result => {
1338 if (result.GotException) {
1339 SetWriteStreamError (result.Exception);
1345 SetWriteStreamInner (inner => {
1346 if (inner.GotException) {
1347 SetWriteStreamError (inner.Exception);
1351 if (asyncWrite != null) {
1352 asyncWrite.SetCompleted (inner.CompletedSynchronously, writeStream);
1353 asyncWrite.DoCallback ();
1360 void SetWriteStreamInner (SimpleAsyncCallback callback)
1362 SimpleAsyncResult.Run (result => {
1363 if (bodyBuffer != null) {
1364 // The body has been written and buffered. The request "user"
1365 // won't write it again, so we must do it.
1366 if (auth_state.NtlmAuthState != NtlmAuthState.Challenge && proxy_auth_state.NtlmAuthState != NtlmAuthState.Challenge) {
1367 // FIXME: this is a blocking call on the thread pool that could lead to thread pool exhaustion
1368 writeStream.Write (bodyBuffer, 0, bodyBufferLength);
1370 writeStream.Close ();
1372 } else if (MethodWithBuffer) {
1373 if (getResponseCalled && !writeStream.RequestWritten)
1374 return writeStream.WriteRequestAsync (result);
1381 void SetWriteStreamError (Exception exc)
1383 WebException wexc = exc as WebException;
1385 SetWriteStreamError (wexc.Status, wexc);
1387 SetWriteStreamError (WebExceptionStatus.SendFailure, exc);
1390 internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
1395 string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
1396 WebAsyncResult r = asyncRead;
1401 if (e is WebException) {
1402 wexc = (WebException) e;
1404 wexc = new WebException (msg, e, status, null);
1407 if (!r.IsCompleted) {
1408 r.SetCompleted (false, wexc);
1410 } else if (r == asyncWrite) {
1413 haveResponse = true;
1417 haveResponse = true;
1423 void CheckSendError (WebConnectionData data)
1425 // Got here, but no one called GetResponse
1426 int status = data.StatusCode;
1427 if (status < 400 || status == 401 || status == 407)
1430 if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
1431 // The request has not been completely sent and we got here!
1432 // We should probably just close and cause an error in any case,
1433 saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse);
1434 if (allowBuffering || sendChunked || writeStream.totalWritten >= contentLength) {
1435 webResponse.ReadAll ();
1437 writeStream.IgnoreIOErrors = true;
1442 bool HandleNtlmAuth (WebAsyncResult r)
1444 bool isProxy = webResponse.StatusCode == HttpStatusCode.ProxyAuthenticationRequired;
1445 if ((isProxy ? proxy_auth_state.NtlmAuthState : auth_state.NtlmAuthState) == NtlmAuthState.None)
1448 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1450 WebConnection cnc = wce.Connection;
1451 cnc.PriorityRequest = this;
1452 ICredentials creds = !isProxy ? credentials : proxy.Credentials;
1453 if (creds != null) {
1454 cnc.NtlmCredential = creds.GetCredential (requestUri, "NTLM");
1455 cnc.UnsafeAuthenticatedConnectionSharing = unsafe_auth_blah;
1459 finished_reading = false;
1460 haveResponse = false;
1461 webResponse.ReadAll ();
1466 internal void SetResponseData (WebConnectionData data)
1470 if (data.stream != null)
1471 data.stream.Close ();
1475 WebException wexc = null;
1477 webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
1478 } catch (Exception e) {
1479 wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null);
1480 if (data.stream != null)
1481 data.stream.Close ();
1484 if (wexc == null && (method == "POST" || method == "PUT")) {
1485 CheckSendError (data);
1486 if (saved_exc != null)
1487 wexc = (WebException) saved_exc;
1490 WebAsyncResult r = asyncRead;
1492 bool forced = false;
1493 if (r == null && webResponse != null) {
1494 // This is a forced completion (302, 204)...
1496 r = new WebAsyncResult (null, null);
1497 r.SetCompleted (false, webResponse);
1502 haveResponse = true;
1504 r.SetCompleted (false, wexc);
1509 bool isProxy = ProxyQuery && !proxy.IsBypassed (actualUri);
1513 redirected = CheckFinalStatus (r);
1515 if ((isProxy ? proxy_auth_state.IsNtlmAuthenticated : auth_state.IsNtlmAuthenticated) &&
1516 webResponse != null && (int)webResponse.StatusCode < 400) {
1517 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1519 WebConnection cnc = wce.Connection;
1520 cnc.NtlmAuthenticated = true;
1524 // clear internal buffer so that it does not
1525 // hold possible big buffer (bug #397627)
1526 if (writeStream != null)
1527 writeStream.KillBuffer ();
1529 haveResponse = true;
1530 r.SetCompleted (false, webResponse);
1534 sendChunked = false;
1535 webHeaders.RemoveInternal ("Transfer-Encoding");
1538 if (webResponse != null) {
1539 if (HandleNtlmAuth (r))
1541 webResponse.Close ();
1543 finished_reading = false;
1544 haveResponse = false;
1547 servicePoint = GetServicePoint ();
1548 abortHandler = servicePoint.SendRequest (this, connectionGroup);
1550 } catch (WebException wexc2) {
1553 haveResponse = true;
1555 r.SetCompleted (false, wexc2);
1558 } catch (Exception ex) {
1559 wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
1562 haveResponse = true;
1564 r.SetCompleted (false, wexc);
1572 struct AuthorizationState
1574 readonly HttpWebRequest request;
1575 readonly bool isProxy;
1577 NtlmAuthState ntlm_auth_state;
1579 public bool IsCompleted {
1580 get { return isCompleted; }
1583 public NtlmAuthState NtlmAuthState {
1584 get { return ntlm_auth_state; }
1587 public bool IsNtlmAuthenticated {
1588 get { return isCompleted && ntlm_auth_state != NtlmAuthState.None; }
1591 public AuthorizationState (HttpWebRequest request, bool isProxy)
1593 this.request = request;
1594 this.isProxy = isProxy;
1595 isCompleted = false;
1596 ntlm_auth_state = NtlmAuthState.None;
1599 public bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1601 isCompleted = false;
1602 if (code == HttpStatusCode.Unauthorized && request.credentials == null)
1605 // FIXME: This should never happen!
1606 if (isProxy != (code == HttpStatusCode.ProxyAuthenticationRequired))
1609 if (isProxy && (request.proxy == null || request.proxy.Credentials == null))
1612 string [] authHeaders = response.Headers.GetValues_internal (isProxy ? "Proxy-Authenticate" : "WWW-Authenticate", false);
1613 if (authHeaders == null || authHeaders.Length == 0)
1616 ICredentials creds = (!isProxy) ? request.credentials : request.proxy.Credentials;
1617 Authorization auth = null;
1618 foreach (string authHeader in authHeaders) {
1619 auth = AuthenticationManager.Authenticate (authHeader, request, creds);
1625 request.webHeaders [isProxy ? "Proxy-Authorization" : "Authorization"] = auth.Message;
1626 isCompleted = auth.Complete;
1627 bool is_ntlm = (auth.Module.AuthenticationType == "NTLM");
1629 ntlm_auth_state = (NtlmAuthState)((int) ntlm_auth_state + 1);
1633 public void Reset ()
1635 isCompleted = false;
1636 ntlm_auth_state = NtlmAuthState.None;
1637 request.webHeaders.RemoveInternal (isProxy ? "Proxy-Authorization" : "Authorization");
1640 public override string ToString ()
1642 return string.Format ("{0}AuthState [{1}:{2}]", isProxy ? "Proxy" : "", isCompleted, ntlm_auth_state);
1646 bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1648 bool isProxy = code == HttpStatusCode.ProxyAuthenticationRequired;
1649 return isProxy ? proxy_auth_state.CheckAuthorization (response, code) : auth_state.CheckAuthorization (response, code);
1652 // Returns true if redirected
1653 bool CheckFinalStatus (WebAsyncResult result)
1655 if (result.GotException) {
1657 throw result.Exception;
1660 Exception throwMe = result.Exception;
1662 HttpWebResponse resp = result.Response;
1663 WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
1664 HttpStatusCode code = 0;
1665 if (throwMe == null && webResponse != null) {
1666 code = webResponse.StatusCode;
1667 if ((!auth_state.IsCompleted && code == HttpStatusCode.Unauthorized && credentials != null) ||
1668 (ProxyQuery && !proxy_auth_state.IsCompleted && code == HttpStatusCode.ProxyAuthenticationRequired)) {
1669 if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
1670 // Keep the written body, so it can be rewritten in the retry
1671 if (MethodWithBuffer) {
1672 if (AllowWriteStreamBuffering) {
1673 if (writeStream.WriteBufferLength > 0) {
1674 bodyBuffer = writeStream.WriteBuffer;
1675 bodyBufferLength = writeStream.WriteBufferLength;
1682 // Buffering is not allowed but we have alternative way to get same content (we
1683 // need to resent it due to NTLM Authentication).
1685 if (ResendContentFactory != null) {
1686 using (var ms = new MemoryStream ()) {
1687 ResendContentFactory (ms);
1688 bodyBuffer = ms.ToArray ();
1689 bodyBufferLength = bodyBuffer.Length;
1693 } else if (method != "PUT" && method != "POST") {
1701 writeStream.InternalClose ();
1703 webResponse.Close ();
1707 throw new WebException ("This request requires buffering " +
1708 "of data for authentication or " +
1709 "redirection to be sucessful.");
1714 if ((int) code >= 400) {
1715 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1716 (int) code, webResponse.StatusDescription);
1717 throwMe = new WebException (err, null, protoError, webResponse);
1718 webResponse.ReadAll ();
1719 } else if ((int) code == 304 && allowAutoRedirect) {
1720 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1721 (int) code, webResponse.StatusDescription);
1722 throwMe = new WebException (err, null, protoError, webResponse);
1723 } else if ((int) code >= 300 && allowAutoRedirect && redirects >= maxAutoRedirect) {
1724 throwMe = new WebException ("Max. redirections exceeded.", null,
1725 protoError, webResponse);
1726 webResponse.ReadAll ();
1731 if (throwMe == null) {
1734 if (allowAutoRedirect && c >= 300) {
1735 b = Redirect (result, code, webResponse);
1736 if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
1737 bodyBuffer = writeStream.WriteBuffer;
1738 bodyBufferLength = writeStream.WriteBufferLength;
1740 if (b && !unsafe_auth_blah) {
1741 auth_state.Reset ();
1742 proxy_auth_state.Reset ();
1746 if (resp != null && c >= 300 && c != 304)
1755 if (writeStream != null) {
1756 writeStream.InternalClose ();
1765 internal bool ReuseConnection {
1770 internal WebConnection StoredConnection;