HttpWebRequest.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197
  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. bool unsafe_auth_blah;
  411. [MonoTODO]
  412. public bool UnsafeAuthenticatedConnectionSharing
  413. {
  414. get { return unsafe_auth_blah; }
  415. set { unsafe_auth_blah = value; }
  416. }
  417. #endif
  418. internal bool GotRequestStream {
  419. get { return gotRequestStream; }
  420. }
  421. internal bool ExpectContinue {
  422. get { return expectContinue; }
  423. set { expectContinue = value; }
  424. }
  425. internal Uri AuthUri {
  426. get { return actualUri; }
  427. }
  428. internal bool ProxyQuery {
  429. get { return servicePoint.UsesProxy && !servicePoint.UseConnect; }
  430. }
  431. // Methods
  432. internal ServicePoint GetServicePoint ()
  433. {
  434. lock (locker) {
  435. if (hostChanged || servicePoint == null) {
  436. servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
  437. hostChanged = false;
  438. }
  439. }
  440. return servicePoint;
  441. }
  442. public void AddRange (int range)
  443. {
  444. AddRange ("bytes", range);
  445. }
  446. public void AddRange (int from, int to)
  447. {
  448. AddRange ("bytes", from, to);
  449. }
  450. public void AddRange (string rangeSpecifier, int range)
  451. {
  452. if (rangeSpecifier == null)
  453. throw new ArgumentNullException ("rangeSpecifier");
  454. string value = webHeaders ["Range"];
  455. if (value == null || value.Length == 0)
  456. value = rangeSpecifier + "=";
  457. else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
  458. value += ",";
  459. else
  460. throw new InvalidOperationException ("rangeSpecifier");
  461. webHeaders.RemoveAndAdd ("Range", value + range + "-");
  462. }
  463. public void AddRange (string rangeSpecifier, int from, int to)
  464. {
  465. if (rangeSpecifier == null)
  466. throw new ArgumentNullException ("rangeSpecifier");
  467. if (from < 0 || to < 0 || from > to)
  468. throw new ArgumentOutOfRangeException ();
  469. string value = webHeaders ["Range"];
  470. if (value == null || value.Length == 0)
  471. value = rangeSpecifier + "=";
  472. else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
  473. value += ",";
  474. else
  475. throw new InvalidOperationException ("rangeSpecifier");
  476. webHeaders.RemoveAndAdd ("Range", value + from + "-" + to);
  477. }
  478. #if !NET_2_0
  479. public override int GetHashCode ()
  480. {
  481. return base.GetHashCode ();
  482. }
  483. #endif
  484. void CommonChecks (bool putpost)
  485. {
  486. if (method == null)
  487. throw new ProtocolViolationException ("Method is null.");
  488. if (putpost && ((!keepAlive || (contentLength == -1 && !sendChunked)) && !allowBuffering))
  489. throw new ProtocolViolationException ("Content-Length not set");
  490. string transferEncoding = TransferEncoding;
  491. if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
  492. throw new ProtocolViolationException ("SendChunked should be true.");
  493. }
  494. public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
  495. {
  496. if (aborted)
  497. throw new WebException ("The request was previosly aborted.");
  498. bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD");
  499. if (method == null || !send)
  500. throw new ProtocolViolationException ("Cannot send data when method is: " + method);
  501. CommonChecks (send);
  502. lock (locker)
  503. {
  504. if (asyncWrite != null) {
  505. throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
  506. "method while a previous call is still in progress.");
  507. }
  508. asyncWrite = new WebAsyncResult (this, callback, state);
  509. initialMethod = method;
  510. if (haveRequest) {
  511. if (writeStream != null) {
  512. asyncWrite.SetCompleted (true, writeStream);
  513. asyncWrite.DoCallback ();
  514. return asyncWrite;
  515. }
  516. }
  517. gotRequestStream = true;
  518. WebAsyncResult result = asyncWrite;
  519. if (!requestSent) {
  520. requestSent = true;
  521. redirects = 0;
  522. servicePoint = GetServicePoint ();
  523. abortHandler = servicePoint.SendRequest (this, connectionGroup);
  524. }
  525. return result;
  526. }
  527. }
  528. public override Stream EndGetRequestStream (IAsyncResult asyncResult)
  529. {
  530. if (asyncResult == null)
  531. throw new ArgumentNullException ("asyncResult");
  532. WebAsyncResult result = asyncResult as WebAsyncResult;
  533. if (result == null)
  534. throw new ArgumentException ("Invalid IAsyncResult");
  535. asyncWrite = result;
  536. result.WaitUntilComplete ();
  537. Exception e = result.Exception;
  538. if (e != null)
  539. throw e;
  540. return result.WriteStream;
  541. }
  542. public override Stream GetRequestStream()
  543. {
  544. IAsyncResult asyncResult = BeginGetRequestStream (null, null);
  545. asyncWrite = (WebAsyncResult) asyncResult;
  546. if (!asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
  547. Abort ();
  548. throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
  549. }
  550. return EndGetRequestStream (asyncResult);
  551. }
  552. public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
  553. {
  554. bool send = (method == "PUT" || method == "POST");
  555. if (send) {
  556. if ((!KeepAlive || (ContentLength == -1 && !SendChunked)) && !AllowWriteStreamBuffering)
  557. throw new ProtocolViolationException ("Content-Length not set");
  558. }
  559. CommonChecks (send);
  560. Monitor.Enter (this);
  561. getResponseCalled = true;
  562. if (asyncRead != null && !haveResponse) {
  563. Monitor.Exit (this);
  564. throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
  565. "method while a previous call is still in progress.");
  566. }
  567. asyncRead = new WebAsyncResult (this, callback, state);
  568. initialMethod = method;
  569. if (haveResponse) {
  570. if (webResponse != null) {
  571. Exception saved = saved_exc;
  572. Monitor.Exit (this);
  573. if (saved == null) {
  574. asyncRead.SetCompleted (true, webResponse);
  575. } else {
  576. asyncRead.SetCompleted (true, saved);
  577. }
  578. asyncRead.DoCallback ();
  579. return asyncRead;
  580. }
  581. }
  582. if (!requestSent) {
  583. requestSent = true;
  584. redirects = 0;
  585. servicePoint = GetServicePoint ();
  586. abortHandler = servicePoint.SendRequest (this, connectionGroup);
  587. }
  588. Monitor.Exit (this);
  589. return asyncRead;
  590. }
  591. public override WebResponse EndGetResponse (IAsyncResult asyncResult)
  592. {
  593. if (asyncResult == null)
  594. throw new ArgumentNullException ("asyncResult");
  595. WebAsyncResult result = asyncResult as WebAsyncResult;
  596. if (result == null)
  597. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  598. if (!result.WaitUntilComplete (timeout, false)) {
  599. Abort ();
  600. throw new WebException("The request timed out", WebExceptionStatus.Timeout);
  601. }
  602. if (result.GotException)
  603. throw result.Exception;
  604. return result.Response;
  605. }
  606. public override WebResponse GetResponse()
  607. {
  608. WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
  609. return EndGetResponse (result);
  610. }
  611. public override void Abort ()
  612. {
  613. haveResponse = true;
  614. aborted = true;
  615. if (asyncWrite != null) {
  616. WebAsyncResult r = asyncWrite;
  617. WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
  618. r.SetCompleted (false, wexc);
  619. r.DoCallback ();
  620. asyncWrite = null;
  621. }
  622. if (asyncRead != null) {
  623. WebAsyncResult r = asyncRead;
  624. WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
  625. r.SetCompleted (false, wexc);
  626. r.DoCallback ();
  627. asyncRead = null;
  628. }
  629. if (abortHandler != null) {
  630. try {
  631. abortHandler (this, EventArgs.Empty);
  632. } catch (Exception) {}
  633. abortHandler = null;
  634. }
  635. if (writeStream != null) {
  636. try {
  637. writeStream.Close ();
  638. writeStream = null;
  639. } catch {}
  640. }
  641. if (webResponse != null) {
  642. try {
  643. webResponse.Close ();
  644. webResponse = null;
  645. } catch {}
  646. }
  647. }
  648. void ISerializable.GetObjectData (SerializationInfo serializationInfo,
  649. StreamingContext streamingContext)
  650. {
  651. SerializationInfo info = serializationInfo;
  652. info.AddValue ("requestUri", requestUri, typeof (Uri));
  653. info.AddValue ("actualUri", actualUri, typeof (Uri));
  654. info.AddValue ("allowAutoRedirect", allowAutoRedirect);
  655. info.AddValue ("allowBuffering", allowBuffering);
  656. info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
  657. info.AddValue ("connectionGroup", connectionGroup);
  658. info.AddValue ("contentLength", contentLength);
  659. info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
  660. info.AddValue ("keepAlive", keepAlive);
  661. info.AddValue ("maxAutoRedirect", maxAutoRedirect);
  662. info.AddValue ("mediaType", mediaType);
  663. info.AddValue ("method", method);
  664. info.AddValue ("initialMethod", initialMethod);
  665. info.AddValue ("pipelined", pipelined);
  666. info.AddValue ("version", version, typeof (Version));
  667. info.AddValue ("proxy", proxy, typeof (IWebProxy));
  668. info.AddValue ("sendChunked", sendChunked);
  669. info.AddValue ("timeout", timeout);
  670. info.AddValue ("redirects", redirects);
  671. }
  672. void CheckRequestStarted ()
  673. {
  674. if (requestSent)
  675. throw new InvalidOperationException ("request started");
  676. }
  677. internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
  678. {
  679. if (continueDelegate != null)
  680. continueDelegate (statusCode, headers);
  681. }
  682. bool Redirect (WebAsyncResult result, HttpStatusCode code)
  683. {
  684. redirects++;
  685. Exception e = null;
  686. string uriString = null;
  687. switch (code) {
  688. case HttpStatusCode.Ambiguous: // 300
  689. e = new WebException ("Ambiguous redirect.");
  690. break;
  691. case HttpStatusCode.MovedPermanently: // 301
  692. case HttpStatusCode.Redirect: // 302
  693. case HttpStatusCode.TemporaryRedirect: // 307
  694. /* MS follows the redirect for POST too
  695. if (method != "GET" && method != "HEAD") // 10.3
  696. return false;
  697. */
  698. uriString = webResponse.Headers ["Location"];
  699. break;
  700. case HttpStatusCode.SeeOther: //303
  701. method = "GET";
  702. uriString = webResponse.Headers ["Location"];
  703. break;
  704. case HttpStatusCode.NotModified: // 304
  705. return false;
  706. case HttpStatusCode.UseProxy: // 305
  707. e = new NotImplementedException ("Proxy support not available.");
  708. break;
  709. case HttpStatusCode.Unused: // 306
  710. default:
  711. e = new ProtocolViolationException ("Invalid status code: " + (int) code);
  712. break;
  713. }
  714. if (e != null)
  715. throw e;
  716. if (uriString == null)
  717. throw new WebException ("No Location header found for " + (int) code,
  718. WebExceptionStatus.ProtocolError);
  719. Uri prev = actualUri;
  720. try {
  721. actualUri = new Uri (actualUri, uriString);
  722. } catch (Exception) {
  723. throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
  724. uriString, (int) code),
  725. WebExceptionStatus.ProtocolError);
  726. }
  727. hostChanged = (actualUri.Scheme != prev.Scheme || actualUri.Host != prev.Host ||
  728. actualUri.Port != prev.Port);
  729. return true;
  730. }
  731. string GetHeaders ()
  732. {
  733. bool continue100 = false;
  734. if (contentLength != -1) {
  735. continue100 = true;
  736. webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
  737. webHeaders.RemoveInternal ("Transfer-Encoding");
  738. } else if (sendChunked) {
  739. continue100 = true;
  740. webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
  741. webHeaders.RemoveInternal ("Content-Length");
  742. }
  743. if (actualVersion == HttpVersion.Version11 && continue100 &&
  744. servicePoint.SendContinue) { // RFC2616 8.2.3
  745. webHeaders.RemoveAndAdd ("Expect" , "100-continue");
  746. expectContinue = true;
  747. } else {
  748. webHeaders.RemoveInternal ("Expect");
  749. expectContinue = false;
  750. }
  751. string connectionHeader = (ProxyQuery) ? "Proxy-Connection" : "Connection";
  752. webHeaders.RemoveInternal ((!ProxyQuery) ? "Proxy-Connection" : "Connection");
  753. bool spoint10 = (servicePoint.ProtocolVersion == null ||
  754. servicePoint.ProtocolVersion == HttpVersion.Version10);
  755. if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
  756. webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
  757. } else if (!keepAlive && version == HttpVersion.Version11) {
  758. webHeaders.RemoveAndAdd (connectionHeader, "close");
  759. }
  760. webHeaders.SetInternal ("Host", actualUri.Authority);
  761. if (cookieContainer != null) {
  762. string cookieHeader = cookieContainer.GetCookieHeader (requestUri);
  763. if (cookieHeader != "")
  764. webHeaders.SetInternal ("Cookie", cookieHeader);
  765. }
  766. if (!usedPreAuth && preAuthenticate)
  767. DoPreAuthenticate ();
  768. return webHeaders.ToString ();
  769. }
  770. void DoPreAuthenticate ()
  771. {
  772. webHeaders.RemoveInternal ("Proxy-Authorization");
  773. webHeaders.RemoveInternal ("Authorization");
  774. bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
  775. ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
  776. Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
  777. if (auth == null)
  778. return;
  779. string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
  780. webHeaders [authHeader] = auth.Message;
  781. usedPreAuth = true;
  782. }
  783. internal void SetWriteStreamError (WebExceptionStatus status)
  784. {
  785. if (aborted)
  786. return;
  787. WebAsyncResult r = asyncWrite;
  788. if (r == null)
  789. r = asyncRead;
  790. if (r != null) {
  791. r.SetCompleted (false, new WebException ("Error: " + status, status));
  792. r.DoCallback ();
  793. }
  794. }
  795. internal void SendRequestHeaders ()
  796. {
  797. StringBuilder req = new StringBuilder ();
  798. string query;
  799. if (!ProxyQuery) {
  800. query = actualUri.PathAndQuery;
  801. } else if (actualUri.IsDefaultPort) {
  802. query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
  803. actualUri.Host,
  804. actualUri.PathAndQuery);
  805. } else {
  806. query = String.Format ("{0}://{1}:{2}{3}", actualUri.Scheme,
  807. actualUri.Host,
  808. actualUri.Port,
  809. actualUri.PathAndQuery);
  810. }
  811. if (servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
  812. actualVersion = servicePoint.ProtocolVersion;
  813. } else {
  814. actualVersion = version;
  815. }
  816. req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
  817. actualVersion.Major, actualVersion.Minor);
  818. req.Append (GetHeaders ());
  819. string reqstr = req.ToString ();
  820. byte [] bytes = Encoding.UTF8.GetBytes (reqstr);
  821. writeStream.SetHeaders (bytes, 0, bytes.Length);
  822. }
  823. internal void SetWriteStream (WebConnectionStream stream)
  824. {
  825. if (aborted)
  826. return;
  827. writeStream = stream;
  828. if (bodyBuffer != null) {
  829. webHeaders.RemoveInternal ("Transfer-Encoding");
  830. contentLength = bodyBufferLength;
  831. writeStream.SendChunked = false;
  832. }
  833. SendRequestHeaders ();
  834. haveRequest = true;
  835. if (bodyBuffer != null) {
  836. // The body has been written and buffered. The request "user"
  837. // won't write it again, so we must do it.
  838. writeStream.Write (bodyBuffer, 0, bodyBufferLength);
  839. bodyBuffer = null;
  840. writeStream.Close ();
  841. } else if (method == "PUT" || method == "POST") {
  842. if (getResponseCalled && !writeStream.RequestWritten)
  843. writeStream.WriteRequest ();
  844. }
  845. if (asyncWrite != null) {
  846. asyncWrite.SetCompleted (false, stream);
  847. asyncWrite.DoCallback ();
  848. asyncWrite = null;
  849. }
  850. }
  851. internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
  852. {
  853. if (aborted)
  854. return;
  855. string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
  856. WebAsyncResult r = asyncRead;
  857. if (r == null)
  858. r = asyncWrite;
  859. if (r != null) {
  860. WebException wexc;
  861. if (e is WebException) {
  862. wexc = (WebException) e;
  863. } else {
  864. wexc = new WebException (msg, e, status, null);
  865. }
  866. r.SetCompleted (false, wexc);
  867. r.DoCallback ();
  868. asyncRead = null;
  869. asyncWrite = null;
  870. }
  871. }
  872. void CheckSendError (WebConnectionData data)
  873. {
  874. // Got here, but no one called GetResponse
  875. if (data.StatusCode < 400)
  876. return;
  877. if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
  878. // The request has not been completely sent and we got here!
  879. // We should probably just close and cause an error in any case,
  880. saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse);
  881. webResponse.ReadAll ();
  882. }
  883. }
  884. internal void SetResponseData (WebConnectionData data)
  885. {
  886. if (aborted) {
  887. if (data.stream != null)
  888. data.stream.Close ();
  889. return;
  890. }
  891. WebException wexc = null;
  892. try {
  893. webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
  894. haveResponse = true;
  895. } catch (Exception e) {
  896. wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null);
  897. if (data.stream != null)
  898. data.stream.Close ();
  899. }
  900. if (wexc == null && (method == "POST" || method == "PUT")) {
  901. lock (locker) {
  902. CheckSendError (data);
  903. if (saved_exc != null)
  904. wexc = (WebException) saved_exc;
  905. }
  906. }
  907. WebAsyncResult r = asyncRead;
  908. if (r != null) {
  909. if (wexc != null) {
  910. r.SetCompleted (false, wexc);
  911. r.DoCallback ();
  912. return;
  913. }
  914. bool redirected;
  915. try {
  916. redirected = CheckFinalStatus (r);
  917. if (!redirected) {
  918. r.SetCompleted (false, webResponse);
  919. r.DoCallback ();
  920. } else {
  921. if (webResponse != null) {
  922. webResponse.Close ();
  923. webResponse = null;
  924. }
  925. haveResponse = false;
  926. webResponse = null;
  927. r.Reset ();
  928. servicePoint = GetServicePoint ();
  929. abortHandler = servicePoint.SendRequest (this, connectionGroup);
  930. }
  931. } catch (WebException wexc2) {
  932. r.SetCompleted (false, wexc2);
  933. r.DoCallback ();
  934. return;
  935. } catch (Exception ex) {
  936. wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
  937. r.SetCompleted (false, wexc);
  938. r.DoCallback ();
  939. return;
  940. }
  941. }
  942. }
  943. bool CheckAuthorization (WebResponse response, HttpStatusCode code)
  944. {
  945. authCompleted = false;
  946. if (code == HttpStatusCode.Unauthorized && credentials == null)
  947. return false;
  948. bool isProxy = (code == HttpStatusCode.ProxyAuthenticationRequired);
  949. if (isProxy && (proxy == null || proxy.Credentials == null))
  950. return false;
  951. string authHeader = response.Headers [(isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate"];
  952. if (authHeader == null)
  953. return false;
  954. ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
  955. Authorization auth = AuthenticationManager.Authenticate (authHeader, this, creds);
  956. if (auth == null)
  957. return false;
  958. webHeaders [(isProxy) ? "Proxy-Authorization" : "Authorization"] = auth.Message;
  959. authCompleted = auth.Complete;
  960. return true;
  961. }
  962. // Returns true if redirected
  963. bool CheckFinalStatus (WebAsyncResult result)
  964. {
  965. if (result.GotException)
  966. throw result.Exception;
  967. Exception throwMe = result.Exception;
  968. bodyBuffer = null;
  969. HttpWebResponse resp = result.Response;
  970. WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
  971. HttpStatusCode code = 0;
  972. if (throwMe == null && webResponse != null) {
  973. code = webResponse.StatusCode;
  974. if (!authCompleted && ((code == HttpStatusCode.Unauthorized && credentials != null) ||
  975. code == HttpStatusCode.ProxyAuthenticationRequired)) {
  976. if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
  977. // Keep the written body, so it can be rewritten in the retry
  978. if (InternalAllowBuffering) {
  979. bodyBuffer = writeStream.WriteBuffer;
  980. bodyBufferLength = writeStream.WriteBufferLength;
  981. webResponse.Close ();
  982. return true;
  983. } else if (method != "PUT" && method != "POST") {
  984. webResponse.Close ();
  985. return true;
  986. }
  987. writeStream.InternalClose ();
  988. writeStream = null;
  989. webResponse.Close ();
  990. webResponse = null;
  991. throw new WebException ("This request requires buffering " +
  992. "of data for authentication or " +
  993. "redirection to be sucessful.");
  994. }
  995. }
  996. if ((int) code >= 400) {
  997. string err = String.Format ("The remote server returned an error: ({0}) {1}.",
  998. (int) code, webResponse.StatusDescription);
  999. throwMe = new WebException (err, null, protoError, webResponse);
  1000. webResponse.ReadAll ();
  1001. } else if ((int) code == 304 && allowAutoRedirect) {
  1002. string err = String.Format ("The remote server returned an error: ({0}) {1}.",
  1003. (int) code, webResponse.StatusDescription);
  1004. throwMe = new WebException (err, null, protoError, webResponse);
  1005. } else if ((int) code >= 300 && allowAutoRedirect && redirects > maxAutoRedirect) {
  1006. throwMe = new WebException ("Max. redirections exceeded.", null,
  1007. protoError, webResponse);
  1008. webResponse.ReadAll ();
  1009. }
  1010. }
  1011. if (throwMe == null) {
  1012. bool b = false;
  1013. int c = (int) code;
  1014. if (allowAutoRedirect && c >= 300)
  1015. b = Redirect (result, code);
  1016. if (resp != null && c >= 300 && c != 304)
  1017. resp.ReadAll ();
  1018. return b;
  1019. }
  1020. if (writeStream != null) {
  1021. writeStream.InternalClose ();
  1022. writeStream = null;
  1023. }
  1024. webResponse = null;
  1025. throw throwMe;
  1026. }
  1027. }
  1028. }