HttpWebRequest.cs 25 KB

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