HttpWebRequest.cs 31 KB

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