HttpWebRequest.cs 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  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. byte[] bodyBuffer;
  63. int bodyBufferLength;
  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. #if NET_1_1
  343. [MonoTODO]
  344. public bool UnsafeAuthenticatedConnectionSharing
  345. {
  346. get { throw new NotImplementedException (); }
  347. set { throw new NotImplementedException (); }
  348. }
  349. #endif
  350. internal bool GotRequestStream {
  351. get { return gotRequestStream; }
  352. }
  353. internal bool ExpectContinue {
  354. get { return expectContinue; }
  355. set { expectContinue = value; }
  356. }
  357. internal Uri AuthUri {
  358. get { return actualUri; }
  359. }
  360. internal bool ProxyQuery {
  361. get { return servicePoint.UsesProxy; }
  362. }
  363. // Methods
  364. internal ServicePoint GetServicePoint ()
  365. {
  366. if (!hostChanged && servicePoint != null)
  367. return servicePoint;
  368. lock (this) {
  369. if (hostChanged || servicePoint == null) {
  370. servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
  371. hostChanged = false;
  372. }
  373. }
  374. return servicePoint;
  375. }
  376. public void AddRange (int range)
  377. {
  378. AddRange ("bytes", range);
  379. }
  380. public void AddRange (int from, int to)
  381. {
  382. AddRange ("bytes", from, to);
  383. }
  384. public void AddRange (string rangeSpecifier, int range)
  385. {
  386. if (rangeSpecifier == null)
  387. throw new ArgumentNullException ("rangeSpecifier");
  388. string value = webHeaders ["Range"];
  389. if (value == null || value.Length == 0)
  390. value = rangeSpecifier + "=";
  391. else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
  392. value += ",";
  393. else
  394. throw new InvalidOperationException ("rangeSpecifier");
  395. webHeaders.SetInternal ("Range", value + range + "-");
  396. }
  397. public void AddRange (string rangeSpecifier, int from, int to)
  398. {
  399. if (rangeSpecifier == null)
  400. throw new ArgumentNullException ("rangeSpecifier");
  401. if (from < 0 || to < 0 || from > to)
  402. throw new ArgumentOutOfRangeException ();
  403. string value = webHeaders ["Range"];
  404. if (value == null || value.Length == 0)
  405. value = rangeSpecifier + "=";
  406. else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
  407. value += ",";
  408. else
  409. throw new InvalidOperationException ("rangeSpecifier");
  410. webHeaders.SetInternal ("Range", value + from + "-" + to);
  411. }
  412. public override int GetHashCode ()
  413. {
  414. return base.GetHashCode ();
  415. }
  416. void CommonChecks (bool putpost)
  417. {
  418. if (method == null)
  419. throw new ProtocolViolationException ("Method is null.");
  420. if (putpost && ((!keepAlive || (contentLength == -1 && !sendChunked)) && !allowBuffering))
  421. throw new ProtocolViolationException ("Content-Length not set");
  422. string transferEncoding = TransferEncoding;
  423. if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
  424. throw new ProtocolViolationException ("SendChunked should be true.");
  425. }
  426. public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
  427. {
  428. if (aborted)
  429. throw new WebException ("The request was previosly aborted.");
  430. bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD");
  431. if (method == null || !send)
  432. throw new ProtocolViolationException ("Cannot send data when method is: " + method);
  433. CommonChecks (send);
  434. Monitor.Enter (this);
  435. if (asyncWrite != null) {
  436. Monitor.Exit (this);
  437. throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
  438. "method while a previous call is still in progress.");
  439. }
  440. asyncWrite = new WebAsyncResult (this, callback, state);
  441. initialMethod = method;
  442. if (haveRequest) {
  443. if (writeStream != null) {
  444. Monitor.Exit (this);
  445. asyncWrite.SetCompleted (true, writeStream);
  446. asyncWrite.DoCallback ();
  447. return asyncWrite;
  448. }
  449. }
  450. gotRequestStream = true;
  451. WebAsyncResult result = asyncWrite;
  452. if (!requestSent) {
  453. requestSent = true;
  454. servicePoint = GetServicePoint ();
  455. abortHandler = servicePoint.SendRequest (this, connectionGroup);
  456. }
  457. Monitor.Exit (this);
  458. return result;
  459. }
  460. public override Stream EndGetRequestStream (IAsyncResult asyncResult)
  461. {
  462. if (asyncResult == null)
  463. throw new ArgumentNullException ("asyncResult");
  464. WebAsyncResult result = asyncResult as WebAsyncResult;
  465. if (result == null)
  466. throw new ArgumentException ("Invalid IAsyncResult");
  467. asyncWrite = result;
  468. result.WaitUntilComplete ();
  469. Exception e = result.Exception;
  470. if (e != null)
  471. throw e;
  472. return result.WriteStream;
  473. }
  474. public override Stream GetRequestStream()
  475. {
  476. IAsyncResult asyncResult = BeginGetRequestStream (null, null);
  477. asyncWrite = (WebAsyncResult) asyncResult;
  478. if (!asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
  479. Abort ();
  480. throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
  481. }
  482. return EndGetRequestStream (asyncResult);
  483. }
  484. public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
  485. {
  486. bool send = (method == "PUT" || method == "POST");
  487. if (send) {
  488. if ((!KeepAlive || (ContentLength == -1 && !SendChunked)) && !AllowWriteStreamBuffering)
  489. throw new ProtocolViolationException ("Content-Length not set");
  490. }
  491. CommonChecks (send);
  492. Monitor.Enter (this);
  493. if (asyncRead != null && !haveResponse) {
  494. Monitor.Exit (this);
  495. throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
  496. "method while a previous call is still in progress.");
  497. }
  498. asyncRead = new WebAsyncResult (this, callback, state);
  499. initialMethod = method;
  500. if (haveResponse) {
  501. if (webResponse != null) {
  502. Monitor.Exit (this);
  503. asyncRead.SetCompleted (true, webResponse);
  504. asyncRead.DoCallback ();
  505. return asyncRead;
  506. }
  507. }
  508. if (!requestSent) {
  509. requestSent = true;
  510. servicePoint = GetServicePoint ();
  511. abortHandler = servicePoint.SendRequest (this, connectionGroup);
  512. }
  513. Monitor.Exit (this);
  514. return asyncRead;
  515. }
  516. public override WebResponse EndGetResponse (IAsyncResult asyncResult)
  517. {
  518. if (asyncResult == null)
  519. throw new ArgumentNullException ("asyncResult");
  520. WebAsyncResult result = asyncResult as WebAsyncResult;
  521. if (result == null)
  522. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  523. redirects = 0;
  524. bool redirected = false;
  525. asyncRead = result;
  526. do {
  527. if (redirected) {
  528. haveResponse = false;
  529. result.Reset ();
  530. servicePoint = GetServicePoint ();
  531. abortHandler = servicePoint.SendRequest (this, connectionGroup);
  532. }
  533. if (!result.WaitUntilComplete (timeout, false)) {
  534. Abort ();
  535. throw new WebException("The request timed out", WebExceptionStatus.Timeout);
  536. }
  537. redirected = CheckFinalStatus (result);
  538. } while (redirected);
  539. return result.Response;
  540. }
  541. public override WebResponse GetResponse()
  542. {
  543. if (haveResponse && webResponse != null)
  544. return webResponse;
  545. WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
  546. return EndGetResponse (result);
  547. }
  548. public override void Abort ()
  549. {
  550. haveResponse = true;
  551. aborted = true;
  552. if (asyncWrite != null) {
  553. WebAsyncResult r = asyncWrite;
  554. WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
  555. r.SetCompleted (false, wexc);
  556. r.DoCallback ();
  557. asyncWrite = null;
  558. }
  559. if (asyncRead != null) {
  560. WebAsyncResult r = asyncRead;
  561. WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
  562. r.SetCompleted (false, wexc);
  563. r.DoCallback ();
  564. asyncRead = null;
  565. }
  566. if (abortHandler != null) {
  567. try {
  568. abortHandler (this, EventArgs.Empty);
  569. } catch {}
  570. abortHandler = null;
  571. }
  572. if (writeStream != null) {
  573. try {
  574. writeStream.Close ();
  575. writeStream = null;
  576. } catch {}
  577. }
  578. if (webResponse != null) {
  579. try {
  580. webResponse.Close ();
  581. webResponse = null;
  582. } catch {}
  583. }
  584. }
  585. void ISerializable.GetObjectData (SerializationInfo serializationInfo,
  586. StreamingContext streamingContext)
  587. {
  588. SerializationInfo info = serializationInfo;
  589. info.AddValue ("requestUri", requestUri, typeof (Uri));
  590. info.AddValue ("actualUri", actualUri, typeof (Uri));
  591. info.AddValue ("allowAutoRedirect", allowAutoRedirect);
  592. info.AddValue ("allowBuffering", allowBuffering);
  593. info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
  594. info.AddValue ("connectionGroup", connectionGroup);
  595. info.AddValue ("contentLength", contentLength);
  596. info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
  597. info.AddValue ("keepAlive", keepAlive);
  598. info.AddValue ("maxAutoRedirect", maxAutoRedirect);
  599. info.AddValue ("mediaType", mediaType);
  600. info.AddValue ("method", method);
  601. info.AddValue ("initialMethod", initialMethod);
  602. info.AddValue ("pipelined", pipelined);
  603. info.AddValue ("version", version, typeof (Version));
  604. info.AddValue ("proxy", proxy, typeof (IWebProxy));
  605. info.AddValue ("sendChunked", sendChunked);
  606. info.AddValue ("timeout", timeout);
  607. info.AddValue ("redirects", redirects);
  608. }
  609. void CheckRequestStarted ()
  610. {
  611. if (requestSent)
  612. throw new InvalidOperationException ("request started");
  613. }
  614. internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
  615. {
  616. if (continueDelegate != null)
  617. continueDelegate (statusCode, headers);
  618. }
  619. bool Redirect (WebAsyncResult result, HttpStatusCode code)
  620. {
  621. redirects++;
  622. Exception e = null;
  623. string uriString = null;
  624. switch (code) {
  625. case HttpStatusCode.Ambiguous: // 300
  626. e = new WebException ("Ambiguous redirect.");
  627. break;
  628. case HttpStatusCode.MovedPermanently: // 301
  629. case HttpStatusCode.Redirect: // 302
  630. case HttpStatusCode.TemporaryRedirect: // 307
  631. if (method != "GET" && method != "HEAD") // 10.3
  632. return false;
  633. uriString = webResponse.Headers ["Location"];
  634. break;
  635. case HttpStatusCode.SeeOther: //303
  636. method = "GET";
  637. uriString = webResponse.Headers ["Location"];
  638. break;
  639. case HttpStatusCode.NotModified: // 304
  640. return false;
  641. case HttpStatusCode.UseProxy: // 305
  642. e = new NotImplementedException ("Proxy support not available.");
  643. break;
  644. case HttpStatusCode.Unused: // 306
  645. default:
  646. e = new ProtocolViolationException ("Invalid status code: " + (int) code);
  647. break;
  648. }
  649. if (e != null)
  650. throw e;
  651. string host = actualUri.Host;
  652. actualUri = new Uri (actualUri, uriString);
  653. hostChanged = (actualUri.Host != host);
  654. return true;
  655. }
  656. string GetHeaders ()
  657. {
  658. bool continue100 = false;
  659. if (gotRequestStream && contentLength != -1) {
  660. continue100 = true;
  661. webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
  662. } else if (sendChunked) {
  663. continue100 = true;
  664. webHeaders.SetInternal ("Transfer-Encoding", "chunked");
  665. }
  666. if (version == HttpVersion.Version11 && continue100 &&
  667. servicePoint.SendContinue) { // RFC2616 8.2.3
  668. webHeaders.SetInternal ("Expect" , "100-continue");
  669. expectContinue = true;
  670. } else {
  671. expectContinue = false;
  672. }
  673. string connectionHeader = (ProxyQuery) ? "Proxy-Connection" : "Connection";
  674. webHeaders.RemoveInternal ((!ProxyQuery) ? "Proxy-Connection" : "Connection");
  675. if (keepAlive && version == HttpVersion.Version10) {
  676. webHeaders.SetInternal (connectionHeader, "keep-alive");
  677. } else if (!keepAlive && version == HttpVersion.Version11) {
  678. webHeaders.SetInternal (connectionHeader, "close");
  679. }
  680. webHeaders.SetInternal ("Host", actualUri.Host);
  681. if (cookieContainer != null) {
  682. string cookieHeader = cookieContainer.GetCookieHeader (requestUri);
  683. if (cookieHeader != "")
  684. webHeaders.SetInternal ("Cookie", cookieHeader);
  685. }
  686. return webHeaders.ToString ();
  687. }
  688. internal void SetWriteStreamError (WebExceptionStatus status)
  689. {
  690. if (aborted)
  691. return;
  692. WebAsyncResult r = asyncWrite;
  693. if (r == null)
  694. r = asyncRead;
  695. if (r != null) {
  696. r.SetCompleted (false, new WebException ("Error: " + status, status));
  697. r.DoCallback ();
  698. }
  699. }
  700. internal void SendRequestHeaders ()
  701. {
  702. StringBuilder req = new StringBuilder ();
  703. string query;
  704. if (!ProxyQuery) {
  705. query = actualUri.PathAndQuery;
  706. } else if (actualUri.IsDefaultPort) {
  707. query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
  708. actualUri.Host,
  709. actualUri.PathAndQuery);
  710. } else {
  711. query = String.Format ("{0}://{1}:{2}{3}", actualUri.Scheme,
  712. actualUri.Host,
  713. actualUri.Port,
  714. actualUri.PathAndQuery);
  715. }
  716. req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query, version.Major, version.Minor);
  717. req.Append (GetHeaders ());
  718. string reqstr = req.ToString ();
  719. byte [] bytes = Encoding.UTF8.GetBytes (reqstr);
  720. writeStream.SetHeaders (bytes, 0, bytes.Length);
  721. }
  722. internal void SetWriteStream (WebConnectionStream stream)
  723. {
  724. if (aborted)
  725. return;
  726. writeStream = stream;
  727. if (bodyBuffer != null) {
  728. webHeaders.RemoveInternal ("Transfer-Encoding");
  729. contentLength = bodyBuffer.Length;
  730. writeStream.SendChunked = false;
  731. }
  732. SendRequestHeaders ();
  733. haveRequest = true;
  734. if (bodyBuffer != null) {
  735. // The body has been written and buffered. The request "user"
  736. // won't write it again, so we must do it.
  737. writeStream.Write (bodyBuffer, 0, bodyBufferLength);
  738. bodyBuffer = null;
  739. writeStream.Close ();
  740. }
  741. if (asyncWrite != null) {
  742. asyncWrite.SetCompleted (false, stream);
  743. asyncWrite.DoCallback ();
  744. asyncWrite = null;
  745. }
  746. }
  747. internal void SetResponseError (WebExceptionStatus status, Exception e)
  748. {
  749. WebAsyncResult r = asyncRead;
  750. if (r == null)
  751. r = asyncWrite;
  752. if (r != null) {
  753. WebException wexc = new WebException ("Error getting response stream", e, status, null);
  754. r.SetCompleted (false, wexc);
  755. r.DoCallback ();
  756. asyncRead = null;
  757. asyncWrite = null;
  758. }
  759. }
  760. internal void SetResponseData (WebConnectionData data)
  761. {
  762. if (aborted) {
  763. if (data.stream != null)
  764. data.stream.Close ();
  765. return;
  766. }
  767. webResponse = new HttpWebResponse (actualUri, method, data, (cookieContainer != null));
  768. haveResponse = true;
  769. WebAsyncResult r = asyncRead;
  770. if (r != null) {
  771. r.SetCompleted (false, webResponse);
  772. r.DoCallback ();
  773. }
  774. }
  775. bool CheckAuthorization (WebResponse response, HttpStatusCode code)
  776. {
  777. authCompleted = false;
  778. if (code == HttpStatusCode.Unauthorized && credentials == null)
  779. return false;
  780. bool isProxy = (code == HttpStatusCode.ProxyAuthenticationRequired);
  781. if (isProxy && (proxy == null || proxy.Credentials == null))
  782. return false;
  783. string authHeader = response.Headers [(isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate"];
  784. if (authHeader == null)
  785. return false;
  786. ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
  787. Authorization auth = AuthenticationManager.Authenticate (authHeader, this, creds);
  788. if (auth == null)
  789. return false;
  790. webHeaders [(isProxy) ? "Proxy-Authorization" : "Authorization"] = auth.Message;
  791. authCompleted = auth.Complete;
  792. return true;
  793. }
  794. // Returns true if redirected
  795. bool CheckFinalStatus (WebAsyncResult result)
  796. {
  797. if (result.GotException)
  798. throw result.Exception;
  799. Exception throwMe = result.Exception;
  800. bodyBuffer = null;
  801. HttpWebResponse resp = result.Response;
  802. WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
  803. HttpStatusCode code = 0;
  804. if (throwMe == null && webResponse != null) {
  805. code = webResponse.StatusCode;
  806. if (!authCompleted && ((code == HttpStatusCode.Unauthorized && credentials != null) ||
  807. code == HttpStatusCode.ProxyAuthenticationRequired)) {
  808. if (CheckAuthorization (webResponse, code)) {
  809. // Keep the written body, so it can be rewritten in the retry
  810. if (allowBuffering) {
  811. bodyBuffer = writeStream.WriteBuffer;
  812. bodyBufferLength = writeStream.WriteBufferLength;
  813. return true;
  814. }
  815. writeStream.InternalClose ();
  816. writeStream = null;
  817. webResponse = null;
  818. throw new WebException ("This request requires buffering " +
  819. "of data for authentication or " +
  820. "redirection to be sucessful.");
  821. }
  822. }
  823. if ((int) code >= 400) {
  824. string err = String.Format ("The remote server returned an error: ({0}) {1}.",
  825. (int) code, webResponse.StatusDescription);
  826. throwMe = new WebException (err, null, protoError, webResponse);
  827. } else if ((int) code == 304 && allowAutoRedirect) {
  828. string err = String.Format ("The remote server returned an error: ({0}) {1}.",
  829. (int) code, webResponse.StatusDescription);
  830. throwMe = new WebException (err, null, protoError, webResponse);
  831. } else if ((int) code >= 300 && allowAutoRedirect && redirects > maxAutoRedirect) {
  832. throwMe = new WebException ("Max. redirections exceeded.", null,
  833. protoError, webResponse);
  834. }
  835. }
  836. if (throwMe == null) {
  837. bool b = false;
  838. if (allowAutoRedirect && (int) code >= 300)
  839. b = Redirect (result, code);
  840. return b;
  841. }
  842. if (writeStream != null) {
  843. writeStream.InternalClose ();
  844. writeStream = null;
  845. }
  846. if (webResponse != null)
  847. webResponse = null;
  848. throw throwMe;
  849. }
  850. }
  851. }