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;
102 DecompressionMethods auto_decomp;
105 int maxResponseHeadersLength;
106 static int defaultMaxResponseHeadersLength;
107 int readWriteTimeout = 300000; // ms
110 static HttpWebRequest ()
112 NetConfig config = ConfigurationSettings.GetConfig ("system.net/settings") as NetConfig;
113 defaultMaxResponseHeadersLength = 64 * 1024;
114 if (config != null) {
115 int x = config.MaxResponseHeadersLength;
119 defaultMaxResponseHeadersLength = x;
129 HttpWebRequest (Uri uri)
131 this.requestUri = uri;
132 this.actualUri = uri;
133 this.proxy = GlobalProxySelection.Select;
137 [Obsolete ("Serialization is obsoleted for this type", false)]
139 protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
141 SerializationInfo info = serializationInfo;
143 requestUri = (Uri) info.GetValue ("requestUri", typeof (Uri));
144 actualUri = (Uri) info.GetValue ("actualUri", typeof (Uri));
145 allowAutoRedirect = info.GetBoolean ("allowAutoRedirect");
146 allowBuffering = info.GetBoolean ("allowBuffering");
147 certificates = (X509CertificateCollection) info.GetValue ("certificates", typeof (X509CertificateCollection));
148 connectionGroup = info.GetString ("connectionGroup");
149 contentLength = info.GetInt64 ("contentLength");
150 webHeaders = (WebHeaderCollection) info.GetValue ("webHeaders", typeof (WebHeaderCollection));
151 keepAlive = info.GetBoolean ("keepAlive");
152 maxAutoRedirect = info.GetInt32 ("maxAutoRedirect");
153 mediaType = info.GetString ("mediaType");
154 method = info.GetString ("method");
155 initialMethod = info.GetString ("initialMethod");
156 pipelined = info.GetBoolean ("pipelined");
157 version = (Version) info.GetValue ("version", typeof (Version));
158 proxy = (IWebProxy) info.GetValue ("proxy", typeof (IWebProxy));
159 sendChunked = info.GetBoolean ("sendChunked");
160 timeout = info.GetInt32 ("timeout");
161 redirects = info.GetInt32 ("redirects");
166 internal bool UsesNtlmAuthentication {
167 get { return is_ntlm_auth; }
170 public string Accept {
171 get { return webHeaders ["Accept"]; }
173 CheckRequestStarted ();
174 webHeaders.RemoveAndAdd ("Accept", value);
179 get { return actualUri; }
182 public bool AllowAutoRedirect {
183 get { return allowAutoRedirect; }
184 set { this.allowAutoRedirect = value; }
187 public bool AllowWriteStreamBuffering {
188 get { return allowBuffering; }
189 set { allowBuffering = value; }
193 static Exception GetMustImplement ()
195 return new NotImplementedException ();
198 public DecompressionMethods AutomaticDecompression
204 CheckRequestStarted ();
210 internal bool InternalAllowBuffering {
212 return (allowBuffering && (method != "HEAD" && method != "GET" &&
213 method != "MKCOL" && method != "CONNECT" &&
214 method != "DELETE" && method != "TRACE"));
218 public X509CertificateCollection ClientCertificates {
220 if (certificates == null)
221 certificates = new X509CertificateCollection ();
228 throw GetMustImplement ();
233 public string Connection {
234 get { return webHeaders ["Connection"]; }
236 CheckRequestStarted ();
239 val = val.Trim ().ToLower ();
241 if (val == null || val.Length == 0) {
242 webHeaders.RemoveInternal ("Connection");
246 if (val == "keep-alive" || val == "close")
247 throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
249 if (keepAlive && val.IndexOf ("keep-alive") == -1)
250 value = value + ", Keep-Alive";
252 webHeaders.RemoveAndAdd ("Connection", value);
256 public override string ConnectionGroupName {
257 get { return connectionGroup; }
258 set { connectionGroup = value; }
261 public override long ContentLength {
262 get { return contentLength; }
264 CheckRequestStarted ();
266 throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
268 contentLength = value;
272 internal long InternalContentLength {
273 set { contentLength = value; }
276 public override string ContentType {
277 get { return webHeaders ["Content-Type"]; }
279 if (value == null || value.Trim().Length == 0) {
280 webHeaders.RemoveInternal ("Content-Type");
283 webHeaders.RemoveAndAdd ("Content-Type", value);
287 public HttpContinueDelegate ContinueDelegate {
288 get { return continueDelegate; }
289 set { continueDelegate = value; }
292 public CookieContainer CookieContainer {
293 get { return cookieContainer; }
294 set { cookieContainer = value; }
297 public override ICredentials Credentials {
298 get { return credentials; }
299 set { credentials = value; }
304 public static new RequestCachePolicy DefaultCachePolicy
307 throw GetMustImplement ();
310 throw GetMustImplement ();
315 public static int DefaultMaximumErrorResponseLength
318 throw GetMustImplement ();
321 throw GetMustImplement ();
326 public string Expect {
327 get { return webHeaders ["Expect"]; }
329 CheckRequestStarted ();
332 val = val.Trim ().ToLower ();
334 if (val == null || val.Length == 0) {
335 webHeaders.RemoveInternal ("Expect");
339 if (val == "100-continue")
340 throw new ArgumentException ("100-Continue cannot be set with this property.",
342 webHeaders.RemoveAndAdd ("Expect", value);
346 public bool HaveResponse {
347 get { return haveResponse; }
350 public override WebHeaderCollection Headers {
351 get { return webHeaders; }
353 CheckRequestStarted ();
354 WebHeaderCollection newHeaders = new WebHeaderCollection (true);
355 int count = value.Count;
356 for (int i = 0; i < count; i++)
357 newHeaders.Add (value.GetKey (i), value.Get (i));
359 webHeaders = newHeaders;
363 public DateTime IfModifiedSince {
365 string str = webHeaders ["If-Modified-Since"];
369 return MonoHttpDate.Parse (str);
370 } catch (Exception) {
375 CheckRequestStarted ();
377 webHeaders.SetInternal ("If-Modified-Since",
378 value.ToUniversalTime ().ToString ("r", null));
379 // TODO: check last param when using different locale
383 public bool KeepAlive {
392 public int MaximumAutomaticRedirections {
393 get { return maxAutoRedirect; }
396 throw new ArgumentException ("Must be > 0", "value");
398 maxAutoRedirect = value;
403 [MonoTODO ("Use this")]
404 public int MaximumResponseHeadersLength {
405 get { return maxResponseHeadersLength; }
406 set { maxResponseHeadersLength = value; }
409 [MonoTODO ("Use this")]
410 public static int DefaultMaximumResponseHeadersLength {
411 get { return defaultMaxResponseHeadersLength; }
412 set { defaultMaxResponseHeadersLength = value; }
419 int ReadWriteTimeout {
420 get { return readWriteTimeout; }
423 throw new InvalidOperationException ("The request has already been sent.");
426 throw new ArgumentOutOfRangeException ("value", "Must be >= -1");
428 readWriteTimeout = value;
432 public string MediaType {
433 get { return mediaType; }
439 public override string Method {
440 get { return this.method; }
442 if (value == null || value.Trim () == "")
443 throw new ArgumentException ("not a valid method");
449 public bool Pipelined {
450 get { return pipelined; }
451 set { pipelined = value; }
454 public override bool PreAuthenticate {
455 get { return preAuthenticate; }
456 set { preAuthenticate = value; }
459 public Version ProtocolVersion {
460 get { return version; }
462 if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
463 throw new ArgumentException ("value");
469 public override IWebProxy Proxy {
470 get { return proxy; }
472 CheckRequestStarted ();
475 throw new ArgumentNullException ("value");
479 servicePoint = null; // we may need a new one
483 public string Referer {
484 get { return webHeaders ["Referer"]; }
486 CheckRequestStarted ();
487 if (value == null || value.Trim().Length == 0) {
488 webHeaders.RemoveInternal ("Referer");
491 webHeaders.SetInternal ("Referer", value);
495 public override Uri RequestUri {
496 get { return requestUri; }
499 public bool SendChunked {
500 get { return sendChunked; }
502 CheckRequestStarted ();
507 public ServicePoint ServicePoint {
508 get { return GetServicePoint (); }
511 public override int Timeout {
512 get { return timeout; }
515 throw new ArgumentOutOfRangeException ("value");
521 public string TransferEncoding {
522 get { return webHeaders ["Transfer-Encoding"]; }
524 CheckRequestStarted ();
527 val = val.Trim ().ToLower ();
529 if (val == null || val.Length == 0) {
530 webHeaders.RemoveInternal ("Transfer-Encoding");
534 if (val == "chunked")
535 throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
538 throw new ArgumentException ("SendChunked must be True", "value");
540 webHeaders.RemoveAndAdd ("Transfer-Encoding", value);
545 public override bool UseDefaultCredentials
547 get { return CredentialCache.DefaultCredentials == Credentials; }
548 set { Credentials = value ? CredentialCache.DefaultCredentials : null; }
552 public string UserAgent {
553 get { return webHeaders ["User-Agent"]; }
554 set { webHeaders.SetInternal ("User-Agent", value); }
558 bool unsafe_auth_blah;
559 public bool UnsafeAuthenticatedConnectionSharing
561 get { return unsafe_auth_blah; }
562 set { unsafe_auth_blah = value; }
566 internal bool GotRequestStream {
567 get { return gotRequestStream; }
570 internal bool ExpectContinue {
571 get { return expectContinue; }
572 set { expectContinue = value; }
575 internal Uri AuthUri {
576 get { return actualUri; }
579 internal bool ProxyQuery {
580 get { return servicePoint.UsesProxy && !servicePoint.UseConnect; }
585 internal ServicePoint GetServicePoint ()
588 if (hostChanged || servicePoint == null) {
589 servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
597 public void AddRange (int range)
599 AddRange ("bytes", range);
602 public void AddRange (int from, int to)
604 AddRange ("bytes", from, to);
607 public void AddRange (string rangeSpecifier, int range)
609 if (rangeSpecifier == null)
610 throw new ArgumentNullException ("rangeSpecifier");
611 string value = webHeaders ["Range"];
612 if (value == null || value.Length == 0)
613 value = rangeSpecifier + "=";
614 else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
617 throw new InvalidOperationException ("rangeSpecifier");
618 webHeaders.RemoveAndAdd ("Range", value + range + "-");
621 public void AddRange (string rangeSpecifier, int from, int to)
623 if (rangeSpecifier == null)
624 throw new ArgumentNullException ("rangeSpecifier");
625 if (from < 0 || to < 0 || from > to)
626 throw new ArgumentOutOfRangeException ();
627 string value = webHeaders ["Range"];
628 if (value == null || value.Length == 0)
629 value = rangeSpecifier + "=";
630 else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
633 throw new InvalidOperationException ("rangeSpecifier");
634 webHeaders.RemoveAndAdd ("Range", value + from + "-" + to);
637 public override int GetHashCode ()
639 return base.GetHashCode ();
643 public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
646 throw new WebException ("The request was previosly aborted.");
648 bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
649 method == "TRACE" || method == "DELETE");
650 if (method == null || !send)
651 throw new ProtocolViolationException ("Cannot send data when method is: " + method);
653 if (contentLength == -1 && !sendChunked && !allowBuffering && KeepAlive)
654 throw new ProtocolViolationException ("Content-Length not set");
656 string transferEncoding = TransferEncoding;
657 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
658 throw new ProtocolViolationException ("SendChunked should be true.");
662 if (asyncWrite != null) {
663 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
664 "method while a previous call is still in progress.");
667 asyncWrite = new WebAsyncResult (this, callback, state);
668 initialMethod = method;
670 if (writeStream != null) {
671 asyncWrite.SetCompleted (true, writeStream);
672 asyncWrite.DoCallback ();
677 gotRequestStream = true;
678 WebAsyncResult result = asyncWrite;
682 servicePoint = GetServicePoint ();
683 abortHandler = servicePoint.SendRequest (this, connectionGroup);
689 public override Stream EndGetRequestStream (IAsyncResult asyncResult)
691 if (asyncResult == null)
692 throw new ArgumentNullException ("asyncResult");
694 WebAsyncResult result = asyncResult as WebAsyncResult;
696 throw new ArgumentException ("Invalid IAsyncResult");
699 result.WaitUntilComplete ();
701 Exception e = result.Exception;
705 return result.WriteStream;
708 public override Stream GetRequestStream()
710 IAsyncResult asyncResult = asyncWrite;
711 if (asyncResult == null) {
712 asyncResult = BeginGetRequestStream (null, null);
713 asyncWrite = (WebAsyncResult) asyncResult;
716 if (!asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
718 throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
721 return EndGetRequestStream (asyncResult);
724 void CheckIfForceWrite ()
726 if (writeStream == null || writeStream.RequestWritten|| contentLength < 0 || !InternalAllowBuffering)
729 // This will write the POST/PUT if the write stream already has the expected
730 // amount of bytes in it (ContentLength) (bug #77753).
731 if (writeStream.WriteBufferLength == contentLength)
732 writeStream.WriteRequest ();
735 public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
738 throw new ProtocolViolationException ("Method is null.");
741 bool send = (method == "PUT" || method == "POST");
742 if (send && contentLength < 0 && !sendChunked && !allowBuffering && KeepAlive)
743 throw new ProtocolViolationException ("Buffering is disabled, ContentLength is negative and SendChunked is disabled.");
745 if (!send && (contentLength > -1 || sendChunked))
746 throw new ProtocolViolationException ("ContentLength can't be set for non-write operations.");
749 string transferEncoding = TransferEncoding;
750 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
751 throw new ProtocolViolationException ("SendChunked should be true.");
753 Monitor.Enter (locker);
754 getResponseCalled = true;
755 if (asyncRead != null && !haveResponse) {
756 Monitor.Exit (locker);
757 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
758 "method while a previous call is still in progress.");
761 CheckIfForceWrite ();
762 asyncRead = new WebAsyncResult (this, callback, state);
763 WebAsyncResult aread = asyncRead;
764 initialMethod = method;
766 Exception saved = saved_exc;
767 if (webResponse != null) {
768 Monitor.Exit (locker);
770 aread.SetCompleted (true, webResponse);
772 aread.SetCompleted (true, saved);
776 } else if (saved != null) {
777 Monitor.Exit (locker);
778 aread.SetCompleted (true, saved);
787 servicePoint = GetServicePoint ();
788 abortHandler = servicePoint.SendRequest (this, connectionGroup);
791 Monitor.Exit (locker);
795 public override WebResponse EndGetResponse (IAsyncResult asyncResult)
797 if (asyncResult == null)
798 throw new ArgumentNullException ("asyncResult");
800 WebAsyncResult result = asyncResult as WebAsyncResult;
802 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
804 if (!result.WaitUntilComplete (timeout, false)) {
806 throw new WebException("The request timed out", WebExceptionStatus.Timeout);
809 if (result.GotException)
810 throw result.Exception;
812 return result.Response;
815 public override WebResponse GetResponse()
817 WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
818 return EndGetResponse (result);
821 internal bool FinishedReading {
822 get { return finished_reading; }
823 set { finished_reading = value; }
826 public override void Abort ()
832 if (haveResponse && finished_reading)
836 if (asyncWrite != null) {
837 WebAsyncResult r = asyncWrite;
838 if (!r.IsCompleted) {
840 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
841 r.SetCompleted (false, wexc);
848 if (asyncRead != null) {
849 WebAsyncResult r = asyncRead;
850 if (!r.IsCompleted) {
852 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
853 r.SetCompleted (false, wexc);
860 if (abortHandler != null) {
862 abortHandler (this, EventArgs.Empty);
863 } catch (Exception) {}
867 if (writeStream != null) {
869 writeStream.Close ();
874 if (webResponse != null) {
876 webResponse.Close ();
882 void ISerializable.GetObjectData (SerializationInfo serializationInfo,
883 StreamingContext streamingContext)
885 GetObjectData (serializationInfo, streamingContext);
891 void GetObjectData (SerializationInfo serializationInfo,
892 StreamingContext streamingContext)
894 SerializationInfo info = serializationInfo;
896 info.AddValue ("requestUri", requestUri, typeof (Uri));
897 info.AddValue ("actualUri", actualUri, typeof (Uri));
898 info.AddValue ("allowAutoRedirect", allowAutoRedirect);
899 info.AddValue ("allowBuffering", allowBuffering);
900 info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
901 info.AddValue ("connectionGroup", connectionGroup);
902 info.AddValue ("contentLength", contentLength);
903 info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
904 info.AddValue ("keepAlive", keepAlive);
905 info.AddValue ("maxAutoRedirect", maxAutoRedirect);
906 info.AddValue ("mediaType", mediaType);
907 info.AddValue ("method", method);
908 info.AddValue ("initialMethod", initialMethod);
909 info.AddValue ("pipelined", pipelined);
910 info.AddValue ("version", version, typeof (Version));
911 info.AddValue ("proxy", proxy, typeof (IWebProxy));
912 info.AddValue ("sendChunked", sendChunked);
913 info.AddValue ("timeout", timeout);
914 info.AddValue ("redirects", redirects);
917 void CheckRequestStarted ()
920 throw new InvalidOperationException ("request started");
923 internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
925 if (continueDelegate != null)
926 continueDelegate (statusCode, headers);
929 bool Redirect (WebAsyncResult result, HttpStatusCode code)
933 string uriString = null;
936 case HttpStatusCode.Ambiguous: // 300
937 e = new WebException ("Ambiguous redirect.");
939 case HttpStatusCode.MovedPermanently: // 301
940 case HttpStatusCode.Redirect: // 302
941 case HttpStatusCode.TemporaryRedirect: // 307
942 /* MS follows the redirect for POST too
943 if (method != "GET" && method != "HEAD") // 10.3
948 bodyBufferLength = 0;
951 uriString = webResponse.Headers ["Location"];
953 case HttpStatusCode.SeeOther: //303
955 uriString = webResponse.Headers ["Location"];
957 case HttpStatusCode.NotModified: // 304
959 case HttpStatusCode.UseProxy: // 305
960 e = new NotImplementedException ("Proxy support not available.");
962 case HttpStatusCode.Unused: // 306
964 e = new ProtocolViolationException ("Invalid status code: " + (int) code);
971 if (uriString == null)
972 throw new WebException ("No Location header found for " + (int) code,
973 WebExceptionStatus.ProtocolError);
975 Uri prev = actualUri;
977 actualUri = new Uri (actualUri, uriString);
978 } catch (Exception) {
979 throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
980 uriString, (int) code),
981 WebExceptionStatus.ProtocolError);
984 hostChanged = (actualUri.Scheme != prev.Scheme || actualUri.Host != prev.Host ||
985 actualUri.Port != prev.Port);
991 bool continue100 = false;
992 if (contentLength != -1) {
993 if (contentLength > 0)
995 webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
996 webHeaders.RemoveInternal ("Transfer-Encoding");
997 } else if (sendChunked) {
999 webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
1000 webHeaders.RemoveInternal ("Content-Length");
1003 if (actualVersion == HttpVersion.Version11 && continue100 &&
1004 servicePoint.SendContinue) { // RFC2616 8.2.3
1005 webHeaders.RemoveAndAdd ("Expect" , "100-continue");
1006 expectContinue = true;
1008 webHeaders.RemoveInternal ("Expect");
1009 expectContinue = false;
1012 bool proxy_query = ProxyQuery;
1013 string connectionHeader = (proxy_query) ? "Proxy-Connection" : "Connection";
1014 webHeaders.RemoveInternal ((!proxy_query) ? "Proxy-Connection" : "Connection");
1015 Version proto_version = servicePoint.ProtocolVersion;
1016 bool spoint10 = (proto_version == null || proto_version == HttpVersion.Version10);
1018 if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
1019 webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
1020 } else if (!keepAlive && version == HttpVersion.Version11) {
1021 webHeaders.RemoveAndAdd (connectionHeader, "close");
1024 webHeaders.SetInternal ("Host", actualUri.Authority);
1025 if (cookieContainer != null) {
1026 string cookieHeader = cookieContainer.GetCookieHeader (actualUri);
1027 if (cookieHeader != "")
1028 webHeaders.SetInternal ("Cookie", cookieHeader);
1032 string accept_encoding = null;
1033 if ((auto_decomp & DecompressionMethods.GZip) != 0)
1034 accept_encoding = "gzip";
1035 if ((auto_decomp & DecompressionMethods.Deflate) != 0)
1036 accept_encoding = accept_encoding != null ? "gzip, deflate" : "deflate";
1037 if (accept_encoding != null)
1038 webHeaders.SetInternal ("Accept-Encoding", accept_encoding);
1040 if (!usedPreAuth && preAuthenticate)
1041 DoPreAuthenticate ();
1043 return webHeaders.ToString ();
1046 void DoPreAuthenticate ()
1048 webHeaders.RemoveInternal ("Proxy-Authorization");
1049 webHeaders.RemoveInternal ("Authorization");
1050 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1051 ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
1052 Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
1056 string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
1057 webHeaders [authHeader] = auth.Message;
1061 internal void SetWriteStreamError (WebExceptionStatus status)
1063 SetWriteStreamError (status, null);
1066 internal void SetWriteStreamError (WebExceptionStatus status, Exception exc)
1071 WebAsyncResult r = asyncWrite;
1078 msg = "Error: " + status;
1080 msg = String.Format ("Error: {0} ({1})", status, exc.Message);
1081 r.SetCompleted (false, new WebException (msg, status));
1086 internal void SendRequestHeaders ()
1088 StringBuilder req = new StringBuilder ();
1091 query = actualUri.PathAndQuery;
1092 } else if (actualUri.IsDefaultPort) {
1093 query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
1095 actualUri.PathAndQuery);
1097 query = String.Format ("{0}://{1}:{2}{3}", actualUri.Scheme,
1100 actualUri.PathAndQuery);
1103 if (servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
1104 actualVersion = servicePoint.ProtocolVersion;
1106 actualVersion = version;
1109 req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
1110 actualVersion.Major, actualVersion.Minor);
1111 req.Append (GetHeaders ());
1112 string reqstr = req.ToString ();
1113 byte [] bytes = Encoding.UTF8.GetBytes (reqstr);
1115 writeStream.SetHeaders (bytes, 0, bytes.Length);
1116 } catch (WebException wexc) {
1117 SetWriteStreamError (wexc.Status);
1118 } catch (Exception) {
1119 SetWriteStreamError (WebExceptionStatus.SendFailure);
1123 internal void SetWriteStream (WebConnectionStream stream)
1128 writeStream = stream;
1129 if (bodyBuffer != null) {
1130 webHeaders.RemoveInternal ("Transfer-Encoding");
1131 contentLength = bodyBufferLength;
1132 writeStream.SendChunked = false;
1135 SendRequestHeaders ();
1139 if (bodyBuffer != null) {
1140 // The body has been written and buffered. The request "user"
1141 // won't write it again, so we must do it.
1142 writeStream.Write (bodyBuffer, 0, bodyBufferLength);
1144 writeStream.Close ();
1145 } else if (method == "PUT" || method == "POST" || method == "OPTIONS") {
1146 if (getResponseCalled && !writeStream.RequestWritten)
1147 writeStream.WriteRequest ();
1150 if (asyncWrite != null) {
1151 asyncWrite.SetCompleted (false, stream);
1152 asyncWrite.DoCallback ();
1157 internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
1162 string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
1163 WebAsyncResult r = asyncRead;
1168 if (e is WebException) {
1169 wexc = (WebException) e;
1171 wexc = new WebException (msg, e, status, null);
1174 if (!r.IsCompleted) {
1175 r.SetCompleted (false, wexc);
1177 } else if (r == asyncWrite) {
1180 haveResponse = true;
1184 haveResponse = true;
1190 void CheckSendError (WebConnectionData data)
1192 // Got here, but no one called GetResponse
1193 int status = data.StatusCode;
1194 if (status < 400 || status == 401 || status == 407)
1197 if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
1198 // The request has not been completely sent and we got here!
1199 // We should probably just close and cause an error in any case,
1200 saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse);
1201 webResponse.ReadAll ();
1205 void HandleNtlmAuth (WebAsyncResult r)
1207 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1209 WebConnection cnc = wce.Connection;
1210 cnc.PriorityRequest = this;
1211 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1212 ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1213 if (creds != null) {
1214 cnc.NtlmCredential = creds.GetCredential (requestUri, "NTLM");
1216 cnc.UnsafeAuthenticatedConnectionSharing = unsafe_auth_blah;
1221 haveResponse = false;
1222 webResponse.ReadAll ();
1226 internal void SetResponseData (WebConnectionData data)
1230 if (data.stream != null)
1231 data.stream.Close ();
1235 WebException wexc = null;
1237 webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
1238 } catch (Exception e) {
1239 wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null);
1240 if (data.stream != null)
1241 data.stream.Close ();
1244 if (wexc == null && (method == "POST" || method == "PUT")) {
1246 CheckSendError (data);
1247 if (saved_exc != null)
1248 wexc = (WebException) saved_exc;
1252 WebAsyncResult r = asyncRead;
1254 bool forced = false;
1255 if (r == null && webResponse != null) {
1256 // This is a forced completion (302, 204)...
1258 r = new WebAsyncResult (null, null);
1259 r.SetCompleted (false, webResponse);
1264 r.SetCompleted (false, wexc);
1271 redirected = CheckFinalStatus (r);
1273 if (is_ntlm_auth && authCompleted && webResponse != null
1274 && (int)webResponse.StatusCode < 400) {
1275 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1277 WebConnection cnc = wce.Connection;
1278 cnc.NtlmAuthenticated = true;
1282 // clear internal buffer so that it does not
1283 // hold possible big buffer (bug #397627)
1284 if (writeStream != null)
1285 writeStream.KillBuffer ();
1287 haveResponse = true;
1288 r.SetCompleted (false, webResponse);
1291 if (webResponse != null) {
1296 webResponse.Close ();
1298 haveResponse = false;
1301 servicePoint = GetServicePoint ();
1302 abortHandler = servicePoint.SendRequest (this, connectionGroup);
1304 } catch (WebException wexc2) {
1307 haveResponse = true;
1309 r.SetCompleted (false, wexc2);
1312 } catch (Exception ex) {
1313 wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
1316 haveResponse = true;
1318 r.SetCompleted (false, wexc);
1326 bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1328 authCompleted = false;
1329 if (code == HttpStatusCode.Unauthorized && credentials == null)
1332 bool isProxy = (code == HttpStatusCode.ProxyAuthenticationRequired);
1333 if (isProxy && (proxy == null || proxy.Credentials == null))
1336 string authHeader = response.Headers [(isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate"];
1337 if (authHeader == null)
1340 ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1341 Authorization auth = AuthenticationManager.Authenticate (authHeader, this, creds);
1345 webHeaders [(isProxy) ? "Proxy-Authorization" : "Authorization"] = auth.Message;
1346 authCompleted = auth.Complete;
1347 is_ntlm_auth = (auth.Module.AuthenticationType == "NTLM");
1351 // Returns true if redirected
1352 bool CheckFinalStatus (WebAsyncResult result)
1354 if (result.GotException)
1355 throw result.Exception;
1357 Exception throwMe = result.Exception;
1360 HttpWebResponse resp = result.Response;
1361 WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
1362 HttpStatusCode code = 0;
1363 if (throwMe == null && webResponse != null) {
1364 code = webResponse.StatusCode;
1365 if (!authCompleted && ((code == HttpStatusCode.Unauthorized && credentials != null) ||
1366 (ProxyQuery && code == HttpStatusCode.ProxyAuthenticationRequired))) {
1367 if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
1368 // Keep the written body, so it can be rewritten in the retry
1369 if (InternalAllowBuffering) {
1370 bodyBuffer = writeStream.WriteBuffer;
1371 bodyBufferLength = writeStream.WriteBufferLength;
1373 } else if (method != "PUT" && method != "POST") {
1377 writeStream.InternalClose ();
1379 webResponse.Close ();
1382 throw new WebException ("This request requires buffering " +
1383 "of data for authentication or " +
1384 "redirection to be sucessful.");
1388 if ((int) code >= 400) {
1389 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1390 (int) code, webResponse.StatusDescription);
1391 throwMe = new WebException (err, null, protoError, webResponse);
1392 webResponse.ReadAll ();
1393 } else if ((int) code == 304 && allowAutoRedirect) {
1394 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1395 (int) code, webResponse.StatusDescription);
1396 throwMe = new WebException (err, null, protoError, webResponse);
1397 } else if ((int) code >= 300 && allowAutoRedirect && redirects >= maxAutoRedirect) {
1398 throwMe = new WebException ("Max. redirections exceeded.", null,
1399 protoError, webResponse);
1400 webResponse.ReadAll ();
1404 if (throwMe == null) {
1407 if (allowAutoRedirect && c >= 300) {
1408 if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
1409 bodyBuffer = writeStream.WriteBuffer;
1410 bodyBufferLength = writeStream.WriteBufferLength;
1412 b = Redirect (result, code);
1415 if (resp != null && c >= 300 && c != 304)
1421 if (writeStream != null) {
1422 writeStream.InternalClose ();