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;
38 using System.Net.Cache;
39 using System.Net.Sockets;
40 using System.Runtime.Remoting.Messaging;
41 using System.Runtime.Serialization;
42 using System.Security.Cryptography.X509Certificates;
44 using System.Threading;
49 internal class HttpWebRequest : WebRequest, ISerializable {
52 public class HttpWebRequest : WebRequest, ISerializable {
57 bool allowAutoRedirect = true;
58 bool allowBuffering = true;
59 X509CertificateCollection certificates;
60 string connectionGroup;
61 long contentLength = -1;
62 HttpContinueDelegate continueDelegate;
63 CookieContainer cookieContainer;
64 ICredentials credentials;
68 WebHeaderCollection webHeaders = new WebHeaderCollection (true);
69 bool keepAlive = true;
70 int maxAutoRedirect = 50;
71 string mediaType = String.Empty;
72 string method = "GET";
73 string initialMethod = "GET";
74 bool pipelined = true;
77 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;
96 bool getResponseCalled;
98 object locker = new object ();
99 bool finished_reading;
100 internal WebConnection WebConnection;
101 DecompressionMethods auto_decomp;
102 int maxResponseHeadersLength;
103 static int defaultMaxResponseHeadersLength;
104 int readWriteTimeout = 300000; // ms
111 NtlmAuthState ntlm_auth_state;
115 static HttpWebRequest ()
117 defaultMaxResponseHeadersLength = 64 * 1024;
119 NetConfig config = ConfigurationSettings.GetConfig ("system.net/settings") as NetConfig;
120 if (config != null) {
121 int x = config.MaxResponseHeadersLength;
125 defaultMaxResponseHeadersLength = x;
135 HttpWebRequest (Uri uri)
137 this.requestUri = uri;
138 this.actualUri = uri;
139 this.proxy = GlobalProxySelection.Select;
142 [Obsolete ("Serialization is obsoleted for this type", false)]
143 protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
145 SerializationInfo info = serializationInfo;
147 requestUri = (Uri) info.GetValue ("requestUri", typeof (Uri));
148 actualUri = (Uri) info.GetValue ("actualUri", typeof (Uri));
149 allowAutoRedirect = info.GetBoolean ("allowAutoRedirect");
150 allowBuffering = info.GetBoolean ("allowBuffering");
151 certificates = (X509CertificateCollection) info.GetValue ("certificates", typeof (X509CertificateCollection));
152 connectionGroup = info.GetString ("connectionGroup");
153 contentLength = info.GetInt64 ("contentLength");
154 webHeaders = (WebHeaderCollection) info.GetValue ("webHeaders", typeof (WebHeaderCollection));
155 keepAlive = info.GetBoolean ("keepAlive");
156 maxAutoRedirect = info.GetInt32 ("maxAutoRedirect");
157 mediaType = info.GetString ("mediaType");
158 method = info.GetString ("method");
159 initialMethod = info.GetString ("initialMethod");
160 pipelined = info.GetBoolean ("pipelined");
161 version = (Version) info.GetValue ("version", typeof (Version));
162 proxy = (IWebProxy) info.GetValue ("proxy", typeof (IWebProxy));
163 sendChunked = info.GetBoolean ("sendChunked");
164 timeout = info.GetInt32 ("timeout");
165 redirects = info.GetInt32 ("redirects");
166 host = info.GetString ("host");
171 public string Accept {
172 get { return webHeaders ["Accept"]; }
174 CheckRequestStarted ();
175 webHeaders.RemoveAndAdd ("Accept", value);
180 get { return actualUri; }
183 public bool AllowAutoRedirect {
184 get { return allowAutoRedirect; }
185 set { this.allowAutoRedirect = value; }
188 public bool AllowWriteStreamBuffering {
189 get { return allowBuffering; }
190 set { allowBuffering = value; }
193 static Exception GetMustImplement ()
195 return new NotImplementedException ();
198 public DecompressionMethods AutomaticDecompression
204 CheckRequestStarted ();
209 internal bool InternalAllowBuffering {
211 return (allowBuffering && (method != "HEAD" && method != "GET" &&
212 method != "MKCOL" && method != "CONNECT" &&
217 public X509CertificateCollection ClientCertificates {
219 if (certificates == null)
220 certificates = new X509CertificateCollection ();
226 throw GetMustImplement ();
230 public string Connection {
231 get { return webHeaders ["Connection"]; }
233 CheckRequestStarted ();
236 val = val.Trim ().ToLower ();
238 if (val == null || val.Length == 0) {
239 webHeaders.RemoveInternal ("Connection");
243 if (val == "keep-alive" || val == "close")
244 throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
246 if (keepAlive && val.IndexOf ("keep-alive", StringComparison.Ordinal) == -1)
247 value = value + ", Keep-Alive";
249 webHeaders.RemoveAndAdd ("Connection", value);
253 public override string ConnectionGroupName {
254 get { return connectionGroup; }
255 set { connectionGroup = value; }
258 public override long ContentLength {
259 get { return contentLength; }
261 CheckRequestStarted ();
263 throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
265 contentLength = value;
269 internal long InternalContentLength {
270 set { contentLength = value; }
273 public override string ContentType {
274 get { return webHeaders ["Content-Type"]; }
276 if (value == null || value.Trim().Length == 0) {
277 webHeaders.RemoveInternal ("Content-Type");
280 webHeaders.RemoveAndAdd ("Content-Type", value);
284 public HttpContinueDelegate ContinueDelegate {
285 get { return continueDelegate; }
286 set { continueDelegate = value; }
289 public CookieContainer CookieContainer {
290 get { return cookieContainer; }
291 set { cookieContainer = value; }
294 public override ICredentials Credentials {
295 get { return credentials; }
296 set { credentials = value; }
300 public static new RequestCachePolicy DefaultCachePolicy
303 throw GetMustImplement ();
306 throw GetMustImplement ();
311 public static int DefaultMaximumErrorResponseLength
314 throw GetMustImplement ();
317 throw GetMustImplement ();
321 public string Expect {
322 get { return webHeaders ["Expect"]; }
324 CheckRequestStarted ();
327 val = val.Trim ().ToLower ();
329 if (val == null || val.Length == 0) {
330 webHeaders.RemoveInternal ("Expect");
334 if (val == "100-continue")
335 throw new ArgumentException ("100-Continue cannot be set with this property.",
337 webHeaders.RemoveAndAdd ("Expect", value);
341 public bool HaveResponse {
342 get { return haveResponse; }
345 public override WebHeaderCollection Headers {
346 get { return webHeaders; }
348 CheckRequestStarted ();
349 WebHeaderCollection newHeaders = new WebHeaderCollection (true);
350 int count = value.Count;
351 for (int i = 0; i < count; i++)
352 newHeaders.Add (value.GetKey (i), value.Get (i));
354 webHeaders = newHeaders;
365 return actualUri.Authority;
370 throw new ArgumentNullException ("value");
372 if (!CheckValidHost (value))
373 throw new ArgumentException ("Invalid host: " + value);
379 static char [] colon = { ':' };
380 static bool CheckValidHost (string val)
383 throw new ArgumentNullException ("value");
391 string [] parts = val.Split ('.');
392 int l = parts.Length;
393 string [] last = parts [l - 1].Split (colon, 2);
394 if (last.Length == 2) {
395 parts [l - 1] = last [0];
397 if (!UInt16.TryParse (parts [1], out port))
401 // MS does not enforce a max. 255 length
402 // MS does not complain about a leading dash or all numbers...
406 public DateTime IfModifiedSince {
408 string str = webHeaders ["If-Modified-Since"];
412 return MonoHttpDate.Parse (str);
413 } catch (Exception) {
418 CheckRequestStarted ();
420 webHeaders.SetInternal ("If-Modified-Since",
421 value.ToUniversalTime ().ToString ("r", null));
422 // TODO: check last param when using different locale
426 public bool KeepAlive {
435 public int MaximumAutomaticRedirections {
436 get { return maxAutoRedirect; }
439 throw new ArgumentException ("Must be > 0", "value");
441 maxAutoRedirect = value;
445 [MonoTODO ("Use this")]
446 public int MaximumResponseHeadersLength {
447 get { return maxResponseHeadersLength; }
448 set { maxResponseHeadersLength = value; }
451 [MonoTODO ("Use this")]
452 public static int DefaultMaximumResponseHeadersLength {
453 get { return defaultMaxResponseHeadersLength; }
454 set { defaultMaxResponseHeadersLength = value; }
457 public int ReadWriteTimeout {
458 get { return readWriteTimeout; }
461 throw new InvalidOperationException ("The request has already been sent.");
464 throw new ArgumentOutOfRangeException ("value", "Must be >= -1");
466 readWriteTimeout = value;
470 public string MediaType {
471 get { return mediaType; }
477 public override string Method {
478 get { return this.method; }
480 if (value == null || value.Trim () == "")
481 throw new ArgumentException ("not a valid method");
487 public bool Pipelined {
488 get { return pipelined; }
489 set { pipelined = value; }
492 public override bool PreAuthenticate {
493 get { return preAuthenticate; }
494 set { preAuthenticate = value; }
497 public Version ProtocolVersion {
498 get { return version; }
500 if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
501 throw new ArgumentException ("value");
507 public override IWebProxy Proxy {
508 get { return proxy; }
510 CheckRequestStarted ();
512 servicePoint = null; // we may need a new one
516 public string Referer {
517 get { return webHeaders ["Referer"]; }
519 CheckRequestStarted ();
520 if (value == null || value.Trim().Length == 0) {
521 webHeaders.RemoveInternal ("Referer");
524 webHeaders.SetInternal ("Referer", value);
528 public override Uri RequestUri {
529 get { return requestUri; }
532 public bool SendChunked {
533 get { return sendChunked; }
535 CheckRequestStarted ();
540 public ServicePoint ServicePoint {
541 get { return GetServicePoint (); }
544 public override int Timeout {
545 get { return timeout; }
548 throw new ArgumentOutOfRangeException ("value");
554 public string TransferEncoding {
555 get { return webHeaders ["Transfer-Encoding"]; }
557 CheckRequestStarted ();
560 val = val.Trim ().ToLower ();
562 if (val == null || val.Length == 0) {
563 webHeaders.RemoveInternal ("Transfer-Encoding");
567 if (val == "chunked")
568 throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
571 throw new ArgumentException ("SendChunked must be True", "value");
573 webHeaders.RemoveAndAdd ("Transfer-Encoding", value);
577 public override bool UseDefaultCredentials
579 get { return CredentialCache.DefaultCredentials == Credentials; }
580 set { Credentials = value ? CredentialCache.DefaultCredentials : null; }
583 public string UserAgent {
584 get { return webHeaders ["User-Agent"]; }
585 set { webHeaders.SetInternal ("User-Agent", value); }
588 bool unsafe_auth_blah;
589 public bool UnsafeAuthenticatedConnectionSharing
591 get { return unsafe_auth_blah; }
592 set { unsafe_auth_blah = value; }
595 internal bool GotRequestStream {
596 get { return gotRequestStream; }
599 internal bool ExpectContinue {
600 get { return expectContinue; }
601 set { expectContinue = value; }
604 internal Uri AuthUri {
605 get { return actualUri; }
608 internal bool ProxyQuery {
609 get { return servicePoint.UsesProxy && !servicePoint.UseConnect; }
614 internal ServicePoint GetServicePoint ()
617 if (hostChanged || servicePoint == null) {
618 servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
626 public void AddRange (int range)
628 AddRange ("bytes", range);
631 public void AddRange (int from, int to)
633 AddRange ("bytes", from, to);
636 public void AddRange (string rangeSpecifier, int range)
638 if (rangeSpecifier == null)
639 throw new ArgumentNullException ("rangeSpecifier");
640 string value = webHeaders ["Range"];
641 if (value == null || value.Length == 0)
642 value = rangeSpecifier + "=";
643 else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
646 throw new InvalidOperationException ("rangeSpecifier");
647 webHeaders.RemoveAndAdd ("Range", value + range + "-");
650 public void AddRange (string rangeSpecifier, int from, int to)
652 if (rangeSpecifier == null)
653 throw new ArgumentNullException ("rangeSpecifier");
654 if (from < 0 || to < 0 || from > to)
655 throw new ArgumentOutOfRangeException ();
656 string value = webHeaders ["Range"];
657 if (value == null || value.Length == 0)
658 value = rangeSpecifier + "=";
659 else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
662 throw new InvalidOperationException ("rangeSpecifier");
663 webHeaders.RemoveAndAdd ("Range", value + from + "-" + to);
666 public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
669 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
671 bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
673 if (method == null || !send)
674 throw new ProtocolViolationException ("Cannot send data when method is: " + method);
676 if (contentLength == -1 && !sendChunked && !allowBuffering && KeepAlive)
677 throw new ProtocolViolationException ("Content-Length not set");
679 string transferEncoding = TransferEncoding;
680 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
681 throw new ProtocolViolationException ("SendChunked should be true.");
685 if (asyncWrite != null) {
686 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
687 "method while a previous call is still in progress.");
690 asyncWrite = new WebAsyncResult (this, callback, state);
691 initialMethod = method;
693 if (writeStream != null) {
694 asyncWrite.SetCompleted (true, writeStream);
695 asyncWrite.DoCallback ();
700 gotRequestStream = true;
701 WebAsyncResult result = asyncWrite;
705 servicePoint = GetServicePoint ();
706 abortHandler = servicePoint.SendRequest (this, connectionGroup);
712 public override Stream EndGetRequestStream (IAsyncResult asyncResult)
714 if (asyncResult == null)
715 throw new ArgumentNullException ("asyncResult");
717 WebAsyncResult result = asyncResult as WebAsyncResult;
719 throw new ArgumentException ("Invalid IAsyncResult");
722 result.WaitUntilComplete ();
724 Exception e = result.Exception;
728 return result.WriteStream;
731 public override Stream GetRequestStream()
733 IAsyncResult asyncResult = asyncWrite;
734 if (asyncResult == null) {
735 asyncResult = BeginGetRequestStream (null, null);
736 asyncWrite = (WebAsyncResult) asyncResult;
739 if (!asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
741 throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
744 return EndGetRequestStream (asyncResult);
747 void CheckIfForceWrite ()
749 if (writeStream == null || writeStream.RequestWritten|| contentLength < 0 || !InternalAllowBuffering)
752 // This will write the POST/PUT if the write stream already has the expected
753 // amount of bytes in it (ContentLength) (bug #77753).
754 if (writeStream.WriteBufferLength == contentLength)
755 writeStream.WriteRequest ();
758 public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
761 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
764 throw new ProtocolViolationException ("Method is null.");
766 string transferEncoding = TransferEncoding;
767 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
768 throw new ProtocolViolationException ("SendChunked should be true.");
770 Monitor.Enter (locker);
771 getResponseCalled = true;
772 if (asyncRead != null && !haveResponse) {
773 Monitor.Exit (locker);
774 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
775 "method while a previous call is still in progress.");
778 CheckIfForceWrite ();
779 asyncRead = new WebAsyncResult (this, callback, state);
780 WebAsyncResult aread = asyncRead;
781 initialMethod = method;
783 Exception saved = saved_exc;
784 if (webResponse != null) {
785 Monitor.Exit (locker);
787 aread.SetCompleted (true, webResponse);
789 aread.SetCompleted (true, saved);
793 } else if (saved != null) {
794 Monitor.Exit (locker);
795 aread.SetCompleted (true, saved);
804 servicePoint = GetServicePoint ();
805 abortHandler = servicePoint.SendRequest (this, connectionGroup);
808 Monitor.Exit (locker);
812 public override WebResponse EndGetResponse (IAsyncResult asyncResult)
814 if (asyncResult == null)
815 throw new ArgumentNullException ("asyncResult");
817 WebAsyncResult result = asyncResult as WebAsyncResult;
819 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
821 if (!result.WaitUntilComplete (timeout, false)) {
823 throw new WebException("The request timed out", WebExceptionStatus.Timeout);
826 if (result.GotException)
827 throw result.Exception;
829 return result.Response;
832 public override WebResponse GetResponse()
834 WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
835 return EndGetResponse (result);
838 internal bool FinishedReading {
839 get { return finished_reading; }
840 set { finished_reading = value; }
843 internal bool Aborted {
844 get { return Interlocked.CompareExchange (ref aborted, 0, 0) == 1; }
847 public override void Abort ()
849 if (Interlocked.CompareExchange (ref aborted, 1, 0) == 1)
852 if (haveResponse && finished_reading)
856 if (abortHandler != null) {
858 abortHandler (this, EventArgs.Empty);
859 } catch (Exception) {}
863 if (asyncWrite != null) {
864 WebAsyncResult r = asyncWrite;
865 if (!r.IsCompleted) {
867 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
868 r.SetCompleted (false, wexc);
875 if (asyncRead != null) {
876 WebAsyncResult r = asyncRead;
877 if (!r.IsCompleted) {
879 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
880 r.SetCompleted (false, wexc);
887 if (writeStream != null) {
889 writeStream.Close ();
894 if (webResponse != null) {
896 webResponse.Close ();
902 void ISerializable.GetObjectData (SerializationInfo serializationInfo,
903 StreamingContext streamingContext)
905 GetObjectData (serializationInfo, streamingContext);
908 protected override void GetObjectData (SerializationInfo serializationInfo,
909 StreamingContext streamingContext)
911 SerializationInfo info = serializationInfo;
913 info.AddValue ("requestUri", requestUri, typeof (Uri));
914 info.AddValue ("actualUri", actualUri, typeof (Uri));
915 info.AddValue ("allowAutoRedirect", allowAutoRedirect);
916 info.AddValue ("allowBuffering", allowBuffering);
917 info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
918 info.AddValue ("connectionGroup", connectionGroup);
919 info.AddValue ("contentLength", contentLength);
920 info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
921 info.AddValue ("keepAlive", keepAlive);
922 info.AddValue ("maxAutoRedirect", maxAutoRedirect);
923 info.AddValue ("mediaType", mediaType);
924 info.AddValue ("method", method);
925 info.AddValue ("initialMethod", initialMethod);
926 info.AddValue ("pipelined", pipelined);
927 info.AddValue ("version", version, typeof (Version));
928 info.AddValue ("proxy", proxy, typeof (IWebProxy));
929 info.AddValue ("sendChunked", sendChunked);
930 info.AddValue ("timeout", timeout);
931 info.AddValue ("redirects", redirects);
932 info.AddValue ("host", host);
935 void CheckRequestStarted ()
938 throw new InvalidOperationException ("request started");
941 internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
943 if (continueDelegate != null)
944 continueDelegate (statusCode, headers);
947 bool Redirect (WebAsyncResult result, HttpStatusCode code)
951 string uriString = null;
954 case HttpStatusCode.Ambiguous: // 300
955 e = new WebException ("Ambiguous redirect.");
957 case HttpStatusCode.MovedPermanently: // 301
958 case HttpStatusCode.Redirect: // 302
959 case HttpStatusCode.TemporaryRedirect: // 307
960 /* MS follows the redirect for POST too
961 if (method != "GET" && method != "HEAD") // 10.3
966 bodyBufferLength = 0;
968 if (code != HttpStatusCode.TemporaryRedirect)
970 uriString = webResponse.Headers ["Location"];
972 case HttpStatusCode.SeeOther: //303
974 uriString = webResponse.Headers ["Location"];
976 case HttpStatusCode.NotModified: // 304
978 case HttpStatusCode.UseProxy: // 305
979 e = new NotImplementedException ("Proxy support not available.");
981 case HttpStatusCode.Unused: // 306
983 e = new ProtocolViolationException ("Invalid status code: " + (int) code);
990 if (uriString == null)
991 throw new WebException ("No Location header found for " + (int) code,
992 WebExceptionStatus.ProtocolError);
994 Uri prev = actualUri;
996 actualUri = new Uri (actualUri, uriString);
997 } catch (Exception) {
998 throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
999 uriString, (int) code),
1000 WebExceptionStatus.ProtocolError);
1003 hostChanged = (actualUri.Scheme != prev.Scheme || Host != prev.Authority);
1007 string GetHeaders ()
1009 bool continue100 = false;
1012 webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
1013 webHeaders.RemoveInternal ("Content-Length");
1014 } else if (contentLength != -1) {
1015 if (ntlm_auth_state != NtlmAuthState.Challenge) {
1016 if (contentLength > 0)
1019 webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
1021 webHeaders.SetInternal ("Content-Length", "0");
1023 webHeaders.RemoveInternal ("Transfer-Encoding");
1025 webHeaders.RemoveInternal ("Content-Length");
1028 if (actualVersion == HttpVersion.Version11 && continue100 &&
1029 servicePoint.SendContinue) { // RFC2616 8.2.3
1030 webHeaders.RemoveAndAdd ("Expect" , "100-continue");
1031 expectContinue = true;
1033 webHeaders.RemoveInternal ("Expect");
1034 expectContinue = false;
1037 bool proxy_query = ProxyQuery;
1038 string connectionHeader = (proxy_query) ? "Proxy-Connection" : "Connection";
1039 webHeaders.RemoveInternal ((!proxy_query) ? "Proxy-Connection" : "Connection");
1040 Version proto_version = servicePoint.ProtocolVersion;
1041 bool spoint10 = (proto_version == null || proto_version == HttpVersion.Version10);
1043 if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
1044 webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
1045 } else if (!keepAlive && version == HttpVersion.Version11) {
1046 webHeaders.RemoveAndAdd (connectionHeader, "close");
1049 webHeaders.SetInternal ("Host", Host);
1050 if (cookieContainer != null) {
1051 string cookieHeader = cookieContainer.GetCookieHeader (actualUri);
1052 if (cookieHeader != "")
1053 webHeaders.SetInternal ("Cookie", cookieHeader);
1056 string accept_encoding = null;
1057 if ((auto_decomp & DecompressionMethods.GZip) != 0)
1058 accept_encoding = "gzip";
1059 if ((auto_decomp & DecompressionMethods.Deflate) != 0)
1060 accept_encoding = accept_encoding != null ? "gzip, deflate" : "deflate";
1061 if (accept_encoding != null)
1062 webHeaders.RemoveAndAdd ("Accept-Encoding", accept_encoding);
1064 if (!usedPreAuth && preAuthenticate)
1065 DoPreAuthenticate ();
1067 return webHeaders.ToString ();
1070 void DoPreAuthenticate ()
1072 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1073 ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
1074 Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
1078 webHeaders.RemoveInternal ("Proxy-Authorization");
1079 webHeaders.RemoveInternal ("Authorization");
1080 string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
1081 webHeaders [authHeader] = auth.Message;
1085 internal void SetWriteStreamError (WebExceptionStatus status, Exception exc)
1090 WebAsyncResult r = asyncWrite;
1098 msg = "Error: " + status;
1099 wex = new WebException (msg, status);
1101 msg = String.Format ("Error: {0} ({1})", status, exc.Message);
1102 wex = new WebException (msg, exc, status);
1104 r.SetCompleted (false, wex);
1109 internal void SendRequestHeaders (bool propagate_error)
1111 StringBuilder req = new StringBuilder ();
1114 query = actualUri.PathAndQuery;
1116 query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
1118 actualUri.PathAndQuery);
1121 if (servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
1122 actualVersion = servicePoint.ProtocolVersion;
1124 actualVersion = version;
1127 req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
1128 actualVersion.Major, actualVersion.Minor);
1129 req.Append (GetHeaders ());
1130 string reqstr = req.ToString ();
1131 byte [] bytes = Encoding.UTF8.GetBytes (reqstr);
1133 writeStream.SetHeaders (bytes);
1134 } catch (WebException wexc) {
1135 SetWriteStreamError (wexc.Status, wexc);
1136 if (propagate_error)
1138 } catch (Exception exc) {
1139 SetWriteStreamError (WebExceptionStatus.SendFailure, exc);
1140 if (propagate_error)
1145 internal void SetWriteStream (WebConnectionStream stream)
1150 writeStream = stream;
1151 if (bodyBuffer != null) {
1152 webHeaders.RemoveInternal ("Transfer-Encoding");
1153 contentLength = bodyBufferLength;
1154 writeStream.SendChunked = false;
1157 SendRequestHeaders (false);
1161 if (bodyBuffer != null) {
1162 // The body has been written and buffered. The request "user"
1163 // won't write it again, so we must do it.
1164 if (ntlm_auth_state != NtlmAuthState.Challenge) {
1165 writeStream.Write (bodyBuffer, 0, bodyBufferLength);
1167 writeStream.Close ();
1169 } else if (method != "HEAD" && method != "GET" && method != "MKCOL" && method != "CONNECT" &&
1170 method != "TRACE") {
1171 if (getResponseCalled && !writeStream.RequestWritten)
1172 writeStream.WriteRequest ();
1175 if (asyncWrite != null) {
1176 asyncWrite.SetCompleted (false, stream);
1177 asyncWrite.DoCallback ();
1182 internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
1187 string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
1188 WebAsyncResult r = asyncRead;
1193 if (e is WebException) {
1194 wexc = (WebException) e;
1196 wexc = new WebException (msg, e, status, null);
1199 if (!r.IsCompleted) {
1200 r.SetCompleted (false, wexc);
1202 } else if (r == asyncWrite) {
1205 haveResponse = true;
1209 haveResponse = true;
1215 void CheckSendError (WebConnectionData data)
1217 // Got here, but no one called GetResponse
1218 int status = data.StatusCode;
1219 if (status < 400 || status == 401 || status == 407)
1222 if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
1223 // The request has not been completely sent and we got here!
1224 // We should probably just close and cause an error in any case,
1225 saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse);
1226 webResponse.ReadAll ();
1230 void HandleNtlmAuth (WebAsyncResult r)
1232 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1234 WebConnection cnc = wce.Connection;
1235 cnc.PriorityRequest = this;
1236 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1237 ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1238 if (creds != null) {
1239 cnc.NtlmCredential = creds.GetCredential (requestUri, "NTLM");
1240 cnc.UnsafeAuthenticatedConnectionSharing = unsafe_auth_blah;
1244 finished_reading = false;
1245 haveResponse = false;
1246 webResponse.ReadAll ();
1250 internal void SetResponseData (WebConnectionData data)
1254 if (data.stream != null)
1255 data.stream.Close ();
1259 WebException wexc = null;
1261 webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
1262 } catch (Exception e) {
1263 wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null);
1264 if (data.stream != null)
1265 data.stream.Close ();
1268 if (wexc == null && (method == "POST" || method == "PUT")) {
1270 CheckSendError (data);
1271 if (saved_exc != null)
1272 wexc = (WebException) saved_exc;
1276 WebAsyncResult r = asyncRead;
1278 bool forced = false;
1279 if (r == null && webResponse != null) {
1280 // This is a forced completion (302, 204)...
1282 r = new WebAsyncResult (null, null);
1283 r.SetCompleted (false, webResponse);
1288 haveResponse = true;
1289 r.SetCompleted (false, wexc);
1296 redirected = CheckFinalStatus (r);
1298 if (ntlm_auth_state != NtlmAuthState.None && authCompleted && webResponse != null
1299 && (int)webResponse.StatusCode < 400) {
1300 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1302 WebConnection cnc = wce.Connection;
1303 cnc.NtlmAuthenticated = true;
1307 // clear internal buffer so that it does not
1308 // hold possible big buffer (bug #397627)
1309 if (writeStream != null)
1310 writeStream.KillBuffer ();
1312 haveResponse = true;
1313 r.SetCompleted (false, webResponse);
1316 if (webResponse != null) {
1317 if (ntlm_auth_state != NtlmAuthState.None) {
1321 webResponse.Close ();
1323 finished_reading = false;
1324 haveResponse = false;
1327 servicePoint = GetServicePoint ();
1328 abortHandler = servicePoint.SendRequest (this, connectionGroup);
1330 } catch (WebException wexc2) {
1333 haveResponse = true;
1335 r.SetCompleted (false, wexc2);
1338 } catch (Exception ex) {
1339 wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
1342 haveResponse = true;
1344 r.SetCompleted (false, wexc);
1352 bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1354 authCompleted = false;
1355 if (code == HttpStatusCode.Unauthorized && credentials == null)
1358 bool isProxy = (code == HttpStatusCode.ProxyAuthenticationRequired);
1359 if (isProxy && (proxy == null || proxy.Credentials == null))
1362 string [] authHeaders = response.Headers.GetValues ( (isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate");
1363 if (authHeaders == null || authHeaders.Length == 0)
1366 ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1367 Authorization auth = null;
1368 foreach (string authHeader in authHeaders) {
1369 auth = AuthenticationManager.Authenticate (authHeader, this, creds);
1375 webHeaders [(isProxy) ? "Proxy-Authorization" : "Authorization"] = auth.Message;
1376 authCompleted = auth.Complete;
1377 bool is_ntlm = (auth.Module.AuthenticationType == "NTLM");
1379 ntlm_auth_state = (NtlmAuthState)((int) ntlm_auth_state + 1);
1383 // Returns true if redirected
1384 bool CheckFinalStatus (WebAsyncResult result)
1386 if (result.GotException) {
1388 throw result.Exception;
1391 Exception throwMe = result.Exception;
1393 HttpWebResponse resp = result.Response;
1394 WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
1395 HttpStatusCode code = 0;
1396 if (throwMe == null && webResponse != null) {
1397 code = webResponse.StatusCode;
1398 if (!authCompleted && ((code == HttpStatusCode.Unauthorized && credentials != null) ||
1399 (ProxyQuery && code == HttpStatusCode.ProxyAuthenticationRequired))) {
1400 if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
1401 // Keep the written body, so it can be rewritten in the retry
1402 if (InternalAllowBuffering) {
1403 // NTLM: This is to avoid sending data in the 'challenge' request
1404 // We save it in the first request (first 401), don't send anything
1405 // in the challenge request and send it in the response request along
1406 // with the buffers kept form the first request.
1407 if (ntlm_auth_state != NtlmAuthState.Response) {
1408 bodyBuffer = writeStream.WriteBuffer;
1409 bodyBufferLength = writeStream.WriteBufferLength;
1412 } else if (method != "PUT" && method != "POST") {
1417 writeStream.InternalClose ();
1419 webResponse.Close ();
1423 throw new WebException ("This request requires buffering " +
1424 "of data for authentication or " +
1425 "redirection to be sucessful.");
1430 if ((int) code >= 400) {
1431 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1432 (int) code, webResponse.StatusDescription);
1433 throwMe = new WebException (err, null, protoError, webResponse);
1434 webResponse.ReadAll ();
1435 } else if ((int) code == 304 && allowAutoRedirect) {
1436 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1437 (int) code, webResponse.StatusDescription);
1438 throwMe = new WebException (err, null, protoError, webResponse);
1439 } else if ((int) code >= 300 && allowAutoRedirect && redirects >= maxAutoRedirect) {
1440 throwMe = new WebException ("Max. redirections exceeded.", null,
1441 protoError, webResponse);
1442 webResponse.ReadAll ();
1447 if (throwMe == null) {
1450 if (allowAutoRedirect && c >= 300) {
1451 if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
1452 bodyBuffer = writeStream.WriteBuffer;
1453 bodyBufferLength = writeStream.WriteBufferLength;
1455 b = Redirect (result, code);
1458 if (resp != null && c >= 300 && c != 304)
1464 if (writeStream != null) {
1465 writeStream.InternalClose ();