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 ();
100 bool finished_reading;
101 internal WebConnection WebConnection;
102 DecompressionMethods auto_decomp;
103 int maxResponseHeadersLength;
104 static int defaultMaxResponseHeadersLength;
105 int readWriteTimeout = 300000; // ms
108 static HttpWebRequest ()
110 defaultMaxResponseHeadersLength = 64 * 1024;
112 NetConfig config = ConfigurationSettings.GetConfig ("system.net/settings") as NetConfig;
113 if (config != null) {
114 int x = config.MaxResponseHeadersLength;
118 defaultMaxResponseHeadersLength = x;
128 HttpWebRequest (Uri uri)
130 this.requestUri = uri;
131 this.actualUri = uri;
132 this.proxy = GlobalProxySelection.Select;
135 [Obsolete ("Serialization is obsoleted for this type", false)]
136 protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
138 SerializationInfo info = serializationInfo;
140 requestUri = (Uri) info.GetValue ("requestUri", typeof (Uri));
141 actualUri = (Uri) info.GetValue ("actualUri", typeof (Uri));
142 allowAutoRedirect = info.GetBoolean ("allowAutoRedirect");
143 allowBuffering = info.GetBoolean ("allowBuffering");
144 certificates = (X509CertificateCollection) info.GetValue ("certificates", typeof (X509CertificateCollection));
145 connectionGroup = info.GetString ("connectionGroup");
146 contentLength = info.GetInt64 ("contentLength");
147 webHeaders = (WebHeaderCollection) info.GetValue ("webHeaders", typeof (WebHeaderCollection));
148 keepAlive = info.GetBoolean ("keepAlive");
149 maxAutoRedirect = info.GetInt32 ("maxAutoRedirect");
150 mediaType = info.GetString ("mediaType");
151 method = info.GetString ("method");
152 initialMethod = info.GetString ("initialMethod");
153 pipelined = info.GetBoolean ("pipelined");
154 version = (Version) info.GetValue ("version", typeof (Version));
155 proxy = (IWebProxy) info.GetValue ("proxy", typeof (IWebProxy));
156 sendChunked = info.GetBoolean ("sendChunked");
157 timeout = info.GetInt32 ("timeout");
158 redirects = info.GetInt32 ("redirects");
163 internal bool UsesNtlmAuthentication {
164 get { return is_ntlm_auth; }
167 public string Accept {
168 get { return webHeaders ["Accept"]; }
170 CheckRequestStarted ();
171 webHeaders.RemoveAndAdd ("Accept", value);
176 get { return actualUri; }
179 public bool AllowAutoRedirect {
180 get { return allowAutoRedirect; }
181 set { this.allowAutoRedirect = value; }
184 public bool AllowWriteStreamBuffering {
185 get { return allowBuffering; }
186 set { allowBuffering = value; }
189 static Exception GetMustImplement ()
191 return new NotImplementedException ();
194 public DecompressionMethods AutomaticDecompression
200 CheckRequestStarted ();
205 internal bool InternalAllowBuffering {
207 return (allowBuffering && (method != "HEAD" && method != "GET" &&
208 method != "MKCOL" && method != "CONNECT" &&
209 method != "DELETE" && method != "TRACE"));
213 public X509CertificateCollection ClientCertificates {
215 if (certificates == null)
216 certificates = new X509CertificateCollection ();
222 throw GetMustImplement ();
226 public string Connection {
227 get { return webHeaders ["Connection"]; }
229 CheckRequestStarted ();
232 val = val.Trim ().ToLower ();
234 if (val == null || val.Length == 0) {
235 webHeaders.RemoveInternal ("Connection");
239 if (val == "keep-alive" || val == "close")
240 throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
242 if (keepAlive && val.IndexOf ("keep-alive") == -1)
243 value = value + ", Keep-Alive";
245 webHeaders.RemoveAndAdd ("Connection", value);
249 public override string ConnectionGroupName {
250 get { return connectionGroup; }
251 set { connectionGroup = value; }
254 public override long ContentLength {
255 get { return contentLength; }
257 CheckRequestStarted ();
259 throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
261 contentLength = value;
265 internal long InternalContentLength {
266 set { contentLength = value; }
269 public override string ContentType {
270 get { return webHeaders ["Content-Type"]; }
272 if (value == null || value.Trim().Length == 0) {
273 webHeaders.RemoveInternal ("Content-Type");
276 webHeaders.RemoveAndAdd ("Content-Type", value);
280 public HttpContinueDelegate ContinueDelegate {
281 get { return continueDelegate; }
282 set { continueDelegate = value; }
285 public CookieContainer CookieContainer {
286 get { return cookieContainer; }
287 set { cookieContainer = value; }
290 public override ICredentials Credentials {
291 get { return credentials; }
292 set { credentials = value; }
296 public static new RequestCachePolicy DefaultCachePolicy
299 throw GetMustImplement ();
302 throw GetMustImplement ();
307 public static int DefaultMaximumErrorResponseLength
310 throw GetMustImplement ();
313 throw GetMustImplement ();
317 public string Expect {
318 get { return webHeaders ["Expect"]; }
320 CheckRequestStarted ();
323 val = val.Trim ().ToLower ();
325 if (val == null || val.Length == 0) {
326 webHeaders.RemoveInternal ("Expect");
330 if (val == "100-continue")
331 throw new ArgumentException ("100-Continue cannot be set with this property.",
333 webHeaders.RemoveAndAdd ("Expect", value);
337 public bool HaveResponse {
338 get { return haveResponse; }
341 public override WebHeaderCollection Headers {
342 get { return webHeaders; }
344 CheckRequestStarted ();
345 WebHeaderCollection newHeaders = new WebHeaderCollection (true);
346 int count = value.Count;
347 for (int i = 0; i < count; i++)
348 newHeaders.Add (value.GetKey (i), value.Get (i));
350 webHeaders = newHeaders;
354 public DateTime IfModifiedSince {
356 string str = webHeaders ["If-Modified-Since"];
360 return MonoHttpDate.Parse (str);
361 } catch (Exception) {
366 CheckRequestStarted ();
368 webHeaders.SetInternal ("If-Modified-Since",
369 value.ToUniversalTime ().ToString ("r", null));
370 // TODO: check last param when using different locale
374 public bool KeepAlive {
383 public int MaximumAutomaticRedirections {
384 get { return maxAutoRedirect; }
387 throw new ArgumentException ("Must be > 0", "value");
389 maxAutoRedirect = value;
393 [MonoTODO ("Use this")]
394 public int MaximumResponseHeadersLength {
395 get { return maxResponseHeadersLength; }
396 set { maxResponseHeadersLength = value; }
399 [MonoTODO ("Use this")]
400 public static int DefaultMaximumResponseHeadersLength {
401 get { return defaultMaxResponseHeadersLength; }
402 set { defaultMaxResponseHeadersLength = value; }
405 public int ReadWriteTimeout {
406 get { return readWriteTimeout; }
409 throw new InvalidOperationException ("The request has already been sent.");
412 throw new ArgumentOutOfRangeException ("value", "Must be >= -1");
414 readWriteTimeout = value;
418 public string MediaType {
419 get { return mediaType; }
425 public override string Method {
426 get { return this.method; }
428 if (value == null || value.Trim () == "")
429 throw new ArgumentException ("not a valid method");
435 public bool Pipelined {
436 get { return pipelined; }
437 set { pipelined = value; }
440 public override bool PreAuthenticate {
441 get { return preAuthenticate; }
442 set { preAuthenticate = value; }
445 public Version ProtocolVersion {
446 get { return version; }
448 if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
449 throw new ArgumentException ("value");
455 public override IWebProxy Proxy {
456 get { return proxy; }
458 CheckRequestStarted ();
460 servicePoint = null; // we may need a new one
464 public string Referer {
465 get { return webHeaders ["Referer"]; }
467 CheckRequestStarted ();
468 if (value == null || value.Trim().Length == 0) {
469 webHeaders.RemoveInternal ("Referer");
472 webHeaders.SetInternal ("Referer", value);
476 public override Uri RequestUri {
477 get { return requestUri; }
480 public bool SendChunked {
481 get { return sendChunked; }
483 CheckRequestStarted ();
488 public ServicePoint ServicePoint {
489 get { return GetServicePoint (); }
492 public override int Timeout {
493 get { return timeout; }
496 throw new ArgumentOutOfRangeException ("value");
502 public string TransferEncoding {
503 get { return webHeaders ["Transfer-Encoding"]; }
505 CheckRequestStarted ();
508 val = val.Trim ().ToLower ();
510 if (val == null || val.Length == 0) {
511 webHeaders.RemoveInternal ("Transfer-Encoding");
515 if (val == "chunked")
516 throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
519 throw new ArgumentException ("SendChunked must be True", "value");
521 webHeaders.RemoveAndAdd ("Transfer-Encoding", value);
525 public override bool UseDefaultCredentials
527 get { return CredentialCache.DefaultCredentials == Credentials; }
528 set { Credentials = value ? CredentialCache.DefaultCredentials : null; }
531 public string UserAgent {
532 get { return webHeaders ["User-Agent"]; }
533 set { webHeaders.SetInternal ("User-Agent", value); }
536 bool unsafe_auth_blah;
537 public bool UnsafeAuthenticatedConnectionSharing
539 get { return unsafe_auth_blah; }
540 set { unsafe_auth_blah = value; }
543 internal bool GotRequestStream {
544 get { return gotRequestStream; }
547 internal bool ExpectContinue {
548 get { return expectContinue; }
549 set { expectContinue = value; }
552 internal Uri AuthUri {
553 get { return actualUri; }
556 internal bool ProxyQuery {
557 get { return servicePoint.UsesProxy && !servicePoint.UseConnect; }
562 internal ServicePoint GetServicePoint ()
565 if (hostChanged || servicePoint == null) {
566 servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
574 public void AddRange (int range)
576 AddRange ("bytes", range);
579 public void AddRange (int from, int to)
581 AddRange ("bytes", from, to);
584 public void AddRange (string rangeSpecifier, int range)
586 if (rangeSpecifier == null)
587 throw new ArgumentNullException ("rangeSpecifier");
588 string value = webHeaders ["Range"];
589 if (value == null || value.Length == 0)
590 value = rangeSpecifier + "=";
591 else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
594 throw new InvalidOperationException ("rangeSpecifier");
595 webHeaders.RemoveAndAdd ("Range", value + range + "-");
598 public void AddRange (string rangeSpecifier, int from, int to)
600 if (rangeSpecifier == null)
601 throw new ArgumentNullException ("rangeSpecifier");
602 if (from < 0 || to < 0 || from > to)
603 throw new ArgumentOutOfRangeException ();
604 string value = webHeaders ["Range"];
605 if (value == null || value.Length == 0)
606 value = rangeSpecifier + "=";
607 else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
610 throw new InvalidOperationException ("rangeSpecifier");
611 webHeaders.RemoveAndAdd ("Range", value + from + "-" + to);
614 public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
617 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
619 bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
620 method == "TRACE" || method == "DELETE");
621 if (method == null || !send)
622 throw new ProtocolViolationException ("Cannot send data when method is: " + method);
624 if (contentLength == -1 && !sendChunked && !allowBuffering && KeepAlive)
625 throw new ProtocolViolationException ("Content-Length not set");
627 string transferEncoding = TransferEncoding;
628 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
629 throw new ProtocolViolationException ("SendChunked should be true.");
633 if (asyncWrite != null) {
634 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
635 "method while a previous call is still in progress.");
638 asyncWrite = new WebAsyncResult (this, callback, state);
639 initialMethod = method;
641 if (writeStream != null) {
642 asyncWrite.SetCompleted (true, writeStream);
643 asyncWrite.DoCallback ();
648 gotRequestStream = true;
649 WebAsyncResult result = asyncWrite;
653 servicePoint = GetServicePoint ();
654 abortHandler = servicePoint.SendRequest (this, connectionGroup);
660 public override Stream EndGetRequestStream (IAsyncResult asyncResult)
662 if (asyncResult == null)
663 throw new ArgumentNullException ("asyncResult");
665 WebAsyncResult result = asyncResult as WebAsyncResult;
667 throw new ArgumentException ("Invalid IAsyncResult");
670 result.WaitUntilComplete ();
672 Exception e = result.Exception;
676 return result.WriteStream;
679 public override Stream GetRequestStream()
681 IAsyncResult asyncResult = asyncWrite;
682 if (asyncResult == null) {
683 asyncResult = BeginGetRequestStream (null, null);
684 asyncWrite = (WebAsyncResult) asyncResult;
687 if (!asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
689 throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
692 return EndGetRequestStream (asyncResult);
695 void CheckIfForceWrite ()
697 if (writeStream == null || writeStream.RequestWritten|| contentLength < 0 || !InternalAllowBuffering)
700 // This will write the POST/PUT if the write stream already has the expected
701 // amount of bytes in it (ContentLength) (bug #77753).
702 if (writeStream.WriteBufferLength == contentLength)
703 writeStream.WriteRequest ();
706 public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
709 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
712 throw new ProtocolViolationException ("Method is null.");
714 string transferEncoding = TransferEncoding;
715 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
716 throw new ProtocolViolationException ("SendChunked should be true.");
718 Monitor.Enter (locker);
719 getResponseCalled = true;
720 if (asyncRead != null && !haveResponse) {
721 Monitor.Exit (locker);
722 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
723 "method while a previous call is still in progress.");
726 CheckIfForceWrite ();
727 asyncRead = new WebAsyncResult (this, callback, state);
728 WebAsyncResult aread = asyncRead;
729 initialMethod = method;
731 Exception saved = saved_exc;
732 if (webResponse != null) {
733 Monitor.Exit (locker);
735 aread.SetCompleted (true, webResponse);
737 aread.SetCompleted (true, saved);
741 } else if (saved != null) {
742 Monitor.Exit (locker);
743 aread.SetCompleted (true, saved);
752 servicePoint = GetServicePoint ();
753 abortHandler = servicePoint.SendRequest (this, connectionGroup);
756 Monitor.Exit (locker);
760 public override WebResponse EndGetResponse (IAsyncResult asyncResult)
762 if (asyncResult == null)
763 throw new ArgumentNullException ("asyncResult");
765 WebAsyncResult result = asyncResult as WebAsyncResult;
767 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
769 if (!result.WaitUntilComplete (timeout, false)) {
771 throw new WebException("The request timed out", WebExceptionStatus.Timeout);
774 if (result.GotException)
775 throw result.Exception;
777 return result.Response;
780 public override WebResponse GetResponse()
782 WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
783 return EndGetResponse (result);
786 internal bool FinishedReading {
787 get { return finished_reading; }
788 set { finished_reading = value; }
791 internal bool Aborted {
792 get { return Interlocked.CompareExchange (ref aborted, 0, 0) == 1; }
795 public override void Abort ()
797 if (Interlocked.CompareExchange (ref aborted, 1, 0) == 1)
800 if (haveResponse && finished_reading)
804 if (abortHandler != null) {
806 abortHandler (this, EventArgs.Empty);
807 } catch (Exception) {}
811 if (asyncWrite != null) {
812 WebAsyncResult r = asyncWrite;
813 if (!r.IsCompleted) {
815 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
816 r.SetCompleted (false, wexc);
823 if (asyncRead != null) {
824 WebAsyncResult r = asyncRead;
825 if (!r.IsCompleted) {
827 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
828 r.SetCompleted (false, wexc);
835 if (writeStream != null) {
837 writeStream.Close ();
842 if (webResponse != null) {
844 webResponse.Close ();
850 void ISerializable.GetObjectData (SerializationInfo serializationInfo,
851 StreamingContext streamingContext)
853 GetObjectData (serializationInfo, streamingContext);
856 protected override void GetObjectData (SerializationInfo serializationInfo,
857 StreamingContext streamingContext)
859 SerializationInfo info = serializationInfo;
861 info.AddValue ("requestUri", requestUri, typeof (Uri));
862 info.AddValue ("actualUri", actualUri, typeof (Uri));
863 info.AddValue ("allowAutoRedirect", allowAutoRedirect);
864 info.AddValue ("allowBuffering", allowBuffering);
865 info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
866 info.AddValue ("connectionGroup", connectionGroup);
867 info.AddValue ("contentLength", contentLength);
868 info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
869 info.AddValue ("keepAlive", keepAlive);
870 info.AddValue ("maxAutoRedirect", maxAutoRedirect);
871 info.AddValue ("mediaType", mediaType);
872 info.AddValue ("method", method);
873 info.AddValue ("initialMethod", initialMethod);
874 info.AddValue ("pipelined", pipelined);
875 info.AddValue ("version", version, typeof (Version));
876 info.AddValue ("proxy", proxy, typeof (IWebProxy));
877 info.AddValue ("sendChunked", sendChunked);
878 info.AddValue ("timeout", timeout);
879 info.AddValue ("redirects", redirects);
882 void CheckRequestStarted ()
885 throw new InvalidOperationException ("request started");
888 internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
890 if (continueDelegate != null)
891 continueDelegate (statusCode, headers);
894 bool Redirect (WebAsyncResult result, HttpStatusCode code)
898 string uriString = null;
901 case HttpStatusCode.Ambiguous: // 300
902 e = new WebException ("Ambiguous redirect.");
904 case HttpStatusCode.MovedPermanently: // 301
905 case HttpStatusCode.Redirect: // 302
906 case HttpStatusCode.TemporaryRedirect: // 307
907 /* MS follows the redirect for POST too
908 if (method != "GET" && method != "HEAD") // 10.3
913 bodyBufferLength = 0;
916 uriString = webResponse.Headers ["Location"];
918 case HttpStatusCode.SeeOther: //303
920 uriString = webResponse.Headers ["Location"];
922 case HttpStatusCode.NotModified: // 304
924 case HttpStatusCode.UseProxy: // 305
925 e = new NotImplementedException ("Proxy support not available.");
927 case HttpStatusCode.Unused: // 306
929 e = new ProtocolViolationException ("Invalid status code: " + (int) code);
936 if (uriString == null)
937 throw new WebException ("No Location header found for " + (int) code,
938 WebExceptionStatus.ProtocolError);
940 Uri prev = actualUri;
942 actualUri = new Uri (actualUri, uriString);
943 } catch (Exception) {
944 throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
945 uriString, (int) code),
946 WebExceptionStatus.ProtocolError);
949 hostChanged = (actualUri.Scheme != prev.Scheme || actualUri.Host != prev.Host ||
950 actualUri.Port != prev.Port);
956 bool continue100 = false;
959 webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
960 webHeaders.RemoveInternal ("Content-Length");
961 } else if (contentLength != -1) {
962 if (contentLength > 0)
964 webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
965 webHeaders.RemoveInternal ("Transfer-Encoding");
968 if (actualVersion == HttpVersion.Version11 && continue100 &&
969 servicePoint.SendContinue) { // RFC2616 8.2.3
970 webHeaders.RemoveAndAdd ("Expect" , "100-continue");
971 expectContinue = true;
973 webHeaders.RemoveInternal ("Expect");
974 expectContinue = false;
977 bool proxy_query = ProxyQuery;
978 string connectionHeader = (proxy_query) ? "Proxy-Connection" : "Connection";
979 webHeaders.RemoveInternal ((!proxy_query) ? "Proxy-Connection" : "Connection");
980 Version proto_version = servicePoint.ProtocolVersion;
981 bool spoint10 = (proto_version == null || proto_version == HttpVersion.Version10);
983 if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
984 webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
985 } else if (!keepAlive && version == HttpVersion.Version11) {
986 webHeaders.RemoveAndAdd (connectionHeader, "close");
989 webHeaders.SetInternal ("Host", actualUri.Authority);
990 if (cookieContainer != null) {
991 string cookieHeader = cookieContainer.GetCookieHeader (actualUri);
992 if (cookieHeader != "")
993 webHeaders.SetInternal ("Cookie", cookieHeader);
996 string accept_encoding = null;
997 if ((auto_decomp & DecompressionMethods.GZip) != 0)
998 accept_encoding = "gzip";
999 if ((auto_decomp & DecompressionMethods.Deflate) != 0)
1000 accept_encoding = accept_encoding != null ? "gzip, deflate" : "deflate";
1001 if (accept_encoding != null)
1002 webHeaders.RemoveAndAdd ("Accept-Encoding", accept_encoding);
1004 if (!usedPreAuth && preAuthenticate)
1005 DoPreAuthenticate ();
1007 return webHeaders.ToString ();
1010 void DoPreAuthenticate ()
1012 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1013 ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
1014 Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
1018 webHeaders.RemoveInternal ("Proxy-Authorization");
1019 webHeaders.RemoveInternal ("Authorization");
1020 string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
1021 webHeaders [authHeader] = auth.Message;
1025 internal void SetWriteStreamError (WebExceptionStatus status, Exception exc)
1030 WebAsyncResult r = asyncWrite;
1038 msg = "Error: " + status;
1039 wex = new WebException (msg, status);
1041 msg = String.Format ("Error: {0} ({1})", status, exc.Message);
1042 wex = new WebException (msg, exc, status);
1044 r.SetCompleted (false, wex);
1049 internal void SendRequestHeaders (bool propagate_error)
1051 StringBuilder req = new StringBuilder ();
1054 query = actualUri.PathAndQuery;
1055 } else if (actualUri.IsDefaultPort) {
1056 query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
1058 actualUri.PathAndQuery);
1060 query = String.Format ("{0}://{1}:{2}{3}", actualUri.Scheme,
1063 actualUri.PathAndQuery);
1066 if (servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
1067 actualVersion = servicePoint.ProtocolVersion;
1069 actualVersion = version;
1072 req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
1073 actualVersion.Major, actualVersion.Minor);
1074 req.Append (GetHeaders ());
1075 string reqstr = req.ToString ();
1076 byte [] bytes = Encoding.UTF8.GetBytes (reqstr);
1078 writeStream.SetHeaders (bytes);
1079 } catch (WebException wexc) {
1080 SetWriteStreamError (wexc.Status, wexc);
1081 if (propagate_error)
1083 } catch (Exception exc) {
1084 SetWriteStreamError (WebExceptionStatus.SendFailure, exc);
1085 if (propagate_error)
1090 internal void SetWriteStream (WebConnectionStream stream)
1095 writeStream = stream;
1096 if (bodyBuffer != null) {
1097 webHeaders.RemoveInternal ("Transfer-Encoding");
1098 contentLength = bodyBufferLength;
1099 writeStream.SendChunked = false;
1102 SendRequestHeaders (false);
1106 if (bodyBuffer != null) {
1107 // The body has been written and buffered. The request "user"
1108 // won't write it again, so we must do it.
1109 writeStream.Write (bodyBuffer, 0, bodyBufferLength);
1111 writeStream.Close ();
1112 } else if (method != "HEAD" && method != "GET" && method != "MKCOL" && method != "CONNECT" &&
1113 method != "DELETE" && method != "TRACE") {
1114 if (getResponseCalled && !writeStream.RequestWritten)
1115 writeStream.WriteRequest ();
1118 if (asyncWrite != null) {
1119 asyncWrite.SetCompleted (false, stream);
1120 asyncWrite.DoCallback ();
1125 internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
1130 string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
1131 WebAsyncResult r = asyncRead;
1136 if (e is WebException) {
1137 wexc = (WebException) e;
1139 wexc = new WebException (msg, e, status, null);
1142 if (!r.IsCompleted) {
1143 r.SetCompleted (false, wexc);
1145 } else if (r == asyncWrite) {
1148 haveResponse = true;
1152 haveResponse = true;
1158 void CheckSendError (WebConnectionData data)
1160 // Got here, but no one called GetResponse
1161 int status = data.StatusCode;
1162 if (status < 400 || status == 401 || status == 407)
1165 if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
1166 // The request has not been completely sent and we got here!
1167 // We should probably just close and cause an error in any case,
1168 saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse);
1169 webResponse.ReadAll ();
1173 void HandleNtlmAuth (WebAsyncResult r)
1175 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1177 WebConnection cnc = wce.Connection;
1178 cnc.PriorityRequest = this;
1179 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1180 ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1181 if (creds != null) {
1182 cnc.NtlmCredential = creds.GetCredential (requestUri, "NTLM");
1183 cnc.UnsafeAuthenticatedConnectionSharing = unsafe_auth_blah;
1187 haveResponse = false;
1188 webResponse.ReadAll ();
1192 internal void SetResponseData (WebConnectionData data)
1196 if (data.stream != null)
1197 data.stream.Close ();
1201 WebException wexc = null;
1203 webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
1204 } catch (Exception e) {
1205 wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null);
1206 if (data.stream != null)
1207 data.stream.Close ();
1210 if (wexc == null && (method == "POST" || method == "PUT")) {
1212 CheckSendError (data);
1213 if (saved_exc != null)
1214 wexc = (WebException) saved_exc;
1218 WebAsyncResult r = asyncRead;
1220 bool forced = false;
1221 if (r == null && webResponse != null) {
1222 // This is a forced completion (302, 204)...
1224 r = new WebAsyncResult (null, null);
1225 r.SetCompleted (false, webResponse);
1230 r.SetCompleted (false, wexc);
1237 redirected = CheckFinalStatus (r);
1239 if (is_ntlm_auth && authCompleted && webResponse != null
1240 && (int)webResponse.StatusCode < 400) {
1241 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1243 WebConnection cnc = wce.Connection;
1244 cnc.NtlmAuthenticated = true;
1248 // clear internal buffer so that it does not
1249 // hold possible big buffer (bug #397627)
1250 if (writeStream != null)
1251 writeStream.KillBuffer ();
1253 haveResponse = true;
1254 r.SetCompleted (false, webResponse);
1257 if (webResponse != null) {
1262 webResponse.Close ();
1264 finished_reading = false;
1265 haveResponse = false;
1268 servicePoint = GetServicePoint ();
1269 abortHandler = servicePoint.SendRequest (this, connectionGroup);
1271 } catch (WebException wexc2) {
1274 haveResponse = true;
1276 r.SetCompleted (false, wexc2);
1279 } catch (Exception ex) {
1280 wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
1283 haveResponse = true;
1285 r.SetCompleted (false, wexc);
1293 bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1295 authCompleted = false;
1296 if (code == HttpStatusCode.Unauthorized && credentials == null)
1299 bool isProxy = (code == HttpStatusCode.ProxyAuthenticationRequired);
1300 if (isProxy && (proxy == null || proxy.Credentials == null))
1303 string [] authHeaders = response.Headers.GetValues ( (isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate");
1304 if (authHeaders == null || authHeaders.Length == 0)
1307 ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1308 Authorization auth = null;
1309 foreach (string authHeader in authHeaders) {
1310 auth = AuthenticationManager.Authenticate (authHeader, this, creds);
1316 webHeaders [(isProxy) ? "Proxy-Authorization" : "Authorization"] = auth.Message;
1317 authCompleted = auth.Complete;
1318 is_ntlm_auth = (auth.Module.AuthenticationType == "NTLM");
1322 // Returns true if redirected
1323 bool CheckFinalStatus (WebAsyncResult result)
1325 if (result.GotException)
1326 throw result.Exception;
1328 Exception throwMe = result.Exception;
1331 HttpWebResponse resp = result.Response;
1332 WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
1333 HttpStatusCode code = 0;
1334 if (throwMe == null && webResponse != null) {
1335 code = webResponse.StatusCode;
1336 if (!authCompleted && ((code == HttpStatusCode.Unauthorized && credentials != null) ||
1337 (ProxyQuery && code == HttpStatusCode.ProxyAuthenticationRequired))) {
1338 if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
1339 // Keep the written body, so it can be rewritten in the retry
1340 if (InternalAllowBuffering) {
1341 bodyBuffer = writeStream.WriteBuffer;
1342 bodyBufferLength = writeStream.WriteBufferLength;
1344 } else if (method != "PUT" && method != "POST") {
1348 writeStream.InternalClose ();
1350 webResponse.Close ();
1353 throw new WebException ("This request requires buffering " +
1354 "of data for authentication or " +
1355 "redirection to be sucessful.");
1359 if ((int) code >= 400) {
1360 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1361 (int) code, webResponse.StatusDescription);
1362 throwMe = new WebException (err, null, protoError, webResponse);
1363 webResponse.ReadAll ();
1364 } else if ((int) code == 304 && allowAutoRedirect) {
1365 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1366 (int) code, webResponse.StatusDescription);
1367 throwMe = new WebException (err, null, protoError, webResponse);
1368 } else if ((int) code >= 300 && allowAutoRedirect && redirects >= maxAutoRedirect) {
1369 throwMe = new WebException ("Max. redirections exceeded.", null,
1370 protoError, webResponse);
1371 webResponse.ReadAll ();
1375 if (throwMe == null) {
1378 if (allowAutoRedirect && c >= 300) {
1379 if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
1380 bodyBuffer = writeStream.WriteBuffer;
1381 bodyBufferLength = writeStream.WriteBufferLength;
1383 b = Redirect (result, code);
1386 if (resp != null && c >= 300 && c != 304)
1392 if (writeStream != null) {
1393 writeStream.InternalClose ();