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.Sockets;
39 using System.Runtime.Remoting.Messaging;
40 using System.Runtime.Serialization;
41 using System.Security.Cryptography.X509Certificates;
43 using System.Threading;
46 using System.Net.Cache;
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 ();
100 bool finished_reading;
101 internal WebConnection WebConnection;
103 DecompressionMethods auto_decomp;
106 int maxResponseHeadersLength;
107 static int defaultMaxResponseHeadersLength;
108 int readWriteTimeout = 300000; // ms
111 static HttpWebRequest ()
113 NetConfig config = ConfigurationSettings.GetConfig ("system.net/settings") as NetConfig;
114 defaultMaxResponseHeadersLength = 64 * 1024;
115 if (config != null) {
116 int x = config.MaxResponseHeadersLength;
120 defaultMaxResponseHeadersLength = x;
130 HttpWebRequest (Uri uri)
132 this.requestUri = uri;
133 this.actualUri = uri;
134 this.proxy = GlobalProxySelection.Select;
138 [Obsolete ("Serialization is obsoleted for this type", false)]
140 protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
142 SerializationInfo info = serializationInfo;
144 requestUri = (Uri) info.GetValue ("requestUri", typeof (Uri));
145 actualUri = (Uri) info.GetValue ("actualUri", typeof (Uri));
146 allowAutoRedirect = info.GetBoolean ("allowAutoRedirect");
147 allowBuffering = info.GetBoolean ("allowBuffering");
148 certificates = (X509CertificateCollection) info.GetValue ("certificates", typeof (X509CertificateCollection));
149 connectionGroup = info.GetString ("connectionGroup");
150 contentLength = info.GetInt64 ("contentLength");
151 webHeaders = (WebHeaderCollection) info.GetValue ("webHeaders", typeof (WebHeaderCollection));
152 keepAlive = info.GetBoolean ("keepAlive");
153 maxAutoRedirect = info.GetInt32 ("maxAutoRedirect");
154 mediaType = info.GetString ("mediaType");
155 method = info.GetString ("method");
156 initialMethod = info.GetString ("initialMethod");
157 pipelined = info.GetBoolean ("pipelined");
158 version = (Version) info.GetValue ("version", typeof (Version));
159 proxy = (IWebProxy) info.GetValue ("proxy", typeof (IWebProxy));
160 sendChunked = info.GetBoolean ("sendChunked");
161 timeout = info.GetInt32 ("timeout");
162 redirects = info.GetInt32 ("redirects");
167 internal bool UsesNtlmAuthentication {
168 get { return is_ntlm_auth; }
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; }
194 static Exception GetMustImplement ()
196 return new NotImplementedException ();
199 public DecompressionMethods AutomaticDecompression
205 CheckRequestStarted ();
211 internal bool InternalAllowBuffering {
213 return (allowBuffering && (method != "HEAD" && method != "GET" &&
214 method != "MKCOL" && method != "CONNECT" &&
215 method != "DELETE" && method != "TRACE"));
219 public X509CertificateCollection ClientCertificates {
221 if (certificates == null)
222 certificates = new X509CertificateCollection ();
229 throw GetMustImplement ();
234 public string Connection {
235 get { return webHeaders ["Connection"]; }
237 CheckRequestStarted ();
240 val = val.Trim ().ToLower ();
242 if (val == null || val.Length == 0) {
243 webHeaders.RemoveInternal ("Connection");
247 if (val == "keep-alive" || val == "close")
248 throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
250 if (keepAlive && val.IndexOf ("keep-alive") == -1)
251 value = value + ", Keep-Alive";
253 webHeaders.RemoveAndAdd ("Connection", value);
257 public override string ConnectionGroupName {
258 get { return connectionGroup; }
259 set { connectionGroup = value; }
262 public override long ContentLength {
263 get { return contentLength; }
265 CheckRequestStarted ();
267 throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
269 contentLength = value;
273 internal long InternalContentLength {
274 set { contentLength = value; }
277 public override string ContentType {
278 get { return webHeaders ["Content-Type"]; }
280 if (value == null || value.Trim().Length == 0) {
281 webHeaders.RemoveInternal ("Content-Type");
284 webHeaders.RemoveAndAdd ("Content-Type", value);
288 public HttpContinueDelegate ContinueDelegate {
289 get { return continueDelegate; }
290 set { continueDelegate = value; }
293 public CookieContainer CookieContainer {
294 get { return cookieContainer; }
295 set { cookieContainer = value; }
298 public override ICredentials Credentials {
299 get { return credentials; }
300 set { credentials = value; }
305 public static new RequestCachePolicy DefaultCachePolicy
308 throw GetMustImplement ();
311 throw GetMustImplement ();
316 public static int DefaultMaximumErrorResponseLength
319 throw GetMustImplement ();
322 throw GetMustImplement ();
327 public string Expect {
328 get { return webHeaders ["Expect"]; }
330 CheckRequestStarted ();
333 val = val.Trim ().ToLower ();
335 if (val == null || val.Length == 0) {
336 webHeaders.RemoveInternal ("Expect");
340 if (val == "100-continue")
341 throw new ArgumentException ("100-Continue cannot be set with this property.",
343 webHeaders.RemoveAndAdd ("Expect", value);
347 public bool HaveResponse {
348 get { return haveResponse; }
351 public override WebHeaderCollection Headers {
352 get { return webHeaders; }
354 CheckRequestStarted ();
355 WebHeaderCollection newHeaders = new WebHeaderCollection (true);
356 int count = value.Count;
357 for (int i = 0; i < count; i++)
358 newHeaders.Add (value.GetKey (i), value.Get (i));
360 webHeaders = newHeaders;
364 public DateTime IfModifiedSince {
366 string str = webHeaders ["If-Modified-Since"];
370 return MonoHttpDate.Parse (str);
371 } catch (Exception) {
376 CheckRequestStarted ();
378 webHeaders.SetInternal ("If-Modified-Since",
379 value.ToUniversalTime ().ToString ("r", null));
380 // TODO: check last param when using different locale
384 public bool KeepAlive {
393 public int MaximumAutomaticRedirections {
394 get { return maxAutoRedirect; }
397 throw new ArgumentException ("Must be > 0", "value");
399 maxAutoRedirect = value;
404 [MonoTODO ("Use this")]
405 public int MaximumResponseHeadersLength {
406 get { return maxResponseHeadersLength; }
407 set { maxResponseHeadersLength = value; }
410 [MonoTODO ("Use this")]
411 public static int DefaultMaximumResponseHeadersLength {
412 get { return defaultMaxResponseHeadersLength; }
413 set { defaultMaxResponseHeadersLength = value; }
420 int ReadWriteTimeout {
421 get { return readWriteTimeout; }
424 throw new InvalidOperationException ("The request has already been sent.");
427 throw new ArgumentOutOfRangeException ("value", "Must be >= -1");
429 readWriteTimeout = value;
433 public string MediaType {
434 get { return mediaType; }
440 public override string Method {
441 get { return this.method; }
443 if (value == null || value.Trim () == "")
444 throw new ArgumentException ("not a valid method");
450 public bool Pipelined {
451 get { return pipelined; }
452 set { pipelined = value; }
455 public override bool PreAuthenticate {
456 get { return preAuthenticate; }
457 set { preAuthenticate = value; }
460 public Version ProtocolVersion {
461 get { return version; }
463 if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
464 throw new ArgumentException ("value");
470 public override IWebProxy Proxy {
471 get { return proxy; }
473 CheckRequestStarted ();
476 throw new ArgumentNullException ("value");
480 servicePoint = null; // we may need a new one
484 public string Referer {
485 get { return webHeaders ["Referer"]; }
487 CheckRequestStarted ();
488 if (value == null || value.Trim().Length == 0) {
489 webHeaders.RemoveInternal ("Referer");
492 webHeaders.SetInternal ("Referer", value);
496 public override Uri RequestUri {
497 get { return requestUri; }
500 public bool SendChunked {
501 get { return sendChunked; }
503 CheckRequestStarted ();
508 public ServicePoint ServicePoint {
509 get { return GetServicePoint (); }
512 public override int Timeout {
513 get { return timeout; }
516 throw new ArgumentOutOfRangeException ("value");
522 public string TransferEncoding {
523 get { return webHeaders ["Transfer-Encoding"]; }
525 CheckRequestStarted ();
528 val = val.Trim ().ToLower ();
530 if (val == null || val.Length == 0) {
531 webHeaders.RemoveInternal ("Transfer-Encoding");
535 if (val == "chunked")
536 throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
539 throw new ArgumentException ("SendChunked must be True", "value");
541 webHeaders.RemoveAndAdd ("Transfer-Encoding", value);
546 public override bool UseDefaultCredentials
548 get { return CredentialCache.DefaultCredentials == Credentials; }
549 set { Credentials = value ? CredentialCache.DefaultCredentials : null; }
553 public string UserAgent {
554 get { return webHeaders ["User-Agent"]; }
555 set { webHeaders.SetInternal ("User-Agent", value); }
559 bool unsafe_auth_blah;
560 public bool UnsafeAuthenticatedConnectionSharing
562 get { return unsafe_auth_blah; }
563 set { unsafe_auth_blah = value; }
567 internal bool GotRequestStream {
568 get { return gotRequestStream; }
571 internal bool ExpectContinue {
572 get { return expectContinue; }
573 set { expectContinue = value; }
576 internal Uri AuthUri {
577 get { return actualUri; }
580 internal bool ProxyQuery {
581 get { return servicePoint.UsesProxy && !servicePoint.UseConnect; }
586 internal ServicePoint GetServicePoint ()
589 if (hostChanged || servicePoint == null) {
590 servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
598 public void AddRange (int range)
600 AddRange ("bytes", range);
603 public void AddRange (int from, int to)
605 AddRange ("bytes", from, to);
608 public void AddRange (string rangeSpecifier, int range)
610 if (rangeSpecifier == null)
611 throw new ArgumentNullException ("rangeSpecifier");
612 string value = webHeaders ["Range"];
613 if (value == null || value.Length == 0)
614 value = rangeSpecifier + "=";
615 else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
618 throw new InvalidOperationException ("rangeSpecifier");
619 webHeaders.RemoveAndAdd ("Range", value + range + "-");
622 public void AddRange (string rangeSpecifier, int from, int to)
624 if (rangeSpecifier == null)
625 throw new ArgumentNullException ("rangeSpecifier");
626 if (from < 0 || to < 0 || from > to)
627 throw new ArgumentOutOfRangeException ();
628 string value = webHeaders ["Range"];
629 if (value == null || value.Length == 0)
630 value = rangeSpecifier + "=";
631 else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
634 throw new InvalidOperationException ("rangeSpecifier");
635 webHeaders.RemoveAndAdd ("Range", value + from + "-" + to);
638 public override int GetHashCode ()
640 return base.GetHashCode ();
644 public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
647 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
649 bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
650 method == "TRACE" || method == "DELETE");
651 if (method == null || !send)
652 throw new ProtocolViolationException ("Cannot send data when method is: " + method);
654 if (contentLength == -1 && !sendChunked && !allowBuffering && KeepAlive)
655 throw new ProtocolViolationException ("Content-Length not set");
657 string transferEncoding = TransferEncoding;
658 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
659 throw new ProtocolViolationException ("SendChunked should be true.");
663 if (asyncWrite != null) {
664 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
665 "method while a previous call is still in progress.");
668 asyncWrite = new WebAsyncResult (this, callback, state);
669 initialMethod = method;
671 if (writeStream != null) {
672 asyncWrite.SetCompleted (true, writeStream);
673 asyncWrite.DoCallback ();
678 gotRequestStream = true;
679 WebAsyncResult result = asyncWrite;
683 servicePoint = GetServicePoint ();
684 abortHandler = servicePoint.SendRequest (this, connectionGroup);
690 public override Stream EndGetRequestStream (IAsyncResult asyncResult)
692 if (asyncResult == null)
693 throw new ArgumentNullException ("asyncResult");
695 WebAsyncResult result = asyncResult as WebAsyncResult;
697 throw new ArgumentException ("Invalid IAsyncResult");
700 result.WaitUntilComplete ();
702 Exception e = result.Exception;
706 return result.WriteStream;
709 public override Stream GetRequestStream()
711 IAsyncResult asyncResult = asyncWrite;
712 if (asyncResult == null) {
713 asyncResult = BeginGetRequestStream (null, null);
714 asyncWrite = (WebAsyncResult) asyncResult;
717 if (!asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
719 throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
722 return EndGetRequestStream (asyncResult);
725 void CheckIfForceWrite ()
727 if (writeStream == null || writeStream.RequestWritten|| contentLength < 0 || !InternalAllowBuffering)
730 // This will write the POST/PUT if the write stream already has the expected
731 // amount of bytes in it (ContentLength) (bug #77753).
732 if (writeStream.WriteBufferLength == contentLength)
733 writeStream.WriteRequest ();
736 public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
739 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
742 throw new ProtocolViolationException ("Method is null.");
745 bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
746 method == "TRACE" || method == "DELETE");
747 if (send && contentLength < 0 && !sendChunked && !allowBuffering && KeepAlive)
748 throw new ProtocolViolationException ("Buffering is disabled, ContentLength is negative and SendChunked is disabled.");
750 if (!send && (contentLength > -1 || sendChunked))
751 throw new ProtocolViolationException ("ContentLength can't be set for non-write operations.");
754 string transferEncoding = TransferEncoding;
755 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
756 throw new ProtocolViolationException ("SendChunked should be true.");
758 Monitor.Enter (locker);
759 getResponseCalled = true;
760 if (asyncRead != null && !haveResponse) {
761 Monitor.Exit (locker);
762 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
763 "method while a previous call is still in progress.");
766 CheckIfForceWrite ();
767 asyncRead = new WebAsyncResult (this, callback, state);
768 WebAsyncResult aread = asyncRead;
769 initialMethod = method;
771 Exception saved = saved_exc;
772 if (webResponse != null) {
773 Monitor.Exit (locker);
775 aread.SetCompleted (true, webResponse);
777 aread.SetCompleted (true, saved);
781 } else if (saved != null) {
782 Monitor.Exit (locker);
783 aread.SetCompleted (true, saved);
792 servicePoint = GetServicePoint ();
793 abortHandler = servicePoint.SendRequest (this, connectionGroup);
796 Monitor.Exit (locker);
800 public override WebResponse EndGetResponse (IAsyncResult asyncResult)
802 if (asyncResult == null)
803 throw new ArgumentNullException ("asyncResult");
805 WebAsyncResult result = asyncResult as WebAsyncResult;
807 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
809 if (!result.WaitUntilComplete (timeout, false)) {
811 throw new WebException("The request timed out", WebExceptionStatus.Timeout);
814 if (result.GotException)
815 throw result.Exception;
817 return result.Response;
820 public override WebResponse GetResponse()
822 WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
823 return EndGetResponse (result);
826 internal bool FinishedReading {
827 get { return finished_reading; }
828 set { finished_reading = value; }
831 internal bool Aborted {
832 get { return Interlocked.CompareExchange (ref aborted, 0, 0) == 1; }
835 public override void Abort ()
837 if (Interlocked.CompareExchange (ref aborted, 1, 0) == 1)
840 if (haveResponse && finished_reading)
844 if (abortHandler != null) {
846 abortHandler (this, EventArgs.Empty);
847 } catch (Exception) {}
851 if (asyncWrite != null) {
852 WebAsyncResult r = asyncWrite;
853 if (!r.IsCompleted) {
855 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
856 r.SetCompleted (false, wexc);
863 if (asyncRead != null) {
864 WebAsyncResult r = asyncRead;
865 if (!r.IsCompleted) {
867 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
868 r.SetCompleted (false, wexc);
875 if (writeStream != null) {
877 writeStream.Close ();
882 if (webResponse != null) {
884 webResponse.Close ();
890 void ISerializable.GetObjectData (SerializationInfo serializationInfo,
891 StreamingContext streamingContext)
893 GetObjectData (serializationInfo, streamingContext);
899 void GetObjectData (SerializationInfo serializationInfo,
900 StreamingContext streamingContext)
902 SerializationInfo info = serializationInfo;
904 info.AddValue ("requestUri", requestUri, typeof (Uri));
905 info.AddValue ("actualUri", actualUri, typeof (Uri));
906 info.AddValue ("allowAutoRedirect", allowAutoRedirect);
907 info.AddValue ("allowBuffering", allowBuffering);
908 info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
909 info.AddValue ("connectionGroup", connectionGroup);
910 info.AddValue ("contentLength", contentLength);
911 info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
912 info.AddValue ("keepAlive", keepAlive);
913 info.AddValue ("maxAutoRedirect", maxAutoRedirect);
914 info.AddValue ("mediaType", mediaType);
915 info.AddValue ("method", method);
916 info.AddValue ("initialMethod", initialMethod);
917 info.AddValue ("pipelined", pipelined);
918 info.AddValue ("version", version, typeof (Version));
919 info.AddValue ("proxy", proxy, typeof (IWebProxy));
920 info.AddValue ("sendChunked", sendChunked);
921 info.AddValue ("timeout", timeout);
922 info.AddValue ("redirects", redirects);
925 void CheckRequestStarted ()
928 throw new InvalidOperationException ("request started");
931 internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
933 if (continueDelegate != null)
934 continueDelegate (statusCode, headers);
937 bool Redirect (WebAsyncResult result, HttpStatusCode code)
941 string uriString = null;
944 case HttpStatusCode.Ambiguous: // 300
945 e = new WebException ("Ambiguous redirect.");
947 case HttpStatusCode.MovedPermanently: // 301
948 case HttpStatusCode.Redirect: // 302
949 case HttpStatusCode.TemporaryRedirect: // 307
950 /* MS follows the redirect for POST too
951 if (method != "GET" && method != "HEAD") // 10.3
956 bodyBufferLength = 0;
959 uriString = webResponse.Headers ["Location"];
961 case HttpStatusCode.SeeOther: //303
963 uriString = webResponse.Headers ["Location"];
965 case HttpStatusCode.NotModified: // 304
967 case HttpStatusCode.UseProxy: // 305
968 e = new NotImplementedException ("Proxy support not available.");
970 case HttpStatusCode.Unused: // 306
972 e = new ProtocolViolationException ("Invalid status code: " + (int) code);
979 if (uriString == null)
980 throw new WebException ("No Location header found for " + (int) code,
981 WebExceptionStatus.ProtocolError);
983 Uri prev = actualUri;
985 actualUri = new Uri (actualUri, uriString);
986 } catch (Exception) {
987 throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
988 uriString, (int) code),
989 WebExceptionStatus.ProtocolError);
992 hostChanged = (actualUri.Scheme != prev.Scheme || actualUri.Host != prev.Host ||
993 actualUri.Port != prev.Port);
999 bool continue100 = false;
1002 webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
1003 webHeaders.RemoveInternal ("Content-Length");
1004 } else if (contentLength != -1) {
1005 if (contentLength > 0)
1007 webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
1008 webHeaders.RemoveInternal ("Transfer-Encoding");
1011 if (actualVersion == HttpVersion.Version11 && continue100 &&
1012 servicePoint.SendContinue) { // RFC2616 8.2.3
1013 webHeaders.RemoveAndAdd ("Expect" , "100-continue");
1014 expectContinue = true;
1016 webHeaders.RemoveInternal ("Expect");
1017 expectContinue = false;
1020 bool proxy_query = ProxyQuery;
1021 string connectionHeader = (proxy_query) ? "Proxy-Connection" : "Connection";
1022 webHeaders.RemoveInternal ((!proxy_query) ? "Proxy-Connection" : "Connection");
1023 Version proto_version = servicePoint.ProtocolVersion;
1024 bool spoint10 = (proto_version == null || proto_version == HttpVersion.Version10);
1026 if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
1027 webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
1028 } else if (!keepAlive && version == HttpVersion.Version11) {
1029 webHeaders.RemoveAndAdd (connectionHeader, "close");
1032 webHeaders.SetInternal ("Host", actualUri.Authority);
1033 if (cookieContainer != null) {
1034 string cookieHeader = cookieContainer.GetCookieHeader (actualUri);
1035 if (cookieHeader != "")
1036 webHeaders.SetInternal ("Cookie", cookieHeader);
1040 string accept_encoding = null;
1041 if ((auto_decomp & DecompressionMethods.GZip) != 0)
1042 accept_encoding = "gzip";
1043 if ((auto_decomp & DecompressionMethods.Deflate) != 0)
1044 accept_encoding = accept_encoding != null ? "gzip, deflate" : "deflate";
1045 if (accept_encoding != null)
1046 webHeaders.RemoveAndAdd ("Accept-Encoding", accept_encoding);
1048 if (!usedPreAuth && preAuthenticate)
1049 DoPreAuthenticate ();
1051 return webHeaders.ToString ();
1054 void DoPreAuthenticate ()
1056 webHeaders.RemoveInternal ("Proxy-Authorization");
1057 webHeaders.RemoveInternal ("Authorization");
1058 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1059 ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
1060 Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
1064 string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
1065 webHeaders [authHeader] = auth.Message;
1069 internal void SetWriteStreamError (WebExceptionStatus status)
1071 SetWriteStreamError (status, null);
1074 internal void SetWriteStreamError (WebExceptionStatus status, Exception exc)
1079 WebAsyncResult r = asyncWrite;
1087 msg = "Error: " + status;
1088 wex = new WebException (msg, status);
1090 msg = String.Format ("Error: {0} ({1})", status, exc.Message);
1091 wex = new WebException (msg, exc, status);
1093 r.SetCompleted (false, wex);
1098 internal void SendRequestHeaders ()
1100 StringBuilder req = new StringBuilder ();
1103 query = actualUri.PathAndQuery;
1104 } else if (actualUri.IsDefaultPort) {
1105 query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
1107 actualUri.PathAndQuery);
1109 query = String.Format ("{0}://{1}:{2}{3}", actualUri.Scheme,
1112 actualUri.PathAndQuery);
1115 if (servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
1116 actualVersion = servicePoint.ProtocolVersion;
1118 actualVersion = version;
1121 req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
1122 actualVersion.Major, actualVersion.Minor);
1123 req.Append (GetHeaders ());
1124 string reqstr = req.ToString ();
1125 byte [] bytes = Encoding.UTF8.GetBytes (reqstr);
1127 writeStream.SetHeaders (bytes);
1128 } catch (WebException wexc) {
1129 SetWriteStreamError (wexc.Status);
1130 } catch (Exception) {
1131 SetWriteStreamError (WebExceptionStatus.SendFailure);
1135 internal void SetWriteStream (WebConnectionStream stream)
1140 writeStream = stream;
1141 if (bodyBuffer != null) {
1142 webHeaders.RemoveInternal ("Transfer-Encoding");
1143 contentLength = bodyBufferLength;
1144 writeStream.SendChunked = false;
1147 SendRequestHeaders ();
1151 if (bodyBuffer != null) {
1152 // The body has been written and buffered. The request "user"
1153 // won't write it again, so we must do it.
1154 writeStream.Write (bodyBuffer, 0, bodyBufferLength);
1156 writeStream.Close ();
1157 } else if (method != "HEAD" && method != "GET" && method != "MKCOL" && method != "CONNECT" &&
1158 method != "DELETE" && method != "TRACE") {
1159 if (getResponseCalled && !writeStream.RequestWritten)
1160 writeStream.WriteRequest ();
1163 if (asyncWrite != null) {
1164 asyncWrite.SetCompleted (false, stream);
1165 asyncWrite.DoCallback ();
1170 internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
1175 string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
1176 WebAsyncResult r = asyncRead;
1181 if (e is WebException) {
1182 wexc = (WebException) e;
1184 wexc = new WebException (msg, e, status, null);
1187 if (!r.IsCompleted) {
1188 r.SetCompleted (false, wexc);
1190 } else if (r == asyncWrite) {
1193 haveResponse = true;
1197 haveResponse = true;
1203 void CheckSendError (WebConnectionData data)
1205 // Got here, but no one called GetResponse
1206 int status = data.StatusCode;
1207 if (status < 400 || status == 401 || status == 407)
1210 if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
1211 // The request has not been completely sent and we got here!
1212 // We should probably just close and cause an error in any case,
1213 saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse);
1214 webResponse.ReadAll ();
1218 void HandleNtlmAuth (WebAsyncResult r)
1220 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1222 WebConnection cnc = wce.Connection;
1223 cnc.PriorityRequest = this;
1224 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1225 ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1226 if (creds != null) {
1227 cnc.NtlmCredential = creds.GetCredential (requestUri, "NTLM");
1229 cnc.UnsafeAuthenticatedConnectionSharing = unsafe_auth_blah;
1234 haveResponse = false;
1235 webResponse.ReadAll ();
1239 internal void SetResponseData (WebConnectionData data)
1243 if (data.stream != null)
1244 data.stream.Close ();
1248 WebException wexc = null;
1250 webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
1251 } catch (Exception e) {
1252 wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null);
1253 if (data.stream != null)
1254 data.stream.Close ();
1257 if (wexc == null && (method == "POST" || method == "PUT")) {
1259 CheckSendError (data);
1260 if (saved_exc != null)
1261 wexc = (WebException) saved_exc;
1265 WebAsyncResult r = asyncRead;
1267 bool forced = false;
1268 if (r == null && webResponse != null) {
1269 // This is a forced completion (302, 204)...
1271 r = new WebAsyncResult (null, null);
1272 r.SetCompleted (false, webResponse);
1277 r.SetCompleted (false, wexc);
1284 redirected = CheckFinalStatus (r);
1286 if (is_ntlm_auth && authCompleted && webResponse != null
1287 && (int)webResponse.StatusCode < 400) {
1288 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1290 WebConnection cnc = wce.Connection;
1291 cnc.NtlmAuthenticated = true;
1295 // clear internal buffer so that it does not
1296 // hold possible big buffer (bug #397627)
1297 if (writeStream != null)
1298 writeStream.KillBuffer ();
1300 haveResponse = true;
1301 r.SetCompleted (false, webResponse);
1304 if (webResponse != null) {
1309 webResponse.Close ();
1311 haveResponse = false;
1314 servicePoint = GetServicePoint ();
1315 abortHandler = servicePoint.SendRequest (this, connectionGroup);
1317 } catch (WebException wexc2) {
1320 haveResponse = true;
1322 r.SetCompleted (false, wexc2);
1325 } catch (Exception ex) {
1326 wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
1329 haveResponse = true;
1331 r.SetCompleted (false, wexc);
1339 bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1341 authCompleted = false;
1342 if (code == HttpStatusCode.Unauthorized && credentials == null)
1345 bool isProxy = (code == HttpStatusCode.ProxyAuthenticationRequired);
1346 if (isProxy && (proxy == null || proxy.Credentials == null))
1349 string authHeader = response.Headers [(isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate"];
1350 if (authHeader == null)
1353 ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1354 Authorization auth = AuthenticationManager.Authenticate (authHeader, this, creds);
1358 webHeaders [(isProxy) ? "Proxy-Authorization" : "Authorization"] = auth.Message;
1359 authCompleted = auth.Complete;
1360 is_ntlm_auth = (auth.Module.AuthenticationType == "NTLM");
1364 // Returns true if redirected
1365 bool CheckFinalStatus (WebAsyncResult result)
1367 if (result.GotException)
1368 throw result.Exception;
1370 Exception throwMe = result.Exception;
1373 HttpWebResponse resp = result.Response;
1374 WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
1375 HttpStatusCode code = 0;
1376 if (throwMe == null && webResponse != null) {
1377 code = webResponse.StatusCode;
1378 if (!authCompleted && ((code == HttpStatusCode.Unauthorized && credentials != null) ||
1379 (ProxyQuery && code == HttpStatusCode.ProxyAuthenticationRequired))) {
1380 if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
1381 // Keep the written body, so it can be rewritten in the retry
1382 if (InternalAllowBuffering) {
1383 bodyBuffer = writeStream.WriteBuffer;
1384 bodyBufferLength = writeStream.WriteBufferLength;
1386 } else if (method != "PUT" && method != "POST") {
1390 writeStream.InternalClose ();
1392 webResponse.Close ();
1395 throw new WebException ("This request requires buffering " +
1396 "of data for authentication or " +
1397 "redirection to be sucessful.");
1401 if ((int) code >= 400) {
1402 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1403 (int) code, webResponse.StatusDescription);
1404 throwMe = new WebException (err, null, protoError, webResponse);
1405 webResponse.ReadAll ();
1406 } else if ((int) code == 304 && allowAutoRedirect) {
1407 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1408 (int) code, webResponse.StatusDescription);
1409 throwMe = new WebException (err, null, protoError, webResponse);
1410 } else if ((int) code >= 300 && allowAutoRedirect && redirects >= maxAutoRedirect) {
1411 throwMe = new WebException ("Max. redirections exceeded.", null,
1412 protoError, webResponse);
1413 webResponse.ReadAll ();
1417 if (throwMe == null) {
1420 if (allowAutoRedirect && c >= 300) {
1421 if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
1422 bodyBuffer = writeStream.WriteBuffer;
1423 bodyBufferLength = writeStream.WriteBufferLength;
1425 b = Redirect (result, code);
1428 if (resp != null && c >= 300 && c != 304)
1434 if (writeStream != null) {
1435 writeStream.InternalClose ();