HttpWebRequest.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  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 sendChunked;
  50. ServicePoint servicePoint;
  51. int timeout = 100000;
  52. WebConnectionStream writeStream;
  53. HttpWebResponse webResponse;
  54. WebAsyncResult asyncWrite;
  55. WebAsyncResult asyncRead;
  56. EventHandler abortHandler;
  57. bool aborted;
  58. bool gotRequestStream;
  59. int redirects;
  60. bool expectContinue;
  61. bool authCompleted;
  62. // Constructors
  63. internal HttpWebRequest (Uri uri)
  64. {
  65. this.requestUri = uri;
  66. this.actualUri = uri;
  67. this.proxy = GlobalProxySelection.Select;
  68. }
  69. protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
  70. {
  71. SerializationInfo info = serializationInfo;
  72. requestUri = (Uri) info.GetValue ("requestUri", typeof (Uri));
  73. actualUri = (Uri) info.GetValue ("actualUri", typeof (Uri));
  74. allowAutoRedirect = info.GetBoolean ("allowAutoRedirect");
  75. allowBuffering = info.GetBoolean ("allowBuffering");
  76. certificates = (X509CertificateCollection) info.GetValue ("certificates", typeof (X509CertificateCollection));
  77. connectionGroup = info.GetString ("connectionGroup");
  78. contentLength = info.GetInt64 ("contentLength");
  79. webHeaders = (WebHeaderCollection) info.GetValue ("webHeaders", typeof (WebHeaderCollection));
  80. keepAlive = info.GetBoolean ("keepAlive");
  81. maxAutoRedirect = info.GetInt32 ("maxAutoRedirect");
  82. mediaType = info.GetString ("mediaType");
  83. method = info.GetString ("method");
  84. initialMethod = info.GetString ("initialMethod");
  85. pipelined = info.GetBoolean ("pipelined");
  86. version = (Version) info.GetValue ("version", typeof (Version));
  87. proxy = (IWebProxy) info.GetValue ("proxy", typeof (IWebProxy));
  88. sendChunked = info.GetBoolean ("sendChunked");
  89. timeout = info.GetInt32 ("timeout");
  90. redirects = info.GetInt32 ("redirects");
  91. }
  92. // Properties
  93. public string Accept {
  94. get { return webHeaders ["Accept"]; }
  95. set {
  96. CheckRequestStarted ();
  97. webHeaders.SetInternal ("Accept", value);
  98. }
  99. }
  100. public Uri Address {
  101. get { return actualUri; }
  102. }
  103. public bool AllowAutoRedirect {
  104. get { return allowAutoRedirect; }
  105. set { this.allowAutoRedirect = value; }
  106. }
  107. public bool AllowWriteStreamBuffering {
  108. get { return allowBuffering; }
  109. set { allowBuffering = value; }
  110. }
  111. internal bool InternalAllowBuffering {
  112. get {
  113. return (allowBuffering && (method == "PUT" || method == "POST"));
  114. }
  115. }
  116. public X509CertificateCollection ClientCertificates {
  117. get {
  118. if (certificates == null)
  119. certificates = new X509CertificateCollection ();
  120. return certificates;
  121. }
  122. }
  123. public string Connection {
  124. get { return webHeaders ["Connection"]; }
  125. set {
  126. CheckRequestStarted ();
  127. string val = value;
  128. if (val != null)
  129. val = val.Trim ().ToLower ();
  130. if (val == null || val.Length == 0) {
  131. webHeaders.RemoveInternal ("Connection");
  132. return;
  133. }
  134. if (val == "keep-alive" || val == "close")
  135. throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
  136. if (keepAlive && val.IndexOf ("keep-alive") == -1)
  137. value = value + ", Keep-Alive";
  138. webHeaders.SetInternal ("Connection", value);
  139. }
  140. }
  141. public override string ConnectionGroupName {
  142. get { return connectionGroup; }
  143. set { connectionGroup = value; }
  144. }
  145. public override long ContentLength {
  146. get { return contentLength; }
  147. set {
  148. CheckRequestStarted ();
  149. if (value < 0)
  150. throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
  151. contentLength = value;
  152. }
  153. }
  154. internal long InternalContentLength {
  155. set { contentLength = value; }
  156. }
  157. public override string ContentType {
  158. get { return webHeaders ["Content-Type"]; }
  159. set {
  160. CheckRequestStarted ();
  161. if (value == null || value.Trim().Length == 0) {
  162. webHeaders.RemoveInternal ("Content-Type");
  163. return;
  164. }
  165. webHeaders.SetInternal ("Content-Type", value);
  166. }
  167. }
  168. public HttpContinueDelegate ContinueDelegate {
  169. get { return continueDelegate; }
  170. set { continueDelegate = value; }
  171. }
  172. public CookieContainer CookieContainer {
  173. get { return cookieContainer; }
  174. set { cookieContainer = value; }
  175. }
  176. public override ICredentials Credentials {
  177. get { return credentials; }
  178. set { credentials = value; }
  179. }
  180. public string Expect {
  181. get { return webHeaders ["Expect"]; }
  182. set {
  183. CheckRequestStarted ();
  184. string val = value;
  185. if (val != null)
  186. val = val.Trim ().ToLower ();
  187. if (val == null || val.Length == 0) {
  188. webHeaders.RemoveInternal ("Expect");
  189. return;
  190. }
  191. if (val == "100-continue")
  192. throw new ArgumentException ("100-Continue cannot be set with this property.",
  193. "value");
  194. webHeaders.SetInternal ("Expect", value);
  195. }
  196. }
  197. public bool HaveResponse {
  198. get { return haveResponse; }
  199. }
  200. public override WebHeaderCollection Headers {
  201. get { return webHeaders; }
  202. set {
  203. CheckRequestStarted ();
  204. WebHeaderCollection newHeaders = new WebHeaderCollection (true);
  205. int count = value.Count;
  206. for (int i = 0; i < count; i++)
  207. newHeaders.Add (value.GetKey (i), value.Get (i));
  208. webHeaders = newHeaders;
  209. }
  210. }
  211. public DateTime IfModifiedSince {
  212. get {
  213. string str = webHeaders ["If-Modified-Since"];
  214. if (str == null)
  215. return DateTime.Now;
  216. try {
  217. return MonoHttpDate.Parse (str);
  218. } catch (Exception) {
  219. return DateTime.Now;
  220. }
  221. }
  222. set {
  223. CheckRequestStarted ();
  224. // rfc-1123 pattern
  225. webHeaders.SetInternal ("If-Modified-Since",
  226. value.ToUniversalTime ().ToString ("r", null));
  227. // TODO: check last param when using different locale
  228. }
  229. }
  230. public bool KeepAlive {
  231. get {
  232. return keepAlive;
  233. }
  234. set {
  235. keepAlive = value;
  236. }
  237. }
  238. public int MaximumAutomaticRedirections {
  239. get { return maxAutoRedirect; }
  240. set {
  241. if (value <= 0)
  242. throw new ArgumentException ("Must be > 0", "value");
  243. maxAutoRedirect = value;
  244. }
  245. }
  246. public string MediaType {
  247. get { return mediaType; }
  248. set {
  249. mediaType = value;
  250. }
  251. }
  252. public override string Method {
  253. get { return this.method; }
  254. set {
  255. if (value == null || value.Trim () == "")
  256. throw new ArgumentException ("not a valid method");
  257. method = value;
  258. }
  259. }
  260. public bool Pipelined {
  261. get { return pipelined; }
  262. set { pipelined = value; }
  263. }
  264. public override bool PreAuthenticate {
  265. get { return preAuthenticate; } //TODO: support preauthentication
  266. set { preAuthenticate = value; }
  267. }
  268. public Version ProtocolVersion {
  269. get { return version; }
  270. set {
  271. if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
  272. throw new ArgumentException ("value");
  273. version = value;
  274. }
  275. }
  276. public override IWebProxy Proxy {
  277. get { return proxy; }
  278. set {
  279. CheckRequestStarted ();
  280. if (value == null)
  281. throw new ArgumentNullException ("value");
  282. proxy = value;
  283. servicePoint = null; // we may need a new one
  284. }
  285. }
  286. public string Referer {
  287. get { return webHeaders ["Referer"]; }
  288. set {
  289. CheckRequestStarted ();
  290. if (value == null || value.Trim().Length == 0) {
  291. webHeaders.RemoveInternal ("Referer");
  292. return;
  293. }
  294. webHeaders.SetInternal ("Referer", value);
  295. }
  296. }
  297. public override Uri RequestUri {
  298. get { return requestUri; }
  299. }
  300. public bool SendChunked {
  301. get { return sendChunked; }
  302. set {
  303. CheckRequestStarted ();
  304. sendChunked = value;
  305. }
  306. }
  307. public ServicePoint ServicePoint {
  308. get { return GetServicePoint (); }
  309. }
  310. public override int Timeout {
  311. get { return timeout; }
  312. set {
  313. if (value < -1)
  314. throw new ArgumentOutOfRangeException ("value");
  315. timeout = value;
  316. }
  317. }
  318. public string TransferEncoding {
  319. get { return webHeaders ["Transfer-Encoding"]; }
  320. set {
  321. CheckRequestStarted ();
  322. string val = value;
  323. if (val != null)
  324. val = val.Trim ().ToLower ();
  325. if (val == null || val.Length == 0) {
  326. webHeaders.RemoveInternal ("Transfer-Encoding");
  327. return;
  328. }
  329. if (val == "chunked")
  330. throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
  331. if (!sendChunked)
  332. throw new ArgumentException ("SendChunked must be True", "value");
  333. webHeaders.SetInternal ("Transfer-Encoding", value);
  334. }
  335. }
  336. public string UserAgent {
  337. get { return webHeaders ["User-Agent"]; }
  338. set { webHeaders.SetInternal ("User-Agent", value); }
  339. }
  340. #if NET_1_1
  341. [MonoTODO]
  342. public bool UnsafeAuthenticatedConnectionSharing
  343. {
  344. get { throw new NotImplementedException (); }
  345. set { throw new NotImplementedException (); }
  346. }
  347. #endif
  348. internal bool GotRequestStream {
  349. get { return gotRequestStream; }
  350. }
  351. internal bool ExpectContinue {
  352. get { return expectContinue; }
  353. set { expectContinue = value; }
  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 == "GET" || method == "CONNECT" || method == "HEAD");
  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 (actualUri, uriString);
  651. hostChanged = (actualUri.Host != host);
  652. return true;
  653. }
  654. string GetHeaders ()
  655. {
  656. bool continue100 = false;
  657. if (gotRequestStream && contentLength != -1) {
  658. continue100 = true;
  659. webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
  660. } else if (sendChunked) {
  661. continue100 = true;
  662. webHeaders.SetInternal ("Transfer-Encoding", "chunked");
  663. }
  664. if (continue100 && servicePoint.SendContinue) { // RFC2616 8.2.3
  665. webHeaders.SetInternal ("Expect" , "100-continue");
  666. expectContinue = true;
  667. } else {
  668. expectContinue = false;
  669. }
  670. string connectionHeader = (ProxyQuery) ? "Proxy-Connection" : "Connection";
  671. webHeaders.RemoveInternal ((!ProxyQuery) ? "Proxy-Connection" : "Connection");
  672. if (keepAlive && version == HttpVersion.Version10) {
  673. webHeaders.SetInternal (connectionHeader, "keep-alive");
  674. } else if (!keepAlive && version == HttpVersion.Version11) {
  675. webHeaders.SetInternal (connectionHeader, "close");
  676. }
  677. webHeaders.SetInternal ("Host", actualUri.Host);
  678. if (cookieContainer != null) {
  679. string cookieHeader = cookieContainer.GetCookieHeader (requestUri);
  680. if (cookieHeader != "")
  681. webHeaders.SetInternal ("Cookie", cookieHeader);
  682. }
  683. return webHeaders.ToString ();
  684. }
  685. internal void SetWriteStreamError (WebExceptionStatus status)
  686. {
  687. if (aborted)
  688. return;
  689. WebAsyncResult r = asyncWrite;
  690. if (r == null)
  691. r = asyncRead;
  692. if (r != null) {
  693. r.SetCompleted (false, new WebException ("Error: " + status, status));
  694. r.DoCallback ();
  695. }
  696. }
  697. internal void SendRequestHeaders ()
  698. {
  699. StringBuilder req = new StringBuilder ();
  700. string query;
  701. if (!ProxyQuery) {
  702. query = actualUri.PathAndQuery;
  703. } else if (actualUri.IsDefaultPort) {
  704. query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
  705. actualUri.Host,
  706. actualUri.PathAndQuery);
  707. } else {
  708. query = String.Format ("{0}://{1}:{2}{3}", actualUri.Scheme,
  709. actualUri.Host,
  710. actualUri.Port,
  711. actualUri.PathAndQuery);
  712. }
  713. req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query, version.Major, version.Minor);
  714. req.Append (GetHeaders ());
  715. string reqstr = req.ToString ();
  716. byte [] bytes = Encoding.UTF8.GetBytes (reqstr);
  717. writeStream.SetHeaders (bytes, 0, bytes.Length);
  718. }
  719. internal void SetWriteStream (WebConnectionStream stream)
  720. {
  721. if (aborted)
  722. return;
  723. writeStream = stream;
  724. SendRequestHeaders ();
  725. haveRequest = true;
  726. if (asyncWrite != null) {
  727. asyncWrite.SetCompleted (false, stream);
  728. asyncWrite.DoCallback ();
  729. asyncWrite = null;
  730. }
  731. }
  732. internal void SetResponseError (WebExceptionStatus status, Exception e)
  733. {
  734. WebAsyncResult r = asyncRead;
  735. if (r == null)
  736. r = asyncWrite;
  737. if (r != null) {
  738. WebException wexc = new WebException ("Error getting response stream", e, status, null);
  739. r.SetCompleted (false, wexc);
  740. r.DoCallback ();
  741. asyncRead = null;
  742. asyncWrite = null;
  743. }
  744. }
  745. internal void SetResponseData (WebConnectionData data)
  746. {
  747. if (aborted) {
  748. if (data.stream != null)
  749. data.stream.Close ();
  750. return;
  751. }
  752. webResponse = new HttpWebResponse (actualUri, method, data, (cookieContainer != null));
  753. haveResponse = true;
  754. WebAsyncResult r = asyncRead;
  755. if (r != null) {
  756. r.SetCompleted (false, webResponse);
  757. r.DoCallback ();
  758. }
  759. }
  760. bool CheckAuthorization (WebResponse response, HttpStatusCode code)
  761. {
  762. authCompleted = false;
  763. if (code == HttpStatusCode.Unauthorized && credentials == null)
  764. return false;
  765. bool isProxy = (code == HttpStatusCode.ProxyAuthenticationRequired);
  766. if (isProxy && (proxy == null || proxy.Credentials == null))
  767. return false;
  768. string authHeader = response.Headers [(isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate"];
  769. if (authHeader == null)
  770. return false;
  771. ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
  772. Authorization auth = AuthenticationManager.Authenticate (authHeader, this, creds);
  773. if (auth == null)
  774. return false;
  775. webHeaders [(isProxy) ? "Proxy-Authorization" : "Authorization"] = auth.Message;
  776. authCompleted = auth.Complete;
  777. return true;
  778. }
  779. // Returns true if redirected
  780. bool CheckFinalStatus (WebAsyncResult result)
  781. {
  782. if (result.GotException)
  783. throw result.Exception;
  784. Exception throwMe = result.Exception;
  785. HttpWebResponse resp = result.Response;
  786. WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
  787. HttpStatusCode code = 0;
  788. if (throwMe == null && webResponse != null) {
  789. code = webResponse.StatusCode;
  790. if (!authCompleted && ((code == HttpStatusCode.Unauthorized && credentials != null) ||
  791. code == HttpStatusCode.ProxyAuthenticationRequired)) {
  792. if (CheckAuthorization (webResponse, code))
  793. return true;
  794. }
  795. if ((int) code >= 400) {
  796. string err = String.Format ("The remote server returned an error: ({0}) {1}.",
  797. (int) code, webResponse.StatusDescription);
  798. throwMe = new WebException (err, null, protoError, webResponse);
  799. } else if ((int) code == 304 && allowAutoRedirect) {
  800. string err = String.Format ("The remote server returned an error: ({0}) {1}.",
  801. (int) code, webResponse.StatusDescription);
  802. throwMe = new WebException (err, null, protoError, webResponse);
  803. } else if ((int) code >= 300 && allowAutoRedirect && redirects > maxAutoRedirect) {
  804. throwMe = new WebException ("Max. redirections exceeded.", null,
  805. protoError, webResponse);
  806. }
  807. }
  808. if (throwMe == null) {
  809. bool b = false;
  810. if (allowAutoRedirect && (int) code >= 300)
  811. b = Redirect (result, code);
  812. return b;
  813. }
  814. if (writeStream != null) {
  815. writeStream.InternalClose ();
  816. writeStream = null;
  817. }
  818. if (webResponse != null)
  819. webResponse = null;
  820. throw throwMe;
  821. }
  822. }
  823. }