HttpWebRequest.cs 32 KB

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