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 ();
101 int maxResponseHeadersLength;
102 static int defaultMaxResponseHeadersLength;
103 int readWriteTimeout = 300000; // ms
106 static HttpWebRequest ()
108 NetConfig config = ConfigurationSettings.GetConfig ("system.net/settings") as NetConfig;
109 defaultMaxResponseHeadersLength = 64 * 1024;
110 if (config != null) {
111 int x = config.MaxResponseHeadersLength;
115 defaultMaxResponseHeadersLength = x;
125 HttpWebRequest (Uri uri)
127 this.requestUri = uri;
128 this.actualUri = uri;
129 this.proxy = GlobalProxySelection.Select;
133 [Obsolete ("Serialization is obsoleted for this type", false)]
135 protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
137 SerializationInfo info = serializationInfo;
139 requestUri = (Uri) info.GetValue ("requestUri", typeof (Uri));
140 actualUri = (Uri) info.GetValue ("actualUri", typeof (Uri));
141 allowAutoRedirect = info.GetBoolean ("allowAutoRedirect");
142 allowBuffering = info.GetBoolean ("allowBuffering");
143 certificates = (X509CertificateCollection) info.GetValue ("certificates", typeof (X509CertificateCollection));
144 connectionGroup = info.GetString ("connectionGroup");
145 contentLength = info.GetInt64 ("contentLength");
146 webHeaders = (WebHeaderCollection) info.GetValue ("webHeaders", typeof (WebHeaderCollection));
147 keepAlive = info.GetBoolean ("keepAlive");
148 maxAutoRedirect = info.GetInt32 ("maxAutoRedirect");
149 mediaType = info.GetString ("mediaType");
150 method = info.GetString ("method");
151 initialMethod = info.GetString ("initialMethod");
152 pipelined = info.GetBoolean ("pipelined");
153 version = (Version) info.GetValue ("version", typeof (Version));
154 proxy = (IWebProxy) info.GetValue ("proxy", typeof (IWebProxy));
155 sendChunked = info.GetBoolean ("sendChunked");
156 timeout = info.GetInt32 ("timeout");
157 redirects = info.GetInt32 ("redirects");
162 internal bool UsesNtlmAuthentication {
163 get { return is_ntlm_auth; }
166 public string Accept {
167 get { return webHeaders ["Accept"]; }
169 CheckRequestStarted ();
170 webHeaders.RemoveAndAdd ("Accept", value);
175 get { return actualUri; }
178 public bool AllowAutoRedirect {
179 get { return allowAutoRedirect; }
180 set { this.allowAutoRedirect = value; }
183 public bool AllowWriteStreamBuffering {
184 get { return allowBuffering; }
185 set { allowBuffering = value; }
189 static Exception GetMustImplement ()
191 return new NotImplementedException ();
195 public DecompressionMethods AutomaticDecompression
198 throw GetMustImplement ();
201 throw GetMustImplement ();
206 internal bool InternalAllowBuffering {
208 return (allowBuffering && (method != "HEAD" && method != "GET" &&
209 method != "MKCOL" && method != "CONNECT" &&
210 method != "DELETE" && method != "TRACE"));
214 public X509CertificateCollection ClientCertificates {
216 if (certificates == null)
217 certificates = new X509CertificateCollection ();
224 throw GetMustImplement ();
229 public string Connection {
230 get { return webHeaders ["Connection"]; }
232 CheckRequestStarted ();
235 val = val.Trim ().ToLower ();
237 if (val == null || val.Length == 0) {
238 webHeaders.RemoveInternal ("Connection");
242 if (val == "keep-alive" || val == "close")
243 throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
245 if (keepAlive && val.IndexOf ("keep-alive") == -1)
246 value = value + ", Keep-Alive";
248 webHeaders.RemoveAndAdd ("Connection", value);
252 public override string ConnectionGroupName {
253 get { return connectionGroup; }
254 set { connectionGroup = value; }
257 public override long ContentLength {
258 get { return contentLength; }
260 CheckRequestStarted ();
262 throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
264 contentLength = value;
268 internal long InternalContentLength {
269 set { contentLength = value; }
272 public override string ContentType {
273 get { return webHeaders ["Content-Type"]; }
275 if (value == null || value.Trim().Length == 0) {
276 webHeaders.RemoveInternal ("Content-Type");
279 webHeaders.RemoveAndAdd ("Content-Type", value);
283 public HttpContinueDelegate ContinueDelegate {
284 get { return continueDelegate; }
285 set { continueDelegate = value; }
288 public CookieContainer CookieContainer {
289 get { return cookieContainer; }
290 set { cookieContainer = value; }
293 public override ICredentials Credentials {
294 get { return credentials; }
295 set { credentials = value; }
300 public static new RequestCachePolicy DefaultCachePolicy
303 throw GetMustImplement ();
306 throw GetMustImplement ();
311 public static int DefaultMaximumErrorResponseLength
314 throw GetMustImplement ();
317 throw GetMustImplement ();
322 public string Expect {
323 get { return webHeaders ["Expect"]; }
325 CheckRequestStarted ();
328 val = val.Trim ().ToLower ();
330 if (val == null || val.Length == 0) {
331 webHeaders.RemoveInternal ("Expect");
335 if (val == "100-continue")
336 throw new ArgumentException ("100-Continue cannot be set with this property.",
338 webHeaders.RemoveAndAdd ("Expect", value);
342 public bool HaveResponse {
343 get { return haveResponse; }
346 public override WebHeaderCollection Headers {
347 get { return webHeaders; }
349 CheckRequestStarted ();
350 WebHeaderCollection newHeaders = new WebHeaderCollection (true);
351 int count = value.Count;
352 for (int i = 0; i < count; i++)
353 newHeaders.Add (value.GetKey (i), value.Get (i));
355 webHeaders = newHeaders;
359 public DateTime IfModifiedSince {
361 string str = webHeaders ["If-Modified-Since"];
365 return MonoHttpDate.Parse (str);
366 } catch (Exception) {
371 CheckRequestStarted ();
373 webHeaders.SetInternal ("If-Modified-Since",
374 value.ToUniversalTime ().ToString ("r", null));
375 // TODO: check last param when using different locale
379 public bool KeepAlive {
388 public int MaximumAutomaticRedirections {
389 get { return maxAutoRedirect; }
392 throw new ArgumentException ("Must be > 0", "value");
394 maxAutoRedirect = value;
399 [MonoTODO ("Use this")]
400 public int MaximumResponseHeadersLength {
401 get { return maxResponseHeadersLength; }
402 set { maxResponseHeadersLength = value; }
405 [MonoTODO ("Use this")]
406 public static int DefaultMaximumResponseHeadersLength {
407 get { return defaultMaxResponseHeadersLength; }
408 set { defaultMaxResponseHeadersLength = value; }
415 int ReadWriteTimeout {
416 get { return readWriteTimeout; }
419 throw new InvalidOperationException ("The request has already been sent.");
422 throw new ArgumentOutOfRangeException ("value", "Must be >= -1");
424 readWriteTimeout = value;
428 public string MediaType {
429 get { return mediaType; }
435 public override string Method {
436 get { return this.method; }
438 if (value == null || value.Trim () == "")
439 throw new ArgumentException ("not a valid method");
445 public bool Pipelined {
446 get { return pipelined; }
447 set { pipelined = value; }
450 public override bool PreAuthenticate {
451 get { return preAuthenticate; }
452 set { preAuthenticate = value; }
455 public Version ProtocolVersion {
456 get { return version; }
458 if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
459 throw new ArgumentException ("value");
465 public override IWebProxy Proxy {
466 get { return proxy; }
468 CheckRequestStarted ();
471 throw new ArgumentNullException ("value");
475 servicePoint = null; // we may need a new one
479 public string Referer {
480 get { return webHeaders ["Referer"]; }
482 CheckRequestStarted ();
483 if (value == null || value.Trim().Length == 0) {
484 webHeaders.RemoveInternal ("Referer");
487 webHeaders.SetInternal ("Referer", value);
491 public override Uri RequestUri {
492 get { return requestUri; }
495 public bool SendChunked {
496 get { return sendChunked; }
498 CheckRequestStarted ();
503 public ServicePoint ServicePoint {
504 get { return GetServicePoint (); }
507 public override int Timeout {
508 get { return timeout; }
511 throw new ArgumentOutOfRangeException ("value");
517 public string TransferEncoding {
518 get { return webHeaders ["Transfer-Encoding"]; }
520 CheckRequestStarted ();
523 val = val.Trim ().ToLower ();
525 if (val == null || val.Length == 0) {
526 webHeaders.RemoveInternal ("Transfer-Encoding");
530 if (val == "chunked")
531 throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
534 throw new ArgumentException ("SendChunked must be True", "value");
536 webHeaders.RemoveAndAdd ("Transfer-Encoding", value);
542 public override bool UseDefaultCredentials
545 throw GetMustImplement ();
548 throw GetMustImplement ();
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 void CommonChecks (bool putpost)
647 throw new ProtocolViolationException ("Method is null.");
649 if (putpost && ((!keepAlive || (contentLength == -1 && !sendChunked)) && !allowBuffering))
650 throw new ProtocolViolationException ("Content-Length not set");
652 string transferEncoding = TransferEncoding;
653 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
654 throw new ProtocolViolationException ("SendChunked should be true.");
657 public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
660 throw new WebException ("The request was previosly aborted.");
662 bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
663 method == "TRACE" || method == "DELETE");
664 if (method == null || !send)
665 throw new ProtocolViolationException ("Cannot send data when method is: " + method);
671 if (asyncWrite != null) {
672 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
673 "method while a previous call is still in progress.");
676 asyncWrite = new WebAsyncResult (this, callback, state);
677 initialMethod = method;
679 if (writeStream != null) {
680 asyncWrite.SetCompleted (true, writeStream);
681 asyncWrite.DoCallback ();
686 gotRequestStream = true;
687 WebAsyncResult result = asyncWrite;
691 servicePoint = GetServicePoint ();
692 abortHandler = servicePoint.SendRequest (this, connectionGroup);
698 public override Stream EndGetRequestStream (IAsyncResult asyncResult)
700 if (asyncResult == null)
701 throw new ArgumentNullException ("asyncResult");
703 WebAsyncResult result = asyncResult as WebAsyncResult;
705 throw new ArgumentException ("Invalid IAsyncResult");
708 result.WaitUntilComplete ();
710 Exception e = result.Exception;
714 return result.WriteStream;
717 public override Stream GetRequestStream()
719 IAsyncResult asyncResult = asyncWrite;
720 if (asyncResult == null) {
721 asyncResult = BeginGetRequestStream (null, null);
722 asyncWrite = (WebAsyncResult) asyncResult;
725 if (!asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
727 throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
730 return EndGetRequestStream (asyncResult);
733 void CheckIfForceWrite ()
735 if (writeStream == null || contentLength < 0 || !InternalAllowBuffering)
738 // This will write the POST/PUT if the write stream already has the expected
739 // amount of bytes in it (ContentLength) (bug #77753).
740 if (writeStream.WriteBufferLength == contentLength)
741 writeStream.WriteRequest ();
744 public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
746 bool send = (method == "PUT" || method == "POST");
748 if ((!KeepAlive || (ContentLength == -1 && !SendChunked)) && !AllowWriteStreamBuffering)
749 throw new ProtocolViolationException ("Content-Length not set");
753 Monitor.Enter (this);
754 getResponseCalled = true;
755 if (asyncRead != null && !haveResponse) {
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 if (webResponse != null) {
767 Exception saved = saved_exc;
770 aread.SetCompleted (true, webResponse);
772 aread.SetCompleted (true, saved);
782 servicePoint = GetServicePoint ();
783 abortHandler = servicePoint.SendRequest (this, connectionGroup);
790 public override WebResponse EndGetResponse (IAsyncResult asyncResult)
792 if (asyncResult == null)
793 throw new ArgumentNullException ("asyncResult");
795 WebAsyncResult result = asyncResult as WebAsyncResult;
797 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
799 if (!result.WaitUntilComplete (timeout, false)) {
801 throw new WebException("The request timed out", WebExceptionStatus.Timeout);
804 if (result.GotException)
805 throw result.Exception;
807 return result.Response;
810 public override WebResponse GetResponse()
812 WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
813 return EndGetResponse (result);
816 public override void Abort ()
820 if (asyncWrite != null) {
821 WebAsyncResult r = asyncWrite;
822 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
823 r.SetCompleted (false, wexc);
828 if (asyncRead != null) {
829 WebAsyncResult r = asyncRead;
830 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
831 r.SetCompleted (false, wexc);
836 if (abortHandler != null) {
838 abortHandler (this, EventArgs.Empty);
839 } catch (Exception) {}
843 if (writeStream != null) {
845 writeStream.Close ();
850 if (webResponse != null) {
852 webResponse.Close ();
858 void ISerializable.GetObjectData (SerializationInfo serializationInfo,
859 StreamingContext streamingContext)
861 GetObjectData (serializationInfo, streamingContext);
867 void GetObjectData (SerializationInfo serializationInfo,
868 StreamingContext streamingContext)
870 SerializationInfo info = serializationInfo;
872 info.AddValue ("requestUri", requestUri, typeof (Uri));
873 info.AddValue ("actualUri", actualUri, typeof (Uri));
874 info.AddValue ("allowAutoRedirect", allowAutoRedirect);
875 info.AddValue ("allowBuffering", allowBuffering);
876 info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
877 info.AddValue ("connectionGroup", connectionGroup);
878 info.AddValue ("contentLength", contentLength);
879 info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
880 info.AddValue ("keepAlive", keepAlive);
881 info.AddValue ("maxAutoRedirect", maxAutoRedirect);
882 info.AddValue ("mediaType", mediaType);
883 info.AddValue ("method", method);
884 info.AddValue ("initialMethod", initialMethod);
885 info.AddValue ("pipelined", pipelined);
886 info.AddValue ("version", version, typeof (Version));
887 info.AddValue ("proxy", proxy, typeof (IWebProxy));
888 info.AddValue ("sendChunked", sendChunked);
889 info.AddValue ("timeout", timeout);
890 info.AddValue ("redirects", redirects);
893 void CheckRequestStarted ()
896 throw new InvalidOperationException ("request started");
899 internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
901 if (continueDelegate != null)
902 continueDelegate (statusCode, headers);
905 bool Redirect (WebAsyncResult result, HttpStatusCode code)
909 string uriString = null;
912 case HttpStatusCode.Ambiguous: // 300
913 e = new WebException ("Ambiguous redirect.");
915 case HttpStatusCode.MovedPermanently: // 301
916 case HttpStatusCode.Redirect: // 302
917 case HttpStatusCode.TemporaryRedirect: // 307
918 /* MS follows the redirect for POST too
919 if (method != "GET" && method != "HEAD") // 10.3
924 bodyBufferLength = 0;
927 uriString = webResponse.Headers ["Location"];
929 case HttpStatusCode.SeeOther: //303
931 uriString = webResponse.Headers ["Location"];
933 case HttpStatusCode.NotModified: // 304
935 case HttpStatusCode.UseProxy: // 305
936 e = new NotImplementedException ("Proxy support not available.");
938 case HttpStatusCode.Unused: // 306
940 e = new ProtocolViolationException ("Invalid status code: " + (int) code);
947 if (uriString == null)
948 throw new WebException ("No Location header found for " + (int) code,
949 WebExceptionStatus.ProtocolError);
951 Uri prev = actualUri;
953 actualUri = new Uri (actualUri, uriString);
954 } catch (Exception) {
955 throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
956 uriString, (int) code),
957 WebExceptionStatus.ProtocolError);
960 hostChanged = (actualUri.Scheme != prev.Scheme || actualUri.Host != prev.Host ||
961 actualUri.Port != prev.Port);
967 bool continue100 = false;
968 if (contentLength != -1) {
969 if (contentLength > 0)
971 webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
972 webHeaders.RemoveInternal ("Transfer-Encoding");
973 } else if (sendChunked) {
975 webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
976 webHeaders.RemoveInternal ("Content-Length");
979 if (actualVersion == HttpVersion.Version11 && continue100 &&
980 servicePoint.SendContinue) { // RFC2616 8.2.3
981 webHeaders.RemoveAndAdd ("Expect" , "100-continue");
982 expectContinue = true;
984 webHeaders.RemoveInternal ("Expect");
985 expectContinue = false;
988 bool proxy_query = ProxyQuery;
989 string connectionHeader = (proxy_query) ? "Proxy-Connection" : "Connection";
990 webHeaders.RemoveInternal ((!proxy_query) ? "Proxy-Connection" : "Connection");
991 Version proto_version = servicePoint.ProtocolVersion;
992 bool spoint10 = (proto_version == null || proto_version == HttpVersion.Version10);
994 if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
995 webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
996 } else if (!keepAlive && version == HttpVersion.Version11) {
997 webHeaders.RemoveAndAdd (connectionHeader, "close");
1000 webHeaders.SetInternal ("Host", actualUri.Authority);
1001 if (cookieContainer != null) {
1002 string cookieHeader = cookieContainer.GetCookieHeader (actualUri);
1003 if (cookieHeader != "")
1004 webHeaders.SetInternal ("Cookie", cookieHeader);
1007 if (!usedPreAuth && preAuthenticate)
1008 DoPreAuthenticate ();
1010 return webHeaders.ToString ();
1013 void DoPreAuthenticate ()
1015 webHeaders.RemoveInternal ("Proxy-Authorization");
1016 webHeaders.RemoveInternal ("Authorization");
1017 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1018 ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
1019 Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
1023 string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
1024 webHeaders [authHeader] = auth.Message;
1028 internal void SetWriteStreamError (WebExceptionStatus status)
1033 WebAsyncResult r = asyncWrite;
1038 r.SetCompleted (false, new WebException ("Error: " + status, status));
1043 internal void SendRequestHeaders ()
1045 StringBuilder req = new StringBuilder ();
1048 query = actualUri.PathAndQuery;
1049 } else if (actualUri.IsDefaultPort) {
1050 query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
1052 actualUri.PathAndQuery);
1054 query = String.Format ("{0}://{1}:{2}{3}", actualUri.Scheme,
1057 actualUri.PathAndQuery);
1060 if (servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
1061 actualVersion = servicePoint.ProtocolVersion;
1063 actualVersion = version;
1066 req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
1067 actualVersion.Major, actualVersion.Minor);
1068 req.Append (GetHeaders ());
1069 string reqstr = req.ToString ();
1070 byte [] bytes = Encoding.UTF8.GetBytes (reqstr);
1072 writeStream.SetHeaders (bytes, 0, bytes.Length);
1073 } catch (WebException wexc) {
1074 SetWriteStreamError (wexc.Status);
1075 } catch (Exception) {
1076 SetWriteStreamError (WebExceptionStatus.SendFailure);
1080 internal void SetWriteStream (WebConnectionStream stream)
1085 writeStream = stream;
1086 if (bodyBuffer != null) {
1087 webHeaders.RemoveInternal ("Transfer-Encoding");
1088 contentLength = bodyBufferLength;
1089 writeStream.SendChunked = false;
1092 SendRequestHeaders ();
1096 if (bodyBuffer != null) {
1097 // The body has been written and buffered. The request "user"
1098 // won't write it again, so we must do it.
1099 writeStream.Write (bodyBuffer, 0, bodyBufferLength);
1101 writeStream.Close ();
1102 } else if (method == "PUT" || method == "POST" || method == "OPTIONS") {
1103 if (getResponseCalled && !writeStream.RequestWritten)
1104 writeStream.WriteRequest ();
1107 if (asyncWrite != null) {
1108 asyncWrite.SetCompleted (false, stream);
1109 asyncWrite.DoCallback ();
1114 internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
1118 string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
1119 WebAsyncResult r = asyncRead;
1125 if (e is WebException) {
1126 wexc = (WebException) e;
1128 wexc = new WebException (msg, e, status, null);
1130 r.SetCompleted (false, wexc);
1137 void CheckSendError (WebConnectionData data)
1139 // Got here, but no one called GetResponse
1140 int status = data.StatusCode;
1141 if (status < 400 || status == 401 || status == 407)
1144 if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
1145 // The request has not been completely sent and we got here!
1146 // We should probably just close and cause an error in any case,
1147 saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse);
1148 webResponse.ReadAll ();
1152 void HandleNtlmAuth (WebAsyncResult r)
1154 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1156 WebConnection cnc = wce.Connection;
1157 cnc.PriorityRequest = this;
1158 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1159 ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1160 if (creds != null) {
1161 cnc.NtlmCredential = creds.GetCredential (requestUri, "NTLM");
1163 cnc.UnsafeAuthenticatedConnectionSharing = unsafe_auth_blah;
1168 haveResponse = false;
1169 webResponse.ReadAll ();
1173 internal void SetResponseData (WebConnectionData data)
1176 if (data.stream != null)
1177 data.stream.Close ();
1181 WebException wexc = null;
1183 webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
1184 haveResponse = true;
1185 } catch (Exception e) {
1186 wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null);
1187 if (data.stream != null)
1188 data.stream.Close ();
1191 if (wexc == null && (method == "POST" || method == "PUT")) {
1193 CheckSendError (data);
1194 if (saved_exc != null)
1195 wexc = (WebException) saved_exc;
1199 WebAsyncResult r = asyncRead;
1202 r.SetCompleted (false, wexc);
1209 redirected = CheckFinalStatus (r);
1211 if (is_ntlm_auth && authCompleted && webResponse != null
1212 && (int)webResponse.StatusCode < 400) {
1213 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1215 WebConnection cnc = wce.Connection;
1216 cnc.NtlmAuthenticated = true;
1220 // clear internal buffer so that it does not
1221 // hold possible big buffer (bug #397627)
1222 if (writeStream != null)
1223 writeStream.KillBuffer ();
1225 r.SetCompleted (false, webResponse);
1228 if (webResponse != null) {
1233 webResponse.Close ();
1235 haveResponse = false;
1238 servicePoint = GetServicePoint ();
1239 abortHandler = servicePoint.SendRequest (this, connectionGroup);
1241 } catch (WebException wexc2) {
1242 r.SetCompleted (false, wexc2);
1245 } catch (Exception ex) {
1246 wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
1247 r.SetCompleted (false, wexc);
1254 bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1256 authCompleted = false;
1257 if (code == HttpStatusCode.Unauthorized && credentials == null)
1260 bool isProxy = (code == HttpStatusCode.ProxyAuthenticationRequired);
1261 if (isProxy && (proxy == null || proxy.Credentials == null))
1264 string authHeader = response.Headers [(isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate"];
1265 if (authHeader == null)
1268 ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1269 Authorization auth = AuthenticationManager.Authenticate (authHeader, this, creds);
1273 webHeaders [(isProxy) ? "Proxy-Authorization" : "Authorization"] = auth.Message;
1274 authCompleted = auth.Complete;
1275 is_ntlm_auth = (auth.Module.AuthenticationType == "NTLM");
1279 // Returns true if redirected
1280 bool CheckFinalStatus (WebAsyncResult result)
1282 if (result.GotException)
1283 throw result.Exception;
1285 Exception throwMe = result.Exception;
1288 HttpWebResponse resp = result.Response;
1289 WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
1290 HttpStatusCode code = 0;
1291 if (throwMe == null && webResponse != null) {
1292 code = webResponse.StatusCode;
1293 if (!authCompleted && ((code == HttpStatusCode.Unauthorized && credentials != null) ||
1294 (ProxyQuery && code == HttpStatusCode.ProxyAuthenticationRequired))) {
1295 if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
1296 // Keep the written body, so it can be rewritten in the retry
1297 if (InternalAllowBuffering) {
1298 bodyBuffer = writeStream.WriteBuffer;
1299 bodyBufferLength = writeStream.WriteBufferLength;
1301 } else if (method != "PUT" && method != "POST") {
1305 writeStream.InternalClose ();
1307 webResponse.Close ();
1310 throw new WebException ("This request requires buffering " +
1311 "of data for authentication or " +
1312 "redirection to be sucessful.");
1316 if ((int) code >= 400) {
1317 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1318 (int) code, webResponse.StatusDescription);
1319 throwMe = new WebException (err, null, protoError, webResponse);
1320 webResponse.ReadAll ();
1321 } else if ((int) code == 304 && allowAutoRedirect) {
1322 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1323 (int) code, webResponse.StatusDescription);
1324 throwMe = new WebException (err, null, protoError, webResponse);
1325 } else if ((int) code >= 300 && allowAutoRedirect && redirects >= maxAutoRedirect) {
1326 throwMe = new WebException ("Max. redirections exceeded.", null,
1327 protoError, webResponse);
1328 webResponse.ReadAll ();
1332 if (throwMe == null) {
1335 if (allowAutoRedirect && c >= 300) {
1336 if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
1337 bodyBuffer = writeStream.WriteBuffer;
1338 bodyBufferLength = writeStream.WriteBufferLength;
1340 b = Redirect (result, code);
1343 if (resp != null && c >= 300 && c != 304)
1349 if (writeStream != null) {
1350 writeStream.InternalClose ();