HttpWebRequest.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  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. //
  11. using System;
  12. using System.Collections;
  13. using System.IO;
  14. using System.Net.Sockets;
  15. using System.Runtime.Remoting.Messaging;
  16. using System.Runtime.Serialization;
  17. using System.Security.Cryptography.X509Certificates;
  18. using System.Text;
  19. using System.Threading;
  20. namespace System.Net
  21. {
  22. [Serializable]
  23. public class HttpWebRequest : WebRequest, ISerializable
  24. {
  25. Uri requestUri;
  26. Uri actualUri;
  27. bool hostChanged;
  28. bool allowAutoRedirect = true;
  29. bool allowBuffering = true;
  30. X509CertificateCollection certificates;
  31. string connectionGroup;
  32. long contentLength = -1;
  33. HttpContinueDelegate continueDelegate;
  34. CookieContainer cookieContainer;
  35. ICredentials credentials;
  36. bool haveResponse;
  37. bool haveRequest;
  38. bool requestSent;
  39. WebHeaderCollection webHeaders = new WebHeaderCollection (true);
  40. bool keepAlive = true;
  41. int maxAutoRedirect = 50;
  42. string mediaType = String.Empty;
  43. string method = "GET";
  44. string initialMethod = "GET";
  45. bool pipelined = true;
  46. bool preAuthenticate;
  47. Version version = HttpVersion.Version11;
  48. IWebProxy proxy;
  49. bool manualProxy;
  50. bool sendChunked;
  51. ServicePoint servicePoint;
  52. int timeout = 100000;
  53. WebConnectionStream writeStream;
  54. HttpWebResponse webResponse;
  55. AutoResetEvent requestEndEvent;
  56. WebAsyncResult asyncWrite;
  57. WebAsyncResult asyncRead;
  58. EventHandler abortHandler;
  59. bool aborted;
  60. bool gotRequestStream;
  61. int redirects;
  62. bool expectContinue;
  63. bool triedAuth;
  64. // Constructors
  65. internal HttpWebRequest (Uri uri)
  66. {
  67. this.requestUri = uri;
  68. this.actualUri = uri;
  69. this.proxy = GlobalProxySelection.Select;
  70. }
  71. protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
  72. {
  73. SerializationInfo info = serializationInfo;
  74. requestUri = (Uri) info.GetValue ("requestUri", typeof (Uri));
  75. actualUri = (Uri) info.GetValue ("actualUri", typeof (Uri));
  76. allowAutoRedirect = info.GetBoolean ("allowAutoRedirect");
  77. allowBuffering = info.GetBoolean ("allowBuffering");
  78. certificates = (X509CertificateCollection) info.GetValue ("certificates", typeof (X509CertificateCollection));
  79. connectionGroup = info.GetString ("connectionGroup");
  80. contentLength = info.GetInt64 ("contentLength");
  81. webHeaders = (WebHeaderCollection) info.GetValue ("webHeaders", typeof (WebHeaderCollection));
  82. keepAlive = info.GetBoolean ("keepAlive");
  83. maxAutoRedirect = info.GetInt32 ("maxAutoRedirect");
  84. mediaType = info.GetString ("mediaType");
  85. method = info.GetString ("method");
  86. initialMethod = info.GetString ("initialMethod");
  87. pipelined = info.GetBoolean ("pipelined");
  88. version = (Version) info.GetValue ("version", typeof (Version));
  89. proxy = (IWebProxy) info.GetValue ("proxy", typeof (IWebProxy));
  90. sendChunked = info.GetBoolean ("sendChunked");
  91. timeout = info.GetInt32 ("timeout");
  92. redirects = info.GetInt32 ("redirects");
  93. }
  94. // Properties
  95. public string Accept {
  96. get { return webHeaders ["Accept"]; }
  97. set {
  98. CheckRequestStarted ();
  99. webHeaders.SetInternal ("Accept", value);
  100. }
  101. }
  102. public Uri Address {
  103. get { return actualUri; }
  104. }
  105. public bool AllowAutoRedirect {
  106. get { return allowAutoRedirect; }
  107. set { this.allowAutoRedirect = value; }
  108. }
  109. public bool AllowWriteStreamBuffering {
  110. get { return allowBuffering; }
  111. set { allowBuffering = value; }
  112. }
  113. internal bool InternalAllowBuffering {
  114. get {
  115. return (allowBuffering && (method == "PUT" || method == "POST"));
  116. }
  117. }
  118. public X509CertificateCollection ClientCertificates {
  119. get {
  120. if (certificates == null)
  121. certificates = new X509CertificateCollection ();
  122. return certificates;
  123. }
  124. }
  125. public string Connection {
  126. get { return webHeaders ["Connection"]; }
  127. set {
  128. CheckRequestStarted ();
  129. string val = value;
  130. if (val != null)
  131. val = val.Trim ().ToLower ();
  132. if (val == null || val.Length == 0) {
  133. webHeaders.RemoveInternal ("Connection");
  134. return;
  135. }
  136. if (val == "keep-alive" || val == "close")
  137. throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
  138. if (keepAlive && val.IndexOf ("keep-alive") == -1)
  139. value = value + ", Keep-Alive";
  140. webHeaders.SetInternal ("Connection", value);
  141. }
  142. }
  143. public override string ConnectionGroupName {
  144. get { return connectionGroup; }
  145. set { connectionGroup = value; }
  146. }
  147. public override long ContentLength {
  148. get { return contentLength; }
  149. set {
  150. CheckRequestStarted ();
  151. if (value < 0)
  152. throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
  153. contentLength = value;
  154. }
  155. }
  156. internal long InternalContentLength {
  157. set { contentLength = value; }
  158. }
  159. public override string ContentType {
  160. get { return webHeaders ["Content-Type"]; }
  161. set {
  162. CheckRequestStarted ();
  163. if (value == null || value.Trim().Length == 0) {
  164. webHeaders.RemoveInternal ("Content-Type");
  165. return;
  166. }
  167. webHeaders.SetInternal ("Content-Type", value);
  168. }
  169. }
  170. public HttpContinueDelegate ContinueDelegate {
  171. get { return continueDelegate; }
  172. set { continueDelegate = value; }
  173. }
  174. public CookieContainer CookieContainer {
  175. get { return cookieContainer; }
  176. set { cookieContainer = value; }
  177. }
  178. public override ICredentials Credentials {
  179. get { return credentials; }
  180. set { credentials = value; }
  181. }
  182. public string Expect {
  183. get { return webHeaders ["Expect"]; }
  184. set {
  185. CheckRequestStarted ();
  186. string val = value;
  187. if (val != null)
  188. val = val.Trim ().ToLower ();
  189. if (val == null || val.Length == 0) {
  190. webHeaders.RemoveInternal ("Expect");
  191. return;
  192. }
  193. if (val == "100-continue")
  194. throw new ArgumentException ("100-Continue cannot be set with this property.",
  195. "value");
  196. webHeaders.SetInternal ("Expect", value);
  197. }
  198. }
  199. public bool HaveResponse {
  200. get { return haveResponse; }
  201. }
  202. public override WebHeaderCollection Headers {
  203. get { return webHeaders; }
  204. set {
  205. CheckRequestStarted ();
  206. WebHeaderCollection newHeaders = new WebHeaderCollection (true);
  207. int count = value.Count;
  208. for (int i = 0; i < count; i++)
  209. newHeaders.Add (value.GetKey (i), value.Get (i));
  210. webHeaders = newHeaders;
  211. }
  212. }
  213. public DateTime IfModifiedSince {
  214. get {
  215. string str = webHeaders ["If-Modified-Since"];
  216. if (str == null)
  217. return DateTime.Now;
  218. try {
  219. return MonoHttpDate.Parse (str);
  220. } catch (Exception) {
  221. return DateTime.Now;
  222. }
  223. }
  224. set {
  225. CheckRequestStarted ();
  226. // rfc-1123 pattern
  227. webHeaders.SetInternal ("If-Modified-Since",
  228. value.ToUniversalTime ().ToString ("r", null));
  229. // TODO: check last param when using different locale
  230. }
  231. }
  232. public bool KeepAlive {
  233. get {
  234. return keepAlive;
  235. }
  236. set {
  237. keepAlive = value;
  238. }
  239. }
  240. public int MaximumAutomaticRedirections {
  241. get { return maxAutoRedirect; }
  242. set {
  243. if (value <= 0)
  244. throw new ArgumentException ("Must be > 0", "value");
  245. maxAutoRedirect = value;
  246. }
  247. }
  248. public string MediaType {
  249. get { return mediaType; }
  250. set {
  251. mediaType = value;
  252. }
  253. }
  254. public override string Method {
  255. get { return this.method; }
  256. set {
  257. if (value == null || value.Trim () == "")
  258. throw new ArgumentException ("not a valid method");
  259. method = value;
  260. }
  261. }
  262. public bool Pipelined {
  263. get { return pipelined; }
  264. set { pipelined = value; }
  265. }
  266. public override bool PreAuthenticate {
  267. get { return preAuthenticate; } //TODO: support preauthentication
  268. set { preAuthenticate = value; }
  269. }
  270. public Version ProtocolVersion {
  271. get { return version; }
  272. set {
  273. if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
  274. throw new ArgumentException ("value");
  275. version = value;
  276. }
  277. }
  278. public override IWebProxy Proxy {
  279. get { return proxy; }
  280. set {
  281. CheckRequestStarted ();
  282. if (value == null)
  283. throw new ArgumentNullException ("value");
  284. proxy = value;
  285. servicePoint = null; // we may need a new one
  286. }
  287. }
  288. public string Referer {
  289. get { return webHeaders ["Referer"]; }
  290. set {
  291. CheckRequestStarted ();
  292. if (value == null || value.Trim().Length == 0) {
  293. webHeaders.RemoveInternal ("Referer");
  294. return;
  295. }
  296. webHeaders.SetInternal ("Referer", value);
  297. }
  298. }
  299. public override Uri RequestUri {
  300. get { return requestUri; }
  301. }
  302. public bool SendChunked {
  303. get { return sendChunked; }
  304. set {
  305. CheckRequestStarted ();
  306. sendChunked = value;
  307. }
  308. }
  309. public ServicePoint ServicePoint {
  310. get { return GetServicePoint (); }
  311. }
  312. public override int Timeout {
  313. get { return timeout; }
  314. set {
  315. if (value < -1)
  316. throw new ArgumentOutOfRangeException ("value");
  317. timeout = value;
  318. }
  319. }
  320. public string TransferEncoding {
  321. get { return webHeaders ["Transfer-Encoding"]; }
  322. set {
  323. CheckRequestStarted ();
  324. string val = value;
  325. if (val != null)
  326. val = val.Trim ().ToLower ();
  327. if (val == null || val.Length == 0) {
  328. webHeaders.RemoveInternal ("Transfer-Encoding");
  329. return;
  330. }
  331. if (val == "chunked")
  332. throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
  333. if (!sendChunked)
  334. throw new ArgumentException ("SendChunked must be True", "value");
  335. webHeaders.SetInternal ("Transfer-Encoding", value);
  336. }
  337. }
  338. public string UserAgent {
  339. get { return webHeaders ["User-Agent"]; }
  340. set { webHeaders.SetInternal ("User-Agent", value); }
  341. }
  342. internal bool GotRequestStream {
  343. get { return gotRequestStream; }
  344. }
  345. internal bool ExpectContinue {
  346. get { return expectContinue; }
  347. set { expectContinue = value; }
  348. }
  349. internal string AuthRequestHeader {
  350. get { return "WWW-Authenticate"; }
  351. }
  352. internal string AuthResponseHeader {
  353. get { return "Authorization"; }
  354. }
  355. internal Uri AuthUri {
  356. get { return actualUri; }
  357. }
  358. internal bool ProxyQuery {
  359. get { return servicePoint.UsesProxy; }
  360. }
  361. // Methods
  362. internal ServicePoint GetServicePoint ()
  363. {
  364. if (!hostChanged && servicePoint != null)
  365. return servicePoint;
  366. lock (this) {
  367. if (hostChanged || servicePoint == null) {
  368. servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
  369. hostChanged = false;
  370. }
  371. }
  372. return servicePoint;
  373. }
  374. public void AddRange (int range)
  375. {
  376. AddRange ("bytes", range);
  377. }
  378. public void AddRange (int from, int to)
  379. {
  380. AddRange ("bytes", from, to);
  381. }
  382. public void AddRange (string rangeSpecifier, int range)
  383. {
  384. if (rangeSpecifier == null)
  385. throw new ArgumentNullException ("rangeSpecifier");
  386. string value = webHeaders ["Range"];
  387. if (value == null || value.Length == 0)
  388. value = rangeSpecifier + "=";
  389. else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
  390. value += ",";
  391. else
  392. throw new InvalidOperationException ("rangeSpecifier");
  393. webHeaders.SetInternal ("Range", value + range + "-");
  394. }
  395. public void AddRange (string rangeSpecifier, int from, int to)
  396. {
  397. if (rangeSpecifier == null)
  398. throw new ArgumentNullException ("rangeSpecifier");
  399. if (from < 0 || to < 0 || from > to)
  400. throw new ArgumentOutOfRangeException ();
  401. string value = webHeaders ["Range"];
  402. if (value == null || value.Length == 0)
  403. value = rangeSpecifier + "=";
  404. else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
  405. value += ",";
  406. else
  407. throw new InvalidOperationException ("rangeSpecifier");
  408. webHeaders.SetInternal ("Range", value + from + "-" + to);
  409. }
  410. public override int GetHashCode ()
  411. {
  412. return base.GetHashCode ();
  413. }
  414. void CommonChecks (bool putpost)
  415. {
  416. if (method == null)
  417. throw new ProtocolViolationException ("Method is null.");
  418. if (putpost && ((!keepAlive || (contentLength == -1 && !sendChunked)) && !allowBuffering))
  419. throw new ProtocolViolationException ("Content-Length not set");
  420. string transferEncoding = TransferEncoding;
  421. if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
  422. throw new ProtocolViolationException ("SendChunked should be true.");
  423. }
  424. public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
  425. {
  426. if (aborted)
  427. throw new WebException ("The request was previosly aborted.");
  428. bool send = (method == "PUT" || method == "POST");
  429. if (method == null || !send)
  430. throw new ProtocolViolationException ("Cannot send data when method is: " + method);
  431. CommonChecks (send);
  432. Monitor.Enter (this);
  433. if (asyncWrite != null) {
  434. Monitor.Exit (this);
  435. throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
  436. "method while a previous call is still in progress.");
  437. }
  438. asyncWrite = new WebAsyncResult (this, callback, state);
  439. initialMethod = method;
  440. if (haveRequest) {
  441. if (writeStream != null) {
  442. Monitor.Exit (this);
  443. asyncWrite.SetCompleted (true, writeStream);
  444. asyncWrite.DoCallback ();
  445. return asyncWrite;
  446. }
  447. }
  448. gotRequestStream = true;
  449. WebAsyncResult result = asyncWrite;
  450. if (!requestSent) {
  451. requestSent = true;
  452. servicePoint = GetServicePoint ();
  453. abortHandler = servicePoint.SendRequest (this, connectionGroup);
  454. }
  455. Monitor.Exit (this);
  456. return result;
  457. }
  458. public override Stream EndGetRequestStream (IAsyncResult asyncResult)
  459. {
  460. if (asyncResult == null)
  461. throw new ArgumentNullException ("asyncResult");
  462. WebAsyncResult result = asyncResult as WebAsyncResult;
  463. if (result == null)
  464. throw new ArgumentException ("Invalid IAsyncResult");
  465. asyncWrite = result;
  466. result.WaitUntilComplete ();
  467. Exception e = result.Exception;
  468. if (e != null)
  469. throw e;
  470. return result.WriteStream;
  471. }
  472. public override Stream GetRequestStream()
  473. {
  474. IAsyncResult asyncResult = BeginGetRequestStream (null, null);
  475. asyncWrite = (WebAsyncResult) asyncResult;
  476. if (!asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
  477. Abort ();
  478. throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
  479. }
  480. return EndGetRequestStream (asyncResult);
  481. }
  482. public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
  483. {
  484. bool send = (method == "PUT" || method == "POST");
  485. if (send) {
  486. if ((!KeepAlive || (ContentLength == -1 && !SendChunked)) && !AllowWriteStreamBuffering)
  487. throw new ProtocolViolationException ("Content-Length not set");
  488. }
  489. CommonChecks (send);
  490. Monitor.Enter (this);
  491. if (asyncRead != null && !haveResponse) {
  492. Monitor.Exit (this);
  493. throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
  494. "method while a previous call is still in progress.");
  495. }
  496. asyncRead = new WebAsyncResult (this, callback, state);
  497. initialMethod = method;
  498. if (haveResponse) {
  499. if (webResponse != null) {
  500. Monitor.Exit (this);
  501. asyncRead.SetCompleted (true, webResponse);
  502. asyncRead.DoCallback ();
  503. return asyncRead;
  504. }
  505. }
  506. if (!requestSent) {
  507. requestSent = true;
  508. servicePoint = GetServicePoint ();
  509. abortHandler = servicePoint.SendRequest (this, connectionGroup);
  510. }
  511. Monitor.Exit (this);
  512. return asyncRead;
  513. }
  514. public override WebResponse EndGetResponse (IAsyncResult asyncResult)
  515. {
  516. if (asyncResult == null)
  517. throw new ArgumentNullException ("asyncResult");
  518. WebAsyncResult result = asyncResult as WebAsyncResult;
  519. if (result == null)
  520. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  521. redirects = 0;
  522. bool redirected = false;
  523. asyncRead = result;
  524. do {
  525. if (redirected) {
  526. haveResponse = false;
  527. result.Reset ();
  528. servicePoint = GetServicePoint ();
  529. abortHandler = servicePoint.SendRequest (this, connectionGroup);
  530. }
  531. if (!result.WaitUntilComplete (timeout, false)) {
  532. Abort ();
  533. throw new WebException("The request timed out", WebExceptionStatus.Timeout);
  534. }
  535. redirected = CheckFinalStatus (result);
  536. } while (redirected);
  537. return result.Response;
  538. }
  539. public override WebResponse GetResponse()
  540. {
  541. if (haveResponse && webResponse != null)
  542. return webResponse;
  543. WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
  544. return EndGetResponse (result);
  545. }
  546. public override void Abort ()
  547. {
  548. haveResponse = true;
  549. aborted = true;
  550. if (asyncWrite != null) {
  551. WebAsyncResult r = asyncWrite;
  552. WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
  553. r.SetCompleted (false, wexc);
  554. r.DoCallback ();
  555. asyncWrite = null;
  556. }
  557. if (asyncRead != null) {
  558. WebAsyncResult r = asyncRead;
  559. WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
  560. r.SetCompleted (false, wexc);
  561. r.DoCallback ();
  562. asyncRead = null;
  563. }
  564. if (abortHandler != null) {
  565. try {
  566. abortHandler (this, EventArgs.Empty);
  567. } catch {}
  568. abortHandler = null;
  569. }
  570. if (writeStream != null) {
  571. try {
  572. writeStream.Close ();
  573. writeStream = null;
  574. } catch {}
  575. }
  576. if (webResponse != null) {
  577. try {
  578. webResponse.Close ();
  579. webResponse = null;
  580. } catch {}
  581. }
  582. }
  583. void ISerializable.GetObjectData (SerializationInfo serializationInfo,
  584. StreamingContext streamingContext)
  585. {
  586. SerializationInfo info = serializationInfo;
  587. info.AddValue ("requestUri", requestUri, typeof (Uri));
  588. info.AddValue ("actualUri", actualUri, typeof (Uri));
  589. info.AddValue ("allowAutoRedirect", allowAutoRedirect);
  590. info.AddValue ("allowBuffering", allowBuffering);
  591. info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
  592. info.AddValue ("connectionGroup", connectionGroup);
  593. info.AddValue ("contentLength", contentLength);
  594. info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
  595. info.AddValue ("keepAlive", keepAlive);
  596. info.AddValue ("maxAutoRedirect", maxAutoRedirect);
  597. info.AddValue ("mediaType", mediaType);
  598. info.AddValue ("method", method);
  599. info.AddValue ("initialMethod", initialMethod);
  600. info.AddValue ("pipelined", pipelined);
  601. info.AddValue ("version", version, typeof (Version));
  602. info.AddValue ("proxy", proxy, typeof (IWebProxy));
  603. info.AddValue ("sendChunked", sendChunked);
  604. info.AddValue ("timeout", timeout);
  605. info.AddValue ("redirects", redirects);
  606. }
  607. void CheckRequestStarted ()
  608. {
  609. if (requestSent)
  610. throw new InvalidOperationException ("request started");
  611. }
  612. internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
  613. {
  614. if (continueDelegate != null)
  615. continueDelegate (statusCode, headers);
  616. }
  617. bool Redirect (WebAsyncResult result, HttpStatusCode code)
  618. {
  619. redirects++;
  620. Exception e = null;
  621. string uriString = null;
  622. switch (code) {
  623. case HttpStatusCode.Ambiguous: // 300
  624. e = new WebException ("Ambiguous redirect.");
  625. break;
  626. case HttpStatusCode.MovedPermanently: // 301
  627. case HttpStatusCode.Redirect: // 302
  628. case HttpStatusCode.TemporaryRedirect: // 307
  629. if (method != "GET" && method != "HEAD") // 10.3
  630. return false;
  631. uriString = webResponse.Headers ["Location"];
  632. break;
  633. case HttpStatusCode.SeeOther: //303
  634. method = "GET";
  635. uriString = webResponse.Headers ["Location"];
  636. break;
  637. case HttpStatusCode.NotModified: // 304
  638. return false;
  639. case HttpStatusCode.UseProxy: // 305
  640. e = new NotImplementedException ("Proxy support not available.");
  641. break;
  642. case HttpStatusCode.Unused: // 306
  643. default:
  644. e = new ProtocolViolationException ("Invalid status code: " + (int) code);
  645. break;
  646. }
  647. if (e != null)
  648. throw e;
  649. string host = actualUri.Host;
  650. actualUri = new Uri (uriString);
  651. hostChanged = (actualUri.Host != host);
  652. return true;
  653. }
  654. string GetHeaders ()
  655. {
  656. StringBuilder result = new StringBuilder ();
  657. bool continue100 = false;
  658. if (gotRequestStream && contentLength != -1) {
  659. continue100 = true;
  660. webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
  661. } else if (sendChunked) {
  662. continue100 = true;
  663. webHeaders.SetInternal ("Transfer-Encoding", "chunked");
  664. }
  665. if (continue100 && servicePoint.SendContinue) { // RFC2616 8.2.3
  666. webHeaders.SetInternal ("Expect" , "100-continue");
  667. expectContinue = true;
  668. } else {
  669. expectContinue = false;
  670. }
  671. string connectionHeader = (ProxyQuery) ? "Proxy-Connection" : "Connection";
  672. webHeaders.RemoveInternal ((!ProxyQuery) ? "Proxy-Connection" : "Connection");
  673. if (keepAlive && version == HttpVersion.Version10) {
  674. webHeaders.SetInternal (connectionHeader, "keep-alive");
  675. } else if (!keepAlive && version == HttpVersion.Version11) {
  676. webHeaders.SetInternal (connectionHeader, "close");
  677. }
  678. webHeaders.SetInternal ("Host", actualUri.Host);
  679. if (cookieContainer != null) {
  680. string cookieHeader = cookieContainer.GetCookieHeader (requestUri);
  681. if (cookieHeader != "")
  682. webHeaders.SetInternal ("Cookie", cookieHeader);
  683. }
  684. return webHeaders.ToString ();
  685. }
  686. internal void SetWriteStreamError (WebExceptionStatus status)
  687. {
  688. if (aborted)
  689. return;
  690. WebAsyncResult r = asyncWrite;
  691. if (r == null)
  692. r = asyncRead;
  693. if (r != null) {
  694. r.SetCompleted (false, new WebException ("Error: " + status, status));
  695. r.DoCallback ();
  696. }
  697. }
  698. internal void SendRequestHeaders ()
  699. {
  700. StringBuilder req = new StringBuilder ();
  701. string query;
  702. if (!ProxyQuery) {
  703. query = actualUri.PathAndQuery;
  704. } else if (actualUri.IsDefaultPort) {
  705. query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
  706. actualUri.Host,
  707. actualUri.PathAndQuery);
  708. } else {
  709. query = String.Format ("{0}://{1}:{2}{3}", actualUri.Scheme,
  710. actualUri.Host,
  711. actualUri.Port,
  712. actualUri.PathAndQuery);
  713. }
  714. req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query, version.Major, version.Minor);
  715. req.Append (GetHeaders ());
  716. string reqstr = req.ToString ();
  717. byte [] bytes = Encoding.UTF8.GetBytes (reqstr);
  718. writeStream.SetHeaders (bytes, 0, bytes.Length);
  719. }
  720. internal void SetWriteStream (WebConnectionStream stream)
  721. {
  722. if (aborted)
  723. return;
  724. writeStream = stream;
  725. SendRequestHeaders ();
  726. haveRequest = true;
  727. if (asyncWrite != null) {
  728. asyncWrite.SetCompleted (false, stream);
  729. asyncWrite.DoCallback ();
  730. asyncWrite = null;
  731. }
  732. }
  733. internal void SetResponseError (WebExceptionStatus status, Exception e)
  734. {
  735. WebAsyncResult r = asyncRead;
  736. if (r == null)
  737. r = asyncWrite;
  738. if (r != null) {
  739. WebException wexc = new WebException ("Error getting response stream", e, status, null);
  740. r.SetCompleted (false, wexc);
  741. r.DoCallback ();
  742. asyncRead = null;
  743. asyncWrite = null;
  744. }
  745. }
  746. internal void SetResponseData (WebConnectionData data)
  747. {
  748. if (aborted) {
  749. if (data.stream != null)
  750. data.stream.Close ();
  751. return;
  752. }
  753. webResponse = new HttpWebResponse (actualUri, method, data, (cookieContainer != null));
  754. haveResponse = true;
  755. WebAsyncResult r = asyncRead;
  756. if (r != null) {
  757. r.SetCompleted (false, webResponse);
  758. r.DoCallback ();
  759. }
  760. }
  761. bool CheckAuthorization (WebResponse response)
  762. {
  763. if (credentials == null)
  764. return false;
  765. string authHeader = response.Headers [AuthRequestHeader];
  766. if (authHeader == null)
  767. return false;
  768. Authorization auth = AuthenticationManager.Authenticate (authHeader, this, credentials);
  769. if (auth == null)
  770. return false;
  771. webHeaders [AuthResponseHeader] = auth.Message;
  772. return true;
  773. }
  774. // Returns true if redirected
  775. bool CheckFinalStatus (WebAsyncResult result)
  776. {
  777. if (result.GotException)
  778. throw result.Exception;
  779. Exception throwMe = result.Exception;
  780. HttpWebResponse resp = result.Response;
  781. WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
  782. HttpStatusCode code = 0;
  783. if (throwMe == null && webResponse != null) {
  784. code = webResponse.StatusCode;
  785. if (!triedAuth && code == HttpStatusCode.Unauthorized && credentials != null) {
  786. // TODO: Proxy not supported yet.
  787. // || code == HttpStatuscode.ProxyAuthenticationRequired)
  788. triedAuth = CheckAuthorization (webResponse);
  789. if (triedAuth)
  790. return true;
  791. }
  792. if ((int) code >= 400) {
  793. string err = String.Format ("The remote server returned an error: ({0}) {1}.",
  794. (int) code, webResponse.StatusDescription);
  795. throwMe = new WebException (err, null, protoError, webResponse);
  796. } else if ((int) code == 304 && allowAutoRedirect) {
  797. string err = String.Format ("The remote server returned an error: ({0}) {1}.",
  798. (int) code, webResponse.StatusDescription);
  799. throwMe = new WebException (err, null, protoError, webResponse);
  800. } else if ((int) code >= 300 && allowAutoRedirect && redirects > maxAutoRedirect) {
  801. throwMe = new WebException ("Max. redirections exceeded.", null,
  802. protoError, webResponse);
  803. }
  804. }
  805. if (throwMe == null) {
  806. bool b = false;
  807. if (allowAutoRedirect && (int) code >= 300)
  808. b = Redirect (result, code);
  809. return b;
  810. }
  811. if (writeStream != null) {
  812. writeStream.InternalClose ();
  813. writeStream = null;
  814. }
  815. if (webResponse != null)
  816. webResponse = null;
  817. throw throwMe;
  818. }
  819. }
  820. }