HttpWebRequest.cs 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196
  1. //
  2. // System.Net.HttpWebRequest
  3. //
  4. // Authors:
  5. // Lawrence Pit ([email protected])
  6. // Gonzalo Paniagua Javier ([email protected])
  7. //
  8. // (c) 2002 Lawrence Pit
  9. // (c) 2003 Ximian, Inc. (http://www.ximian.com)
  10. // (c) 2004 Novell, Inc. (http://www.novell.com)
  11. //
  12. //
  13. // Permission is hereby granted, free of charge, to any person obtaining
  14. // a copy of this software and associated documentation files (the
  15. // "Software"), to deal in the Software without restriction, including
  16. // without limitation the rights to use, copy, modify, merge, publish,
  17. // distribute, sublicense, and/or sell copies of the Software, and to
  18. // permit persons to whom the Software is furnished to do so, subject to
  19. // the following conditions:
  20. //
  21. // The above copyright notice and this permission notice shall be
  22. // included in all copies or substantial portions of the Software.
  23. //
  24. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  25. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  27. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  28. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  29. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  30. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  31. //
  32. using System;
  33. using System.Collections;
  34. using System.Configuration;
  35. using System.IO;
  36. using System.Net.Sockets;
  37. using System.Runtime.Remoting.Messaging;
  38. using System.Runtime.Serialization;
  39. using System.Security.Cryptography.X509Certificates;
  40. using System.Text;
  41. using System.Threading;
  42. namespace System.Net
  43. {
  44. [Serializable]
  45. public class HttpWebRequest : WebRequest, ISerializable
  46. {
  47. Uri requestUri;
  48. Uri actualUri;
  49. bool hostChanged;
  50. bool allowAutoRedirect = true;
  51. bool allowBuffering = true;
  52. X509CertificateCollection certificates;
  53. string connectionGroup;
  54. long contentLength = -1;
  55. HttpContinueDelegate continueDelegate;
  56. CookieContainer cookieContainer;
  57. ICredentials credentials;
  58. bool haveResponse;
  59. bool haveRequest;
  60. bool requestSent;
  61. WebHeaderCollection webHeaders = new WebHeaderCollection (true);
  62. bool keepAlive = true;
  63. int maxAutoRedirect = 50;
  64. string mediaType = String.Empty;
  65. string method = "GET";
  66. string initialMethod = "GET";
  67. bool pipelined = true;
  68. bool preAuthenticate;
  69. bool usedPreAuth;
  70. Version version = HttpVersion.Version11;
  71. Version actualVersion;
  72. IWebProxy proxy;
  73. bool sendChunked;
  74. ServicePoint servicePoint;
  75. int timeout = 100000;
  76. WebConnectionStream writeStream;
  77. HttpWebResponse webResponse;
  78. WebAsyncResult asyncWrite;
  79. WebAsyncResult asyncRead;
  80. EventHandler abortHandler;
  81. bool aborted;
  82. bool gotRequestStream;
  83. int redirects;
  84. bool expectContinue;
  85. bool authCompleted;
  86. byte[] bodyBuffer;
  87. int bodyBufferLength;
  88. bool getResponseCalled;
  89. Exception saved_exc;
  90. object locker = new object ();
  91. #if NET_1_1
  92. int maxResponseHeadersLength;
  93. static int defaultMaxResponseHeadersLength;
  94. int readWriteTimeout = 300000; // ms
  95. // Constructors
  96. static HttpWebRequest ()
  97. {
  98. NetConfig config = ConfigurationSettings.GetConfig ("system.net/settings") as NetConfig;
  99. defaultMaxResponseHeadersLength = 64 * 1024;
  100. if (config != null) {
  101. int x = config.MaxResponseHeadersLength;
  102. if (x != -1)
  103. x *= 64;
  104. defaultMaxResponseHeadersLength = x;
  105. }
  106. }
  107. #endif
  108. internal HttpWebRequest (Uri uri)
  109. {
  110. this.requestUri = uri;
  111. this.actualUri = uri;
  112. this.proxy = GlobalProxySelection.Select;
  113. }
  114. protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
  115. {
  116. SerializationInfo info = serializationInfo;
  117. requestUri = (Uri) info.GetValue ("requestUri", typeof (Uri));
  118. actualUri = (Uri) info.GetValue ("actualUri", typeof (Uri));
  119. allowAutoRedirect = info.GetBoolean ("allowAutoRedirect");
  120. allowBuffering = info.GetBoolean ("allowBuffering");
  121. certificates = (X509CertificateCollection) info.GetValue ("certificates", typeof (X509CertificateCollection));
  122. connectionGroup = info.GetString ("connectionGroup");
  123. contentLength = info.GetInt64 ("contentLength");
  124. webHeaders = (WebHeaderCollection) info.GetValue ("webHeaders", typeof (WebHeaderCollection));
  125. keepAlive = info.GetBoolean ("keepAlive");
  126. maxAutoRedirect = info.GetInt32 ("maxAutoRedirect");
  127. mediaType = info.GetString ("mediaType");
  128. method = info.GetString ("method");
  129. initialMethod = info.GetString ("initialMethod");
  130. pipelined = info.GetBoolean ("pipelined");
  131. version = (Version) info.GetValue ("version", typeof (Version));
  132. proxy = (IWebProxy) info.GetValue ("proxy", typeof (IWebProxy));
  133. sendChunked = info.GetBoolean ("sendChunked");
  134. timeout = info.GetInt32 ("timeout");
  135. redirects = info.GetInt32 ("redirects");
  136. }
  137. // Properties
  138. public string Accept {
  139. get { return webHeaders ["Accept"]; }
  140. set {
  141. CheckRequestStarted ();
  142. webHeaders.RemoveAndAdd ("Accept", value);
  143. }
  144. }
  145. public Uri Address {
  146. get { return actualUri; }
  147. }
  148. public bool AllowAutoRedirect {
  149. get { return allowAutoRedirect; }
  150. set { this.allowAutoRedirect = value; }
  151. }
  152. public bool AllowWriteStreamBuffering {
  153. get { return allowBuffering; }
  154. set { allowBuffering = value; }
  155. }
  156. internal bool InternalAllowBuffering {
  157. get {
  158. return (allowBuffering && (method == "PUT" || method == "POST"));
  159. }
  160. }
  161. public X509CertificateCollection ClientCertificates {
  162. get {
  163. if (certificates == null)
  164. certificates = new X509CertificateCollection ();
  165. return certificates;
  166. }
  167. }
  168. public string Connection {
  169. get { return webHeaders ["Connection"]; }
  170. set {
  171. CheckRequestStarted ();
  172. string val = value;
  173. if (val != null)
  174. val = val.Trim ().ToLower ();
  175. if (val == null || val.Length == 0) {
  176. webHeaders.RemoveInternal ("Connection");
  177. return;
  178. }
  179. if (val == "keep-alive" || val == "close")
  180. throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
  181. if (keepAlive && val.IndexOf ("keep-alive") == -1)
  182. value = value + ", Keep-Alive";
  183. webHeaders.RemoveAndAdd ("Connection", value);
  184. }
  185. }
  186. public override string ConnectionGroupName {
  187. get { return connectionGroup; }
  188. set { connectionGroup = value; }
  189. }
  190. public override long ContentLength {
  191. get { return contentLength; }
  192. set {
  193. CheckRequestStarted ();
  194. if (value < 0)
  195. throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
  196. contentLength = value;
  197. }
  198. }
  199. internal long InternalContentLength {
  200. set { contentLength = value; }
  201. }
  202. public override string ContentType {
  203. get { return webHeaders ["Content-Type"]; }
  204. set {
  205. if (value == null || value.Trim().Length == 0) {
  206. webHeaders.RemoveInternal ("Content-Type");
  207. return;
  208. }
  209. webHeaders.RemoveAndAdd ("Content-Type", value);
  210. }
  211. }
  212. public HttpContinueDelegate ContinueDelegate {
  213. get { return continueDelegate; }
  214. set { continueDelegate = value; }
  215. }
  216. public CookieContainer CookieContainer {
  217. get { return cookieContainer; }
  218. set { cookieContainer = value; }
  219. }
  220. public override ICredentials Credentials {
  221. get { return credentials; }
  222. set { credentials = value; }
  223. }
  224. public string Expect {
  225. get { return webHeaders ["Expect"]; }
  226. set {
  227. CheckRequestStarted ();
  228. string val = value;
  229. if (val != null)
  230. val = val.Trim ().ToLower ();
  231. if (val == null || val.Length == 0) {
  232. webHeaders.RemoveInternal ("Expect");
  233. return;
  234. }
  235. if (val == "100-continue")
  236. throw new ArgumentException ("100-Continue cannot be set with this property.",
  237. "value");
  238. webHeaders.RemoveAndAdd ("Expect", value);
  239. }
  240. }
  241. public bool HaveResponse {
  242. get { return haveResponse; }
  243. }
  244. public override WebHeaderCollection Headers {
  245. get { return webHeaders; }
  246. set {
  247. CheckRequestStarted ();
  248. WebHeaderCollection newHeaders = new WebHeaderCollection (true);
  249. int count = value.Count;
  250. for (int i = 0; i < count; i++)
  251. newHeaders.Add (value.GetKey (i), value.Get (i));
  252. webHeaders = newHeaders;
  253. }
  254. }
  255. public DateTime IfModifiedSince {
  256. get {
  257. string str = webHeaders ["If-Modified-Since"];
  258. if (str == null)
  259. return DateTime.Now;
  260. try {
  261. return MonoHttpDate.Parse (str);
  262. } catch (Exception) {
  263. return DateTime.Now;
  264. }
  265. }
  266. set {
  267. CheckRequestStarted ();
  268. // rfc-1123 pattern
  269. webHeaders.SetInternal ("If-Modified-Since",
  270. value.ToUniversalTime ().ToString ("r", null));
  271. // TODO: check last param when using different locale
  272. }
  273. }
  274. public bool KeepAlive {
  275. get {
  276. return keepAlive;
  277. }
  278. set {
  279. keepAlive = value;
  280. }
  281. }
  282. public int MaximumAutomaticRedirections {
  283. get { return maxAutoRedirect; }
  284. set {
  285. if (value <= 0)
  286. throw new ArgumentException ("Must be > 0", "value");
  287. maxAutoRedirect = value;
  288. }
  289. }
  290. #if NET_1_1
  291. [MonoTODO ("Use this")]
  292. public int MaximumResponseHeadersLength {
  293. get { return maxResponseHeadersLength; }
  294. set { maxResponseHeadersLength = value; }
  295. }
  296. [MonoTODO ("Use this")]
  297. public static int DefaultMaximumResponseHeadersLength {
  298. get { return defaultMaxResponseHeadersLength; }
  299. set { defaultMaxResponseHeadersLength = value; }
  300. }
  301. public
  302. #else
  303. internal
  304. #endif
  305. int ReadWriteTimeout {
  306. get { return readWriteTimeout; }
  307. set {
  308. if (requestSent)
  309. throw new InvalidOperationException ("The request has already been sent.");
  310. if (value < -1)
  311. throw new ArgumentOutOfRangeException ("value", "Must be >= -1");
  312. readWriteTimeout = value;
  313. }
  314. }
  315. public string MediaType {
  316. get { return mediaType; }
  317. set {
  318. mediaType = value;
  319. }
  320. }
  321. public override string Method {
  322. get { return this.method; }
  323. set {
  324. if (value == null || value.Trim () == "")
  325. throw new ArgumentException ("not a valid method");
  326. method = value;
  327. }
  328. }
  329. public bool Pipelined {
  330. get { return pipelined; }
  331. set { pipelined = value; }
  332. }
  333. public override bool PreAuthenticate {
  334. get { return preAuthenticate; }
  335. set { preAuthenticate = value; }
  336. }
  337. public Version ProtocolVersion {
  338. get { return version; }
  339. set {
  340. if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
  341. throw new ArgumentException ("value");
  342. version = value;
  343. }
  344. }
  345. public override IWebProxy Proxy {
  346. get { return proxy; }
  347. set {
  348. CheckRequestStarted ();
  349. if (value == null)
  350. throw new ArgumentNullException ("value");
  351. proxy = value;
  352. servicePoint = null; // we may need a new one
  353. }
  354. }
  355. public string Referer {
  356. get { return webHeaders ["Referer"]; }
  357. set {
  358. CheckRequestStarted ();
  359. if (value == null || value.Trim().Length == 0) {
  360. webHeaders.RemoveInternal ("Referer");
  361. return;
  362. }
  363. webHeaders.SetInternal ("Referer", value);
  364. }
  365. }
  366. public override Uri RequestUri {
  367. get { return requestUri; }
  368. }
  369. public bool SendChunked {
  370. get { return sendChunked; }
  371. set {
  372. CheckRequestStarted ();
  373. sendChunked = value;
  374. }
  375. }
  376. public ServicePoint ServicePoint {
  377. get { return GetServicePoint (); }
  378. }
  379. public override int Timeout {
  380. get { return timeout; }
  381. set {
  382. if (value < -1)
  383. throw new ArgumentOutOfRangeException ("value");
  384. timeout = value;
  385. }
  386. }
  387. public string TransferEncoding {
  388. get { return webHeaders ["Transfer-Encoding"]; }
  389. set {
  390. CheckRequestStarted ();
  391. string val = value;
  392. if (val != null)
  393. val = val.Trim ().ToLower ();
  394. if (val == null || val.Length == 0) {
  395. webHeaders.RemoveInternal ("Transfer-Encoding");
  396. return;
  397. }
  398. if (val == "chunked")
  399. throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
  400. if (!sendChunked)
  401. throw new ArgumentException ("SendChunked must be True", "value");
  402. webHeaders.RemoveAndAdd ("Transfer-Encoding", value);
  403. }
  404. }
  405. public string UserAgent {
  406. get { return webHeaders ["User-Agent"]; }
  407. set { webHeaders.SetInternal ("User-Agent", value); }
  408. }
  409. #if NET_1_1
  410. [MonoTODO]
  411. public bool UnsafeAuthenticatedConnectionSharing
  412. {
  413. get { throw new NotImplementedException (); }
  414. set { throw new NotImplementedException (); }
  415. }
  416. #endif
  417. internal bool GotRequestStream {
  418. get { return gotRequestStream; }
  419. }
  420. internal bool ExpectContinue {
  421. get { return expectContinue; }
  422. set { expectContinue = value; }
  423. }
  424. internal Uri AuthUri {
  425. get { return actualUri; }
  426. }
  427. internal bool ProxyQuery {
  428. get { return servicePoint.UsesProxy && !servicePoint.UseConnect; }
  429. }
  430. // Methods
  431. internal ServicePoint GetServicePoint ()
  432. {
  433. lock (locker) {
  434. if (hostChanged || servicePoint == null) {
  435. servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
  436. hostChanged = false;
  437. }
  438. }
  439. return servicePoint;
  440. }
  441. public void AddRange (int range)
  442. {
  443. AddRange ("bytes", range);
  444. }
  445. public void AddRange (int from, int to)
  446. {
  447. AddRange ("bytes", from, to);
  448. }
  449. public void AddRange (string rangeSpecifier, int range)
  450. {
  451. if (rangeSpecifier == null)
  452. throw new ArgumentNullException ("rangeSpecifier");
  453. string value = webHeaders ["Range"];
  454. if (value == null || value.Length == 0)
  455. value = rangeSpecifier + "=";
  456. else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
  457. value += ",";
  458. else
  459. throw new InvalidOperationException ("rangeSpecifier");
  460. webHeaders.RemoveAndAdd ("Range", value + range + "-");
  461. }
  462. public void AddRange (string rangeSpecifier, int from, int to)
  463. {
  464. if (rangeSpecifier == null)
  465. throw new ArgumentNullException ("rangeSpecifier");
  466. if (from < 0 || to < 0 || from > to)
  467. throw new ArgumentOutOfRangeException ();
  468. string value = webHeaders ["Range"];
  469. if (value == null || value.Length == 0)
  470. value = rangeSpecifier + "=";
  471. else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
  472. value += ",";
  473. else
  474. throw new InvalidOperationException ("rangeSpecifier");
  475. webHeaders.RemoveAndAdd ("Range", value + from + "-" + to);
  476. }
  477. #if !NET_2_0
  478. public override int GetHashCode ()
  479. {
  480. return base.GetHashCode ();
  481. }
  482. #endif
  483. void CommonChecks (bool putpost)
  484. {
  485. if (method == null)
  486. throw new ProtocolViolationException ("Method is null.");
  487. if (putpost && ((!keepAlive || (contentLength == -1 && !sendChunked)) && !allowBuffering))
  488. throw new ProtocolViolationException ("Content-Length not set");
  489. string transferEncoding = TransferEncoding;
  490. if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
  491. throw new ProtocolViolationException ("SendChunked should be true.");
  492. }
  493. public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
  494. {
  495. if (aborted)
  496. throw new WebException ("The request was previosly aborted.");
  497. bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD");
  498. if (method == null || !send)
  499. throw new ProtocolViolationException ("Cannot send data when method is: " + method);
  500. CommonChecks (send);
  501. lock (locker)
  502. {
  503. if (asyncWrite != null) {
  504. throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
  505. "method while a previous call is still in progress.");
  506. }
  507. asyncWrite = new WebAsyncResult (this, callback, state);
  508. initialMethod = method;
  509. if (haveRequest) {
  510. if (writeStream != null) {
  511. asyncWrite.SetCompleted (true, writeStream);
  512. asyncWrite.DoCallback ();
  513. return asyncWrite;
  514. }
  515. }
  516. gotRequestStream = true;
  517. WebAsyncResult result = asyncWrite;
  518. if (!requestSent) {
  519. requestSent = true;
  520. redirects = 0;
  521. servicePoint = GetServicePoint ();
  522. abortHandler = servicePoint.SendRequest (this, connectionGroup);
  523. }
  524. return result;
  525. }
  526. }
  527. public override Stream EndGetRequestStream (IAsyncResult asyncResult)
  528. {
  529. if (asyncResult == null)
  530. throw new ArgumentNullException ("asyncResult");
  531. WebAsyncResult result = asyncResult as WebAsyncResult;
  532. if (result == null)
  533. throw new ArgumentException ("Invalid IAsyncResult");
  534. asyncWrite = result;
  535. result.WaitUntilComplete ();
  536. Exception e = result.Exception;
  537. if (e != null)
  538. throw e;
  539. return result.WriteStream;
  540. }
  541. public override Stream GetRequestStream()
  542. {
  543. IAsyncResult asyncResult = BeginGetRequestStream (null, null);
  544. asyncWrite = (WebAsyncResult) asyncResult;
  545. if (!asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
  546. Abort ();
  547. throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
  548. }
  549. return EndGetRequestStream (asyncResult);
  550. }
  551. public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
  552. {
  553. bool send = (method == "PUT" || method == "POST");
  554. if (send) {
  555. if ((!KeepAlive || (ContentLength == -1 && !SendChunked)) && !AllowWriteStreamBuffering)
  556. throw new ProtocolViolationException ("Content-Length not set");
  557. }
  558. CommonChecks (send);
  559. Monitor.Enter (this);
  560. getResponseCalled = true;
  561. if (asyncRead != null && !haveResponse) {
  562. Monitor.Exit (this);
  563. throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
  564. "method while a previous call is still in progress.");
  565. }
  566. asyncRead = new WebAsyncResult (this, callback, state);
  567. initialMethod = method;
  568. if (haveResponse) {
  569. if (webResponse != null) {
  570. Exception saved = saved_exc;
  571. Monitor.Exit (this);
  572. if (saved == null) {
  573. asyncRead.SetCompleted (true, webResponse);
  574. } else {
  575. asyncRead.SetCompleted (true, saved);
  576. }
  577. asyncRead.DoCallback ();
  578. return asyncRead;
  579. }
  580. }
  581. if (!requestSent) {
  582. requestSent = true;
  583. redirects = 0;
  584. servicePoint = GetServicePoint ();
  585. abortHandler = servicePoint.SendRequest (this, connectionGroup);
  586. }
  587. Monitor.Exit (this);
  588. return asyncRead;
  589. }
  590. public override WebResponse EndGetResponse (IAsyncResult asyncResult)
  591. {
  592. if (asyncResult == null)
  593. throw new ArgumentNullException ("asyncResult");
  594. WebAsyncResult result = asyncResult as WebAsyncResult;
  595. if (result == null)
  596. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  597. if (!result.WaitUntilComplete (timeout, false)) {
  598. Abort ();
  599. throw new WebException("The request timed out", WebExceptionStatus.Timeout);
  600. }
  601. if (result.GotException)
  602. throw result.Exception;
  603. return result.Response;
  604. }
  605. public override WebResponse GetResponse()
  606. {
  607. WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
  608. return EndGetResponse (result);
  609. }
  610. public override void Abort ()
  611. {
  612. haveResponse = true;
  613. aborted = true;
  614. if (asyncWrite != null) {
  615. WebAsyncResult r = asyncWrite;
  616. WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
  617. r.SetCompleted (false, wexc);
  618. r.DoCallback ();
  619. asyncWrite = null;
  620. }
  621. if (asyncRead != null) {
  622. WebAsyncResult r = asyncRead;
  623. WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
  624. r.SetCompleted (false, wexc);
  625. r.DoCallback ();
  626. asyncRead = null;
  627. }
  628. if (abortHandler != null) {
  629. try {
  630. abortHandler (this, EventArgs.Empty);
  631. } catch (Exception) {}
  632. abortHandler = null;
  633. }
  634. if (writeStream != null) {
  635. try {
  636. writeStream.Close ();
  637. writeStream = null;
  638. } catch {}
  639. }
  640. if (webResponse != null) {
  641. try {
  642. webResponse.Close ();
  643. webResponse = null;
  644. } catch {}
  645. }
  646. }
  647. void ISerializable.GetObjectData (SerializationInfo serializationInfo,
  648. StreamingContext streamingContext)
  649. {
  650. SerializationInfo info = serializationInfo;
  651. info.AddValue ("requestUri", requestUri, typeof (Uri));
  652. info.AddValue ("actualUri", actualUri, typeof (Uri));
  653. info.AddValue ("allowAutoRedirect", allowAutoRedirect);
  654. info.AddValue ("allowBuffering", allowBuffering);
  655. info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
  656. info.AddValue ("connectionGroup", connectionGroup);
  657. info.AddValue ("contentLength", contentLength);
  658. info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
  659. info.AddValue ("keepAlive", keepAlive);
  660. info.AddValue ("maxAutoRedirect", maxAutoRedirect);
  661. info.AddValue ("mediaType", mediaType);
  662. info.AddValue ("method", method);
  663. info.AddValue ("initialMethod", initialMethod);
  664. info.AddValue ("pipelined", pipelined);
  665. info.AddValue ("version", version, typeof (Version));
  666. info.AddValue ("proxy", proxy, typeof (IWebProxy));
  667. info.AddValue ("sendChunked", sendChunked);
  668. info.AddValue ("timeout", timeout);
  669. info.AddValue ("redirects", redirects);
  670. }
  671. void CheckRequestStarted ()
  672. {
  673. if (requestSent)
  674. throw new InvalidOperationException ("request started");
  675. }
  676. internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
  677. {
  678. if (continueDelegate != null)
  679. continueDelegate (statusCode, headers);
  680. }
  681. bool Redirect (WebAsyncResult result, HttpStatusCode code)
  682. {
  683. redirects++;
  684. Exception e = null;
  685. string uriString = null;
  686. switch (code) {
  687. case HttpStatusCode.Ambiguous: // 300
  688. e = new WebException ("Ambiguous redirect.");
  689. break;
  690. case HttpStatusCode.MovedPermanently: // 301
  691. case HttpStatusCode.Redirect: // 302
  692. case HttpStatusCode.TemporaryRedirect: // 307
  693. /* MS follows the redirect for POST too
  694. if (method != "GET" && method != "HEAD") // 10.3
  695. return false;
  696. */
  697. uriString = webResponse.Headers ["Location"];
  698. break;
  699. case HttpStatusCode.SeeOther: //303
  700. method = "GET";
  701. uriString = webResponse.Headers ["Location"];
  702. break;
  703. case HttpStatusCode.NotModified: // 304
  704. return false;
  705. case HttpStatusCode.UseProxy: // 305
  706. e = new NotImplementedException ("Proxy support not available.");
  707. break;
  708. case HttpStatusCode.Unused: // 306
  709. default:
  710. e = new ProtocolViolationException ("Invalid status code: " + (int) code);
  711. break;
  712. }
  713. if (e != null)
  714. throw e;
  715. if (uriString == null)
  716. throw new WebException ("No Location header found for " + (int) code,
  717. WebExceptionStatus.ProtocolError);
  718. Uri prev = actualUri;
  719. try {
  720. actualUri = new Uri (actualUri, uriString);
  721. } catch (Exception) {
  722. throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
  723. uriString, (int) code),
  724. WebExceptionStatus.ProtocolError);
  725. }
  726. hostChanged = (actualUri.Scheme != prev.Scheme || actualUri.Host != prev.Host ||
  727. actualUri.Port != prev.Port);
  728. return true;
  729. }
  730. string GetHeaders ()
  731. {
  732. bool continue100 = false;
  733. if (contentLength != -1) {
  734. continue100 = true;
  735. webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
  736. webHeaders.RemoveInternal ("Transfer-Encoding");
  737. } else if (sendChunked) {
  738. continue100 = true;
  739. webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
  740. webHeaders.RemoveInternal ("Content-Length");
  741. }
  742. if (actualVersion == HttpVersion.Version11 && continue100 &&
  743. servicePoint.SendContinue) { // RFC2616 8.2.3
  744. webHeaders.RemoveAndAdd ("Expect" , "100-continue");
  745. expectContinue = true;
  746. } else {
  747. webHeaders.RemoveInternal ("Expect");
  748. expectContinue = false;
  749. }
  750. string connectionHeader = (ProxyQuery) ? "Proxy-Connection" : "Connection";
  751. webHeaders.RemoveInternal ((!ProxyQuery) ? "Proxy-Connection" : "Connection");
  752. bool spoint10 = (servicePoint.ProtocolVersion == null ||
  753. servicePoint.ProtocolVersion == HttpVersion.Version10);
  754. if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
  755. webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
  756. } else if (!keepAlive && version == HttpVersion.Version11) {
  757. webHeaders.RemoveAndAdd (connectionHeader, "close");
  758. }
  759. webHeaders.SetInternal ("Host", actualUri.Authority);
  760. if (cookieContainer != null) {
  761. string cookieHeader = cookieContainer.GetCookieHeader (requestUri);
  762. if (cookieHeader != "")
  763. webHeaders.SetInternal ("Cookie", cookieHeader);
  764. }
  765. if (!usedPreAuth && preAuthenticate)
  766. DoPreAuthenticate ();
  767. return webHeaders.ToString ();
  768. }
  769. void DoPreAuthenticate ()
  770. {
  771. webHeaders.RemoveInternal ("Proxy-Authorization");
  772. webHeaders.RemoveInternal ("Authorization");
  773. bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
  774. ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
  775. Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
  776. if (auth == null)
  777. return;
  778. string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
  779. webHeaders [authHeader] = auth.Message;
  780. usedPreAuth = true;
  781. }
  782. internal void SetWriteStreamError (WebExceptionStatus status)
  783. {
  784. if (aborted)
  785. return;
  786. WebAsyncResult r = asyncWrite;
  787. if (r == null)
  788. r = asyncRead;
  789. if (r != null) {
  790. r.SetCompleted (false, new WebException ("Error: " + status, status));
  791. r.DoCallback ();
  792. }
  793. }
  794. internal void SendRequestHeaders ()
  795. {
  796. StringBuilder req = new StringBuilder ();
  797. string query;
  798. if (!ProxyQuery) {
  799. query = actualUri.PathAndQuery;
  800. } else if (actualUri.IsDefaultPort) {
  801. query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
  802. actualUri.Host,
  803. actualUri.PathAndQuery);
  804. } else {
  805. query = String.Format ("{0}://{1}:{2}{3}", actualUri.Scheme,
  806. actualUri.Host,
  807. actualUri.Port,
  808. actualUri.PathAndQuery);
  809. }
  810. if (servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
  811. actualVersion = servicePoint.ProtocolVersion;
  812. } else {
  813. actualVersion = version;
  814. }
  815. req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
  816. actualVersion.Major, actualVersion.Minor);
  817. req.Append (GetHeaders ());
  818. string reqstr = req.ToString ();
  819. byte [] bytes = Encoding.UTF8.GetBytes (reqstr);
  820. writeStream.SetHeaders (bytes, 0, bytes.Length);
  821. }
  822. internal void SetWriteStream (WebConnectionStream stream)
  823. {
  824. if (aborted)
  825. return;
  826. writeStream = stream;
  827. if (bodyBuffer != null) {
  828. webHeaders.RemoveInternal ("Transfer-Encoding");
  829. contentLength = bodyBufferLength;
  830. writeStream.SendChunked = false;
  831. }
  832. SendRequestHeaders ();
  833. haveRequest = true;
  834. if (bodyBuffer != null) {
  835. // The body has been written and buffered. The request "user"
  836. // won't write it again, so we must do it.
  837. writeStream.Write (bodyBuffer, 0, bodyBufferLength);
  838. bodyBuffer = null;
  839. writeStream.Close ();
  840. } else if (method == "PUT" || method == "POST") {
  841. if (getResponseCalled && !writeStream.RequestWritten)
  842. writeStream.WriteRequest ();
  843. }
  844. if (asyncWrite != null) {
  845. asyncWrite.SetCompleted (false, stream);
  846. asyncWrite.DoCallback ();
  847. asyncWrite = null;
  848. }
  849. }
  850. internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
  851. {
  852. if (aborted)
  853. return;
  854. string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
  855. WebAsyncResult r = asyncRead;
  856. if (r == null)
  857. r = asyncWrite;
  858. if (r != null) {
  859. WebException wexc;
  860. if (e is WebException) {
  861. wexc = (WebException) e;
  862. } else {
  863. wexc = new WebException (msg, e, status, null);
  864. }
  865. r.SetCompleted (false, wexc);
  866. r.DoCallback ();
  867. asyncRead = null;
  868. asyncWrite = null;
  869. }
  870. }
  871. void CheckSendError (WebConnectionData data)
  872. {
  873. // Got here, but no one called GetResponse
  874. if (data.StatusCode < 400)
  875. return;
  876. if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
  877. // The request has not been completely sent and we got here!
  878. // We should probably just close and cause an error in any case,
  879. saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse);
  880. webResponse.ReadAll ();
  881. }
  882. }
  883. internal void SetResponseData (WebConnectionData data)
  884. {
  885. if (aborted) {
  886. if (data.stream != null)
  887. data.stream.Close ();
  888. return;
  889. }
  890. WebException wexc = null;
  891. try {
  892. webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
  893. haveResponse = true;
  894. } catch (Exception e) {
  895. wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null);
  896. if (data.stream != null)
  897. data.stream.Close ();
  898. }
  899. if (wexc == null && (method == "POST" || method == "PUT")) {
  900. lock (locker) {
  901. CheckSendError (data);
  902. if (saved_exc != null)
  903. wexc = (WebException) saved_exc;
  904. }
  905. }
  906. WebAsyncResult r = asyncRead;
  907. if (r != null) {
  908. if (wexc != null) {
  909. r.SetCompleted (false, wexc);
  910. r.DoCallback ();
  911. return;
  912. }
  913. bool redirected;
  914. try {
  915. redirected = CheckFinalStatus (r);
  916. if (!redirected) {
  917. r.SetCompleted (false, webResponse);
  918. r.DoCallback ();
  919. } else {
  920. if (webResponse != null) {
  921. webResponse.Close ();
  922. webResponse = null;
  923. }
  924. haveResponse = false;
  925. webResponse = null;
  926. r.Reset ();
  927. servicePoint = GetServicePoint ();
  928. abortHandler = servicePoint.SendRequest (this, connectionGroup);
  929. }
  930. } catch (WebException wexc2) {
  931. r.SetCompleted (false, wexc2);
  932. r.DoCallback ();
  933. return;
  934. } catch (Exception ex) {
  935. wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
  936. r.SetCompleted (false, wexc);
  937. r.DoCallback ();
  938. return;
  939. }
  940. }
  941. }
  942. bool CheckAuthorization (WebResponse response, HttpStatusCode code)
  943. {
  944. authCompleted = false;
  945. if (code == HttpStatusCode.Unauthorized && credentials == null)
  946. return false;
  947. bool isProxy = (code == HttpStatusCode.ProxyAuthenticationRequired);
  948. if (isProxy && (proxy == null || proxy.Credentials == null))
  949. return false;
  950. string authHeader = response.Headers [(isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate"];
  951. if (authHeader == null)
  952. return false;
  953. ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
  954. Authorization auth = AuthenticationManager.Authenticate (authHeader, this, creds);
  955. if (auth == null)
  956. return false;
  957. webHeaders [(isProxy) ? "Proxy-Authorization" : "Authorization"] = auth.Message;
  958. authCompleted = auth.Complete;
  959. return true;
  960. }
  961. // Returns true if redirected
  962. bool CheckFinalStatus (WebAsyncResult result)
  963. {
  964. if (result.GotException)
  965. throw result.Exception;
  966. Exception throwMe = result.Exception;
  967. bodyBuffer = null;
  968. HttpWebResponse resp = result.Response;
  969. WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
  970. HttpStatusCode code = 0;
  971. if (throwMe == null && webResponse != null) {
  972. code = webResponse.StatusCode;
  973. if (!authCompleted && ((code == HttpStatusCode.Unauthorized && credentials != null) ||
  974. code == HttpStatusCode.ProxyAuthenticationRequired)) {
  975. if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
  976. // Keep the written body, so it can be rewritten in the retry
  977. if (InternalAllowBuffering) {
  978. bodyBuffer = writeStream.WriteBuffer;
  979. bodyBufferLength = writeStream.WriteBufferLength;
  980. webResponse.Close ();
  981. return true;
  982. } else if (method != "PUT" && method != "POST") {
  983. webResponse.Close ();
  984. return true;
  985. }
  986. writeStream.InternalClose ();
  987. writeStream = null;
  988. webResponse.Close ();
  989. webResponse = null;
  990. throw new WebException ("This request requires buffering " +
  991. "of data for authentication or " +
  992. "redirection to be sucessful.");
  993. }
  994. }
  995. if ((int) code >= 400) {
  996. string err = String.Format ("The remote server returned an error: ({0}) {1}.",
  997. (int) code, webResponse.StatusDescription);
  998. throwMe = new WebException (err, null, protoError, webResponse);
  999. webResponse.ReadAll ();
  1000. } else if ((int) code == 304 && allowAutoRedirect) {
  1001. string err = String.Format ("The remote server returned an error: ({0}) {1}.",
  1002. (int) code, webResponse.StatusDescription);
  1003. throwMe = new WebException (err, null, protoError, webResponse);
  1004. } else if ((int) code >= 300 && allowAutoRedirect && redirects > maxAutoRedirect) {
  1005. throwMe = new WebException ("Max. redirections exceeded.", null,
  1006. protoError, webResponse);
  1007. webResponse.ReadAll ();
  1008. }
  1009. }
  1010. if (throwMe == null) {
  1011. bool b = false;
  1012. int c = (int) code;
  1013. if (allowAutoRedirect && c >= 300)
  1014. b = Redirect (result, code);
  1015. if (resp != null && c >= 300 && c != 304)
  1016. resp.ReadAll ();
  1017. return b;
  1018. }
  1019. if (writeStream != null) {
  1020. writeStream.InternalClose ();
  1021. writeStream = null;
  1022. }
  1023. webResponse = null;
  1024. throw throwMe;
  1025. }
  1026. }
  1027. }