HttpWebRequest.cs 30 KB

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