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);
541 public override bool UseDefaultCredentials
543 get { return CredentialCache.DefaultCredentials == Credentials; }
544 set { Credentials = value ? CredentialCache.DefaultCredentials : null; }
548 public string UserAgent {
549 get { return webHeaders ["User-Agent"]; }
550 set { webHeaders.SetInternal ("User-Agent", value); }
554 bool unsafe_auth_blah;
555 public bool UnsafeAuthenticatedConnectionSharing
557 get { return unsafe_auth_blah; }
558 set { unsafe_auth_blah = value; }
562 internal bool GotRequestStream {
563 get { return gotRequestStream; }
566 internal bool ExpectContinue {
567 get { return expectContinue; }
568 set { expectContinue = value; }
571 internal Uri AuthUri {
572 get { return actualUri; }
575 internal bool ProxyQuery {
576 get { return servicePoint.UsesProxy && !servicePoint.UseConnect; }
581 internal ServicePoint GetServicePoint ()
584 if (hostChanged || servicePoint == null) {
585 servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
593 public void AddRange (int range)
595 AddRange ("bytes", range);
598 public void AddRange (int from, int to)
600 AddRange ("bytes", from, to);
603 public void AddRange (string rangeSpecifier, int range)
605 if (rangeSpecifier == null)
606 throw new ArgumentNullException ("rangeSpecifier");
607 string value = webHeaders ["Range"];
608 if (value == null || value.Length == 0)
609 value = rangeSpecifier + "=";
610 else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
613 throw new InvalidOperationException ("rangeSpecifier");
614 webHeaders.RemoveAndAdd ("Range", value + range + "-");
617 public void AddRange (string rangeSpecifier, int from, int to)
619 if (rangeSpecifier == null)
620 throw new ArgumentNullException ("rangeSpecifier");
621 if (from < 0 || to < 0 || from > to)
622 throw new ArgumentOutOfRangeException ();
623 string value = webHeaders ["Range"];
624 if (value == null || value.Length == 0)
625 value = rangeSpecifier + "=";
626 else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
629 throw new InvalidOperationException ("rangeSpecifier");
630 webHeaders.RemoveAndAdd ("Range", value + from + "-" + to);
633 public override int GetHashCode ()
635 return base.GetHashCode ();
639 void CommonChecks (bool putpost)
642 throw new ProtocolViolationException ("Method is null.");
644 if (putpost && contentLength == -1 && !sendChunked && !allowBuffering)
645 throw new ProtocolViolationException ("Content-Length not set");
647 string transferEncoding = TransferEncoding;
648 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
649 throw new ProtocolViolationException ("SendChunked should be true.");
652 public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
655 throw new WebException ("The request was previosly aborted.");
657 bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
658 method == "TRACE" || method == "DELETE");
659 if (method == null || !send)
660 throw new ProtocolViolationException ("Cannot send data when method is: " + method);
666 if (asyncWrite != null) {
667 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
668 "method while a previous call is still in progress.");
671 asyncWrite = new WebAsyncResult (this, callback, state);
672 initialMethod = method;
674 if (writeStream != null) {
675 asyncWrite.SetCompleted (true, writeStream);
676 asyncWrite.DoCallback ();
681 gotRequestStream = true;
682 WebAsyncResult result = asyncWrite;
686 servicePoint = GetServicePoint ();
687 abortHandler = servicePoint.SendRequest (this, connectionGroup);
693 public override Stream EndGetRequestStream (IAsyncResult asyncResult)
695 if (asyncResult == null)
696 throw new ArgumentNullException ("asyncResult");
698 WebAsyncResult result = asyncResult as WebAsyncResult;
700 throw new ArgumentException ("Invalid IAsyncResult");
703 result.WaitUntilComplete ();
705 Exception e = result.Exception;
709 return result.WriteStream;
712 public override Stream GetRequestStream()
714 IAsyncResult asyncResult = asyncWrite;
715 if (asyncResult == null) {
716 asyncResult = BeginGetRequestStream (null, null);
717 asyncWrite = (WebAsyncResult) asyncResult;
720 if (!asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
722 throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
725 return EndGetRequestStream (asyncResult);
728 void CheckIfForceWrite ()
730 if (writeStream == null || writeStream.RequestWritten|| contentLength < 0 || !InternalAllowBuffering)
733 // This will write the POST/PUT if the write stream already has the expected
734 // amount of bytes in it (ContentLength) (bug #77753).
735 if (writeStream.WriteBufferLength == contentLength)
736 writeStream.WriteRequest ();
739 public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
741 bool send = (method == "PUT" || method == "POST");
743 if ((!KeepAlive || (ContentLength == -1 && !SendChunked)) && !AllowWriteStreamBuffering)
744 throw new ProtocolViolationException ("Content-Length not set");
748 Monitor.Enter (locker);
749 getResponseCalled = true;
750 if (asyncRead != null && !haveResponse) {
751 Monitor.Exit (locker);
752 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
753 "method while a previous call is still in progress.");
756 CheckIfForceWrite ();
757 asyncRead = new WebAsyncResult (this, callback, state);
758 WebAsyncResult aread = asyncRead;
759 initialMethod = method;
761 if (webResponse != null) {
762 Exception saved = saved_exc;
763 Monitor.Exit (locker);
765 aread.SetCompleted (true, webResponse);
767 aread.SetCompleted (true, saved);
771 } else if (saved_exc != null) {
772 aread.SetCompleted (true, saved_exc);
781 servicePoint = GetServicePoint ();
782 abortHandler = servicePoint.SendRequest (this, connectionGroup);
785 Monitor.Exit (locker);
789 public override WebResponse EndGetResponse (IAsyncResult asyncResult)
791 if (asyncResult == null)
792 throw new ArgumentNullException ("asyncResult");
794 WebAsyncResult result = asyncResult as WebAsyncResult;
796 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
798 if (!result.WaitUntilComplete (timeout, false)) {
800 throw new WebException("The request timed out", WebExceptionStatus.Timeout);
803 if (result.GotException)
804 throw result.Exception;
806 return result.Response;
809 public override WebResponse GetResponse()
811 WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
812 return EndGetResponse (result);
815 public override void Abort ()
819 if (asyncWrite != null) {
820 WebAsyncResult r = asyncWrite;
821 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
822 r.SetCompleted (false, wexc);
827 if (asyncRead != null) {
828 WebAsyncResult r = asyncRead;
829 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
830 r.SetCompleted (false, wexc);
835 if (abortHandler != null) {
837 abortHandler (this, EventArgs.Empty);
838 } catch (Exception) {}
842 if (writeStream != null) {
844 writeStream.Close ();
849 if (webResponse != null) {
851 webResponse.Close ();
857 void ISerializable.GetObjectData (SerializationInfo serializationInfo,
858 StreamingContext streamingContext)
860 GetObjectData (serializationInfo, streamingContext);
866 void GetObjectData (SerializationInfo serializationInfo,
867 StreamingContext streamingContext)
869 SerializationInfo info = serializationInfo;
871 info.AddValue ("requestUri", requestUri, typeof (Uri));
872 info.AddValue ("actualUri", actualUri, typeof (Uri));
873 info.AddValue ("allowAutoRedirect", allowAutoRedirect);
874 info.AddValue ("allowBuffering", allowBuffering);
875 info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
876 info.AddValue ("connectionGroup", connectionGroup);
877 info.AddValue ("contentLength", contentLength);
878 info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
879 info.AddValue ("keepAlive", keepAlive);
880 info.AddValue ("maxAutoRedirect", maxAutoRedirect);
881 info.AddValue ("mediaType", mediaType);
882 info.AddValue ("method", method);
883 info.AddValue ("initialMethod", initialMethod);
884 info.AddValue ("pipelined", pipelined);
885 info.AddValue ("version", version, typeof (Version));
886 info.AddValue ("proxy", proxy, typeof (IWebProxy));
887 info.AddValue ("sendChunked", sendChunked);
888 info.AddValue ("timeout", timeout);
889 info.AddValue ("redirects", redirects);
892 void CheckRequestStarted ()
895 throw new InvalidOperationException ("request started");
898 internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
900 if (continueDelegate != null)
901 continueDelegate (statusCode, headers);
904 bool Redirect (WebAsyncResult result, HttpStatusCode code)
908 string uriString = null;
911 case HttpStatusCode.Ambiguous: // 300
912 e = new WebException ("Ambiguous redirect.");
914 case HttpStatusCode.MovedPermanently: // 301
915 case HttpStatusCode.Redirect: // 302
916 case HttpStatusCode.TemporaryRedirect: // 307
917 /* MS follows the redirect for POST too
918 if (method != "GET" && method != "HEAD") // 10.3
923 bodyBufferLength = 0;
926 uriString = webResponse.Headers ["Location"];
928 case HttpStatusCode.SeeOther: //303
930 uriString = webResponse.Headers ["Location"];
932 case HttpStatusCode.NotModified: // 304
934 case HttpStatusCode.UseProxy: // 305
935 e = new NotImplementedException ("Proxy support not available.");
937 case HttpStatusCode.Unused: // 306
939 e = new ProtocolViolationException ("Invalid status code: " + (int) code);
946 if (uriString == null)
947 throw new WebException ("No Location header found for " + (int) code,
948 WebExceptionStatus.ProtocolError);
950 Uri prev = actualUri;
952 actualUri = new Uri (actualUri, uriString);
953 } catch (Exception) {
954 throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
955 uriString, (int) code),
956 WebExceptionStatus.ProtocolError);
959 hostChanged = (actualUri.Scheme != prev.Scheme || actualUri.Host != prev.Host ||
960 actualUri.Port != prev.Port);
966 bool continue100 = false;
967 if (contentLength != -1) {
968 if (contentLength > 0)
970 webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
971 webHeaders.RemoveInternal ("Transfer-Encoding");
972 } else if (sendChunked) {
974 webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
975 webHeaders.RemoveInternal ("Content-Length");
978 if (actualVersion == HttpVersion.Version11 && continue100 &&
979 servicePoint.SendContinue) { // RFC2616 8.2.3
980 webHeaders.RemoveAndAdd ("Expect" , "100-continue");
981 expectContinue = true;
983 webHeaders.RemoveInternal ("Expect");
984 expectContinue = false;
987 bool proxy_query = ProxyQuery;
988 string connectionHeader = (proxy_query) ? "Proxy-Connection" : "Connection";
989 webHeaders.RemoveInternal ((!proxy_query) ? "Proxy-Connection" : "Connection");
990 Version proto_version = servicePoint.ProtocolVersion;
991 bool spoint10 = (proto_version == null || proto_version == HttpVersion.Version10);
993 if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
994 webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
995 } else if (!keepAlive && version == HttpVersion.Version11) {
996 webHeaders.RemoveAndAdd (connectionHeader, "close");
999 webHeaders.SetInternal ("Host", actualUri.Authority);
1000 if (cookieContainer != null) {
1001 string cookieHeader = cookieContainer.GetCookieHeader (actualUri);
1002 if (cookieHeader != "")
1003 webHeaders.SetInternal ("Cookie", cookieHeader);
1006 if (!usedPreAuth && preAuthenticate)
1007 DoPreAuthenticate ();
1009 return webHeaders.ToString ();
1012 void DoPreAuthenticate ()
1014 webHeaders.RemoveInternal ("Proxy-Authorization");
1015 webHeaders.RemoveInternal ("Authorization");
1016 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1017 ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
1018 Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
1022 string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
1023 webHeaders [authHeader] = auth.Message;
1027 internal void SetWriteStreamError (WebExceptionStatus status)
1032 WebAsyncResult r = asyncWrite;
1037 r.SetCompleted (false, new WebException ("Error: " + status, status));
1042 internal void SendRequestHeaders ()
1044 StringBuilder req = new StringBuilder ();
1047 query = actualUri.PathAndQuery;
1048 } else if (actualUri.IsDefaultPort) {
1049 query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
1051 actualUri.PathAndQuery);
1053 query = String.Format ("{0}://{1}:{2}{3}", actualUri.Scheme,
1056 actualUri.PathAndQuery);
1059 if (servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
1060 actualVersion = servicePoint.ProtocolVersion;
1062 actualVersion = version;
1065 req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
1066 actualVersion.Major, actualVersion.Minor);
1067 req.Append (GetHeaders ());
1068 string reqstr = req.ToString ();
1069 byte [] bytes = Encoding.UTF8.GetBytes (reqstr);
1071 writeStream.SetHeaders (bytes, 0, bytes.Length);
1072 } catch (WebException wexc) {
1073 SetWriteStreamError (wexc.Status);
1074 } catch (Exception) {
1075 SetWriteStreamError (WebExceptionStatus.SendFailure);
1079 internal void SetWriteStream (WebConnectionStream stream)
1084 writeStream = stream;
1085 if (bodyBuffer != null) {
1086 webHeaders.RemoveInternal ("Transfer-Encoding");
1087 contentLength = bodyBufferLength;
1088 writeStream.SendChunked = false;
1091 SendRequestHeaders ();
1095 if (bodyBuffer != null) {
1096 // The body has been written and buffered. The request "user"
1097 // won't write it again, so we must do it.
1098 writeStream.Write (bodyBuffer, 0, bodyBufferLength);
1100 writeStream.Close ();
1101 } else if (method == "PUT" || method == "POST" || method == "OPTIONS") {
1102 if (getResponseCalled && !writeStream.RequestWritten)
1103 writeStream.WriteRequest ();
1106 if (asyncWrite != null) {
1107 asyncWrite.SetCompleted (false, stream);
1108 asyncWrite.DoCallback ();
1113 internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
1117 string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
1118 WebAsyncResult r = asyncRead;
1124 if (e is WebException) {
1125 wexc = (WebException) e;
1127 wexc = new WebException (msg, e, status, null);
1129 r.SetCompleted (false, wexc);
1136 void CheckSendError (WebConnectionData data)
1138 // Got here, but no one called GetResponse
1139 int status = data.StatusCode;
1140 if (status < 400 || status == 401 || status == 407)
1143 if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
1144 // The request has not been completely sent and we got here!
1145 // We should probably just close and cause an error in any case,
1146 saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse);
1147 webResponse.ReadAll ();
1151 void HandleNtlmAuth (WebAsyncResult r)
1153 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1155 WebConnection cnc = wce.Connection;
1156 cnc.PriorityRequest = this;
1157 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1158 ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1159 if (creds != null) {
1160 cnc.NtlmCredential = creds.GetCredential (requestUri, "NTLM");
1162 cnc.UnsafeAuthenticatedConnectionSharing = unsafe_auth_blah;
1167 haveResponse = false;
1168 webResponse.ReadAll ();
1172 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 } catch (Exception e) {
1185 wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null);
1186 if (data.stream != null)
1187 data.stream.Close ();
1190 if (wexc == null && (method == "POST" || method == "PUT")) {
1192 CheckSendError (data);
1193 if (saved_exc != null)
1194 wexc = (WebException) saved_exc;
1198 WebAsyncResult r = asyncRead;
1200 bool forced = false;
1201 if (r == null && webResponse != null) {
1202 // This is a forced completion (302, 204)...
1204 r = new WebAsyncResult (null, null);
1205 r.SetCompleted (false, webResponse);
1210 r.SetCompleted (false, wexc);
1217 redirected = CheckFinalStatus (r);
1219 if (is_ntlm_auth && authCompleted && webResponse != null
1220 && (int)webResponse.StatusCode < 400) {
1221 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1223 WebConnection cnc = wce.Connection;
1224 cnc.NtlmAuthenticated = true;
1228 // clear internal buffer so that it does not
1229 // hold possible big buffer (bug #397627)
1230 if (writeStream != null)
1231 writeStream.KillBuffer ();
1233 haveResponse = true;
1234 r.SetCompleted (false, webResponse);
1237 if (webResponse != null) {
1242 webResponse.Close ();
1244 haveResponse = false;
1247 servicePoint = GetServicePoint ();
1248 abortHandler = servicePoint.SendRequest (this, connectionGroup);
1250 } catch (WebException wexc2) {
1253 haveResponse = true;
1255 r.SetCompleted (false, wexc2);
1258 } catch (Exception ex) {
1259 wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
1262 haveResponse = true;
1264 r.SetCompleted (false, wexc);
1272 bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1274 authCompleted = false;
1275 if (code == HttpStatusCode.Unauthorized && credentials == null)
1278 bool isProxy = (code == HttpStatusCode.ProxyAuthenticationRequired);
1279 if (isProxy && (proxy == null || proxy.Credentials == null))
1282 string authHeader = response.Headers [(isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate"];
1283 if (authHeader == null)
1286 ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1287 Authorization auth = AuthenticationManager.Authenticate (authHeader, this, creds);
1291 webHeaders [(isProxy) ? "Proxy-Authorization" : "Authorization"] = auth.Message;
1292 authCompleted = auth.Complete;
1293 is_ntlm_auth = (auth.Module.AuthenticationType == "NTLM");
1297 // Returns true if redirected
1298 bool CheckFinalStatus (WebAsyncResult result)
1300 if (result.GotException)
1301 throw result.Exception;
1303 Exception throwMe = result.Exception;
1306 HttpWebResponse resp = result.Response;
1307 WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
1308 HttpStatusCode code = 0;
1309 if (throwMe == null && webResponse != null) {
1310 code = webResponse.StatusCode;
1311 if (!authCompleted && ((code == HttpStatusCode.Unauthorized && credentials != null) ||
1312 (ProxyQuery && code == HttpStatusCode.ProxyAuthenticationRequired))) {
1313 if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
1314 // Keep the written body, so it can be rewritten in the retry
1315 if (InternalAllowBuffering) {
1316 bodyBuffer = writeStream.WriteBuffer;
1317 bodyBufferLength = writeStream.WriteBufferLength;
1319 } else if (method != "PUT" && method != "POST") {
1323 writeStream.InternalClose ();
1325 webResponse.Close ();
1328 throw new WebException ("This request requires buffering " +
1329 "of data for authentication or " +
1330 "redirection to be sucessful.");
1334 if ((int) code >= 400) {
1335 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1336 (int) code, webResponse.StatusDescription);
1337 throwMe = new WebException (err, null, protoError, webResponse);
1338 webResponse.ReadAll ();
1339 } else if ((int) code == 304 && allowAutoRedirect) {
1340 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1341 (int) code, webResponse.StatusDescription);
1342 throwMe = new WebException (err, null, protoError, webResponse);
1343 } else if ((int) code >= 300 && allowAutoRedirect && redirects >= maxAutoRedirect) {
1344 throwMe = new WebException ("Max. redirections exceeded.", null,
1345 protoError, webResponse);
1346 webResponse.ReadAll ();
1350 if (throwMe == null) {
1353 if (allowAutoRedirect && c >= 300) {
1354 if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
1355 bodyBuffer = writeStream.WriteBuffer;
1356 bodyBufferLength = writeStream.WriteBufferLength;
1358 b = Redirect (result, code);
1361 if (resp != null && c >= 300 && c != 304)
1367 if (writeStream != null) {
1368 writeStream.InternalClose ();