HttpWebRequest.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  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, IDisposable
  24. {
  25. private Uri requestUri;
  26. private Uri actualUri = null;
  27. private bool allowAutoRedirect = true;
  28. private bool allowBuffering = true;
  29. private X509CertificateCollection certificate = null;
  30. private string connectionGroup = null;
  31. private long contentLength = -1;
  32. private HttpContinueDelegate continueDelegate = null;
  33. private CookieContainer cookieContainer = null;
  34. private ICredentials credentials = null;
  35. private bool haveResponse = false;
  36. private WebHeaderCollection webHeaders;
  37. private bool keepAlive = true;
  38. private int maxAutoRedirect = 50;
  39. private string mediaType = String.Empty;
  40. private string method;
  41. private bool pipelined = true;
  42. private bool preAuthenticate = false;
  43. private Version version;
  44. private IWebProxy proxy;
  45. private bool sendChunked = false;
  46. private ServicePoint servicePoint = null;
  47. private int timeout = System.Threading.Timeout.Infinite;
  48. private HttpWebRequestStream requestStream = null;
  49. private HttpWebResponse webResponse = null;
  50. private AutoResetEvent requestEndEvent = null;
  51. private bool requesting = false;
  52. private bool asyncResponding = false;
  53. private Socket socket;
  54. private bool requestClosed = false;
  55. private bool responseClosed = false;
  56. private bool disposed;
  57. // Constructors
  58. internal HttpWebRequest (Uri uri)
  59. {
  60. this.requestUri = uri;
  61. this.actualUri = uri;
  62. this.webHeaders = new WebHeaderCollection (true);
  63. this.webHeaders.SetInternal ("Host", uri.Authority);
  64. this.webHeaders.SetInternal ("Date", DateTime.Now.ToUniversalTime ().ToString ("r", null));
  65. this.webHeaders.SetInternal ("Expect", "100-continue");
  66. this.method = "GET";
  67. this.version = HttpVersion.Version11;
  68. this.proxy = GlobalProxySelection.Select;
  69. }
  70. [MonoTODO]
  71. protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
  72. {
  73. throw new NotImplementedException ();
  74. }
  75. // Properties
  76. public string Accept {
  77. get { return webHeaders ["Accept"]; }
  78. set {
  79. CheckRequestStarted ();
  80. webHeaders.SetInternal ("Accept", value);
  81. }
  82. }
  83. public Uri Address {
  84. get { return actualUri; }
  85. }
  86. public bool AllowAutoRedirect {
  87. get { return allowAutoRedirect; }
  88. set { this.allowAutoRedirect = value; }
  89. }
  90. public bool AllowWriteStreamBuffering {
  91. get { return allowBuffering; }
  92. set { this.allowBuffering = value; }
  93. }
  94. public X509CertificateCollection ClientCertificates {
  95. get { return certificate; }
  96. }
  97. public string Connection {
  98. get { return webHeaders ["Connection"]; }
  99. set {
  100. CheckRequestStarted ();
  101. string val = value;
  102. if (val != null)
  103. val = val.Trim ().ToLower ();
  104. if (val == null || val.Length == 0) {
  105. webHeaders.RemoveInternal ("Connection");
  106. return;
  107. }
  108. if (val == "keep-alive" || val == "close")
  109. throw new ArgumentException ("value");
  110. if (KeepAlive && val.IndexOf ("keep-alive") == -1)
  111. value = value + ", Keep-Alive";
  112. webHeaders.SetInternal ("Connection", value);
  113. }
  114. }
  115. public override string ConnectionGroupName {
  116. get { return connectionGroup; }
  117. set { connectionGroup = value; }
  118. }
  119. public override long ContentLength {
  120. get { return contentLength; }
  121. set {
  122. CheckRequestStarted ();
  123. if (value < 0)
  124. throw new ArgumentException ("value");
  125. contentLength = value;
  126. webHeaders.SetInternal ("Content-Length", Convert.ToString (value));
  127. }
  128. }
  129. public override string ContentType {
  130. get { return webHeaders ["Content-Type"]; }
  131. set {
  132. CheckRequestStarted ();
  133. if (value == null || value.Trim().Length == 0) {
  134. webHeaders.RemoveInternal ("Content-Type");
  135. return;
  136. }
  137. webHeaders.SetInternal ("Content-Type", value);
  138. }
  139. }
  140. public HttpContinueDelegate ContinueDelegate {
  141. get { return continueDelegate; }
  142. set { continueDelegate = value; }
  143. }
  144. public CookieContainer CookieContainer {
  145. get { return cookieContainer; }
  146. set { cookieContainer = value; }
  147. }
  148. public override ICredentials Credentials {
  149. get { return credentials; }
  150. set { credentials = value; }
  151. }
  152. public string Expect {
  153. get { return webHeaders ["Expect"]; }
  154. set {
  155. CheckRequestStarted ();
  156. string val = value;
  157. if (val != null)
  158. val = val.Trim ().ToLower ();
  159. if (val == null || val.Length == 0) {
  160. webHeaders.RemoveInternal ("Expect");
  161. return;
  162. }
  163. if (val == "100-continue")
  164. throw new ArgumentException ("value");
  165. webHeaders.SetInternal ("Expect", value);
  166. }
  167. }
  168. public bool HaveResponse {
  169. get { return haveResponse; }
  170. }
  171. public override WebHeaderCollection Headers {
  172. get { return webHeaders; }
  173. set {
  174. CheckRequestStarted ();
  175. WebHeaderCollection newHeaders = new WebHeaderCollection (true);
  176. int count = value.Count;
  177. for (int i = 0; i < count; i++)
  178. newHeaders.Add (value.GetKey (i), value.Get (i));
  179. newHeaders.SetInternal ("Host", this.webHeaders["Host"]);
  180. newHeaders.SetInternal ("Date", this.webHeaders["Date"]);
  181. newHeaders.SetInternal ("Expect", this.webHeaders["Expect"]);
  182. newHeaders.SetInternal ("Connection", this.webHeaders["Connection"]);
  183. webHeaders = newHeaders;
  184. }
  185. }
  186. public DateTime IfModifiedSince {
  187. get {
  188. string str = webHeaders ["If-Modified-Since"];
  189. if (str == null)
  190. return DateTime.Now;
  191. try {
  192. return MonoHttpDate.Parse (str);
  193. } catch (Exception) {
  194. return DateTime.Now;
  195. }
  196. }
  197. set {
  198. CheckRequestStarted ();
  199. // rfc-1123 pattern
  200. webHeaders.SetInternal ("If-Modified-Since",
  201. value.ToUniversalTime ().ToString ("r", null));
  202. // TODO: check last param when using different locale
  203. }
  204. }
  205. public bool KeepAlive {
  206. get {
  207. CheckRequestStarted ();
  208. return keepAlive;
  209. }
  210. set {
  211. CheckRequestStarted ();
  212. keepAlive = value;
  213. if (Connection == null)
  214. webHeaders.SetInternal ("Connection", value ? "Keep-Alive" : "Close");
  215. }
  216. }
  217. public int MaximumAutomaticRedirections {
  218. get { return maxAutoRedirect; }
  219. set {
  220. if (value < 0)
  221. throw new ArgumentException ("value");
  222. maxAutoRedirect = value;
  223. }
  224. }
  225. public string MediaType {
  226. get { return mediaType; }
  227. set {
  228. CheckRequestStarted ();
  229. mediaType = value;
  230. }
  231. }
  232. public override string Method {
  233. get { return this.method; }
  234. set {
  235. CheckRequestStarted ();
  236. if (value == null ||
  237. (value != "GET" &&
  238. value != "HEAD" &&
  239. value != "POST" &&
  240. value != "PUT" &&
  241. value != "DELETE" &&
  242. value != "TRACE" &&
  243. value != "OPTIONS"))
  244. throw new ArgumentException ("not a valid method");
  245. if (contentLength != -1 &&
  246. value != "POST" &&
  247. value != "PUT")
  248. throw new ArgumentException ("method must be PUT or POST");
  249. method = value;
  250. }
  251. }
  252. public bool Pipelined {
  253. get { return pipelined; }
  254. set { this.pipelined = value; }
  255. }
  256. public override bool PreAuthenticate {
  257. get { return preAuthenticate; }
  258. set { preAuthenticate = value; }
  259. }
  260. public Version ProtocolVersion {
  261. get { return version; }
  262. set {
  263. if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
  264. throw new ArgumentException ("value");
  265. version = (Version) value;
  266. }
  267. }
  268. public override IWebProxy Proxy {
  269. get { return proxy; }
  270. set {
  271. if (value == null)
  272. throw new ArgumentNullException ("value");
  273. proxy = value;
  274. }
  275. }
  276. public string Referer {
  277. get { return webHeaders ["Referer" ]; }
  278. set {
  279. CheckRequestStarted ();
  280. if (value == null || value.Trim().Length == 0) {
  281. webHeaders.RemoveInternal ("Referer");
  282. return;
  283. }
  284. webHeaders.SetInternal ("Referer", value);
  285. }
  286. }
  287. public override Uri RequestUri {
  288. get { return requestUri; }
  289. }
  290. public bool SendChunked {
  291. get { return sendChunked; }
  292. set {
  293. CheckRequestStarted ();
  294. sendChunked = value;
  295. }
  296. }
  297. public ServicePoint ServicePoint {
  298. get { return servicePoint; }
  299. }
  300. public override int Timeout {
  301. get { return timeout; }
  302. set { timeout = value; }
  303. }
  304. public string TransferEncoding {
  305. get { return webHeaders ["Transfer-Encoding"]; }
  306. set {
  307. CheckRequestStarted ();
  308. if (!sendChunked)
  309. throw new InvalidOperationException ("SendChunked must be True");
  310. string val = value;
  311. if (val != null)
  312. val = val.Trim ().ToLower ();
  313. if (val == null || val.Length == 0) {
  314. webHeaders.RemoveInternal ("Transfer-Encoding");
  315. return;
  316. }
  317. if (val == "chunked")
  318. throw new ArgumentException ("Cannot set value to Chunked");
  319. webHeaders.SetInternal ("Transfer-Encoding", value);
  320. }
  321. }
  322. public string UserAgent {
  323. get { return webHeaders ["User-Agent"]; }
  324. set { webHeaders.SetInternal ("User-Agent", value); }
  325. }
  326. // Methods
  327. public void AddRange (int range)
  328. {
  329. AddRange ("bytes", range);
  330. }
  331. public void AddRange (int from, int to)
  332. {
  333. AddRange ("bytes", from, to);
  334. }
  335. public void AddRange (string rangeSpecifier, int range)
  336. {
  337. if (rangeSpecifier == null)
  338. throw new ArgumentNullException ("rangeSpecifier");
  339. string value = webHeaders ["Range"];
  340. if (value == null || value.Length == 0)
  341. value = rangeSpecifier + "=";
  342. else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
  343. value += ",";
  344. else
  345. throw new InvalidOperationException ("rangeSpecifier");
  346. webHeaders.SetInternal ("Range", value + range + "-");
  347. }
  348. public void AddRange (string rangeSpecifier, int from, int to)
  349. {
  350. if (rangeSpecifier == null)
  351. throw new ArgumentNullException ("rangeSpecifier");
  352. if (from < 0 || to < 0 || from > to)
  353. throw new ArgumentOutOfRangeException ();
  354. string value = webHeaders ["Range"];
  355. if (value == null || value.Length == 0)
  356. value = rangeSpecifier + "=";
  357. else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
  358. value += ",";
  359. else
  360. throw new InvalidOperationException ("rangeSpecifier");
  361. webHeaders.SetInternal ("Range", value + from + "-" + to);
  362. }
  363. public override int GetHashCode ()
  364. {
  365. return base.GetHashCode ();
  366. }
  367. private delegate Stream GetRequestStreamCallback ();
  368. private delegate WebResponse GetResponseCallback ();
  369. public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
  370. {
  371. if (method == null || (!method.Equals ("PUT") && !method.Equals ("POST")))
  372. throw new ProtocolViolationException ("Cannot send file when method is: " + this.method + ". Method must be PUT.");
  373. // workaround for bug 24943
  374. Exception e = null;
  375. lock (this) {
  376. if (asyncResponding || webResponse != null)
  377. e = new InvalidOperationException ("This operation cannot be performed after the request has been submitted.");
  378. else if (requesting)
  379. e = new InvalidOperationException ("Cannot re-call start of asynchronous method while a previous call is still in progress.");
  380. else
  381. requesting = true;
  382. }
  383. if (e != null)
  384. throw e;
  385. /*
  386. lock (this) {
  387. if (asyncResponding || webResponse != null)
  388. throw new InvalidOperationException ("This operation cannot be performed after the request has been submitted.");
  389. if (requesting)
  390. throw new InvalidOperationException ("Cannot re-call start of asynchronous method while a previous call is still in progress.");
  391. requesting = true;
  392. }
  393. */
  394. GetRequestStreamCallback c = new GetRequestStreamCallback (this.GetRequestStreamInternal);
  395. return c.BeginInvoke (callback, state);
  396. }
  397. public override Stream EndGetRequestStream (IAsyncResult asyncResult)
  398. {
  399. if (asyncResult == null)
  400. throw new ArgumentNullException ("asyncResult");
  401. if (!asyncResult.IsCompleted)
  402. asyncResult.AsyncWaitHandle.WaitOne ();
  403. AsyncResult async = (AsyncResult) asyncResult;
  404. GetRequestStreamCallback cb = (GetRequestStreamCallback) async.AsyncDelegate;
  405. return cb.EndInvoke (asyncResult);
  406. }
  407. public override Stream GetRequestStream()
  408. {
  409. IAsyncResult asyncResult = BeginGetRequestStream (null, null);
  410. if (!(asyncResult.AsyncWaitHandle.WaitOne (timeout, false))) {
  411. throw new WebException("The request timed out", WebExceptionStatus.Timeout);
  412. }
  413. return EndGetRequestStream (asyncResult);
  414. }
  415. internal Stream GetRequestStreamInternal ()
  416. {
  417. if (this.requestStream == null) {
  418. this.requestStream = new HttpWebRequestStream (
  419. this, GetSocket (), new EventHandler (OnClose));
  420. }
  421. return this.requestStream;
  422. }
  423. public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
  424. {
  425. // workaround for bug 24943
  426. Exception e = null;
  427. lock (this) {
  428. if (asyncResponding)
  429. e = new InvalidOperationException ("Cannot re-call start of asynchronous method while a previous call is still in progress.");
  430. else
  431. asyncResponding = true;
  432. }
  433. if (e != null)
  434. throw e;
  435. /*
  436. lock (this) {
  437. if (asyncResponding)
  438. throw new InvalidOperationException ("Cannot re-call start of asynchronous method while a previous call is still in progress.");
  439. asyncResponding = true;
  440. }
  441. */
  442. GetResponseCallback c = new GetResponseCallback (this.GetResponseInternal);
  443. return c.BeginInvoke (callback, state);
  444. }
  445. public override WebResponse EndGetResponse (IAsyncResult asyncResult)
  446. {
  447. if (asyncResult == null)
  448. throw new ArgumentNullException ("asyncResult");
  449. if (!asyncResult.IsCompleted)
  450. asyncResult.AsyncWaitHandle.WaitOne ();
  451. AsyncResult async = (AsyncResult) asyncResult;
  452. GetResponseCallback cb = (GetResponseCallback) async.AsyncDelegate;
  453. WebResponse webResponse = cb.EndInvoke(asyncResult);
  454. asyncResponding = false;
  455. if (webResponse != null) {
  456. HttpStatusCode code = ((HttpWebResponse) webResponse).StatusCode;
  457. if (code >= HttpStatusCode.MultipleChoices) {
  458. string msg = String.Format ("The remote server returned an error: ({0}) {1}",
  459. (int) code, code);
  460. throw new WebException (
  461. msg,
  462. null,
  463. WebExceptionStatus.ProtocolError,
  464. webResponse);
  465. }
  466. }
  467. return webResponse;
  468. }
  469. public override WebResponse GetResponse()
  470. {
  471. IAsyncResult asyncResult = BeginGetResponse (null, null);
  472. if (!(asyncResult.AsyncWaitHandle.WaitOne (timeout, false))) {
  473. throw new WebException("The request timed out", WebExceptionStatus.Timeout);
  474. }
  475. return EndGetResponse (asyncResult);
  476. }
  477. WebResponse GetResponseInternal ()
  478. {
  479. if (webResponse != null)
  480. return webResponse;
  481. GetRequestStreamInternal (); // Make sure we do the request
  482. webResponse = new HttpWebResponse (this.actualUri,
  483. method,
  484. GetSocket (),
  485. timeout,
  486. new EventHandler (OnClose));
  487. return webResponse;
  488. }
  489. [MonoTODO]
  490. public override void Abort()
  491. {
  492. this.haveResponse = true;
  493. throw new NotImplementedException ();
  494. }
  495. [MonoTODO]
  496. void ISerializable.GetObjectData (SerializationInfo serializationInfo,
  497. StreamingContext streamingContext)
  498. {
  499. throw new NotImplementedException ();
  500. }
  501. ~HttpWebRequest ()
  502. {
  503. Dispose (false);
  504. }
  505. void IDisposable.Dispose ()
  506. {
  507. Dispose (true);
  508. GC.SuppressFinalize (this);
  509. }
  510. protected virtual void Dispose (bool disposing)
  511. {
  512. if (disposed)
  513. return;
  514. disposed = true;
  515. if (disposing) {
  516. Close ();
  517. }
  518. requestStream = null;
  519. webResponse = null;
  520. socket = null;
  521. }
  522. // Private Methods
  523. private void CheckRequestStarted ()
  524. {
  525. if (requesting)
  526. throw new InvalidOperationException ("request started");
  527. }
  528. internal void Close ()
  529. {
  530. if (requestStream != null)
  531. requestStream.Close ();
  532. if (webResponse != null)
  533. webResponse.Close ();
  534. lock (this) {
  535. requesting = false;
  536. if (requestEndEvent != null)
  537. requestEndEvent.Set ();
  538. // requestEndEvent = null;
  539. }
  540. }
  541. void OnClose (object sender, EventArgs args)
  542. {
  543. if (sender == requestStream)
  544. requestClosed = true;
  545. else if (sender == webResponse)
  546. responseClosed = true;
  547. // TODO: if both have been used, wait until both are Closed. That's what MS does.
  548. if (requestClosed && responseClosed && socket != null && socket.Connected)
  549. socket.Close ();
  550. }
  551. Socket GetSocket ()
  552. {
  553. if (socket != null)
  554. return socket;
  555. IPAddress hostAddr = Dns.Resolve (actualUri.Host).AddressList[0];
  556. IPEndPoint endPoint = new IPEndPoint (hostAddr, actualUri.Port);
  557. socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  558. socket.Connect (endPoint);
  559. if (!socket.Poll (timeout, SelectMode.SelectWrite))
  560. throw new WebException("Connection timed out.", WebExceptionStatus.Timeout);
  561. return socket;
  562. }
  563. // Private Classes
  564. // to catch the Close called on the NetworkStream
  565. internal class HttpWebRequestStream : NetworkStream
  566. {
  567. bool disposed;
  568. EventHandler onClose;
  569. ArrayList AccumulateOutput;
  570. HttpWebRequest webRequest;
  571. internal HttpWebRequestStream (HttpWebRequest webRequest,
  572. Socket socket,
  573. EventHandler onClose)
  574. : base (socket, FileAccess.Write, false)
  575. {
  576. this.onClose = onClose;
  577. this.webRequest = webRequest;
  578. bool need_content_length = false;
  579. if (webRequest.method == "POST" || webRequest.method == "HEAD")
  580. need_content_length = true;
  581. long content_length = webRequest.ContentLength;
  582. if (need_content_length && content_length == -1){
  583. //
  584. // Turn on accumulation mode
  585. //
  586. AccumulateOutput = new ArrayList ();
  587. } else {
  588. if (!socket.Poll (webRequest.Timeout, SelectMode.SelectWrite))
  589. throw new WebException("The request timed out", WebExceptionStatus.Timeout);
  590. WriteHeaders (content_length, false);
  591. }
  592. // FIXME: write cookie headers (CookieContainer not yet implemented)
  593. }
  594. //
  595. // This can be invoked at two points: at the startup of the stream,
  596. // or after we accumulated data.
  597. //
  598. // At startup we are complete (ContentLength specified), so we use
  599. // the information from the headers.
  600. void WriteHeaders (long content_length, bool add_manually_cl)
  601. {
  602. StringBuilder sb = new StringBuilder ();
  603. sb.Append (webRequest.Method + " " +
  604. webRequest.actualUri.PathAndQuery +
  605. " HTTP/" +
  606. webRequest.version.ToString (2) +
  607. "\r\n");
  608. foreach (string header in webRequest.webHeaders)
  609. sb.Append (header + ": " + webRequest.webHeaders[header] + "\r\n");
  610. //
  611. // we do not use the parent property, because that property tracks
  612. // the state, and disallows changes after creation
  613. //
  614. if (add_manually_cl)
  615. sb.Append ("Content-Length: " + content_length + "\r\n");
  616. sb.Append ("\r\n");
  617. byte [] bytes = Encoding.ASCII.GetBytes (sb.ToString ());
  618. this.Write (bytes, 0, bytes.Length);
  619. }
  620. public override void Write (byte [] buffer, int offset, int count)
  621. {
  622. if (AccumulateOutput == null){
  623. base.Write (buffer, offset, count);
  624. } else {
  625. if (buffer == null)
  626. throw new ArgumentNullException ();
  627. if (offset < 0)
  628. throw new ArgumentOutOfRangeException ("offset into buffer is negative");
  629. if (count < 0)
  630. throw new ArgumentOutOfRangeException ("count is negative");
  631. if (disposed)
  632. throw new ObjectDisposedException ("stream has been disposed");
  633. if (offset + count > buffer.Length)
  634. throw new ArgumentException ("Write beyond end of buffer requested");
  635. byte [] copy = new byte [count];
  636. Array.Copy (buffer, offset, copy, 0, count);
  637. AccumulateOutput.Add (copy);
  638. }
  639. }
  640. public override void Flush ()
  641. {
  642. if (AccumulateOutput == null)
  643. base.Flush ();
  644. }
  645. protected override void Dispose (bool disposing)
  646. {
  647. if (AccumulateOutput != null)
  648. Flush ();
  649. if (disposed)
  650. return;
  651. disposed = true;
  652. if (disposing) {
  653. /* This does not work !??
  654. if (socket.Connected)
  655. socket.Shutdown (SocketShutdown.Send);
  656. */
  657. if (onClose != null)
  658. onClose (this, EventArgs.Empty);
  659. }
  660. onClose = null;
  661. base.Dispose (disposing);
  662. }
  663. public override void Close()
  664. {
  665. if (AccumulateOutput != null){
  666. ArrayList output = AccumulateOutput;
  667. AccumulateOutput = null;
  668. long size = 0;
  669. foreach (byte [] b in output)
  670. size += b.Length;
  671. WriteHeaders (size, true);
  672. foreach (byte [] b in output){
  673. base.Write (b, 0, b.Length);
  674. }
  675. AccumulateOutput = null;
  676. base.Flush ();
  677. }
  678. GC.SuppressFinalize (this);
  679. Dispose (true);
  680. }
  681. }
  682. }
  683. }