HttpResponseStream.jvm.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. //
  2. // System.Web.HttpResponseStream.cs
  3. //
  4. //
  5. // Author:
  6. // Miguel de Icaza ([email protected])
  7. // Ben Maurer ([email protected])
  8. //
  9. //
  10. // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
  11. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. using System;
  32. using System.IO;
  33. using System.Text;
  34. using System.Globalization;
  35. using System.Runtime.InteropServices;
  36. namespace System.Web
  37. {
  38. //
  39. // HttpResponseStream implements the "OutputStream" from HttpResponse
  40. //
  41. // The MS implementation is broken in that it does not hook up this
  42. // to HttpResponse, so calling "Flush" on Response.OutputStream does not
  43. // flush the contents and produce the headers.
  44. //
  45. // You must call HttpResponse.Flush which does the actual header generation
  46. // and actual data flushing
  47. //
  48. internal class HttpResponseStream : Stream
  49. {
  50. Bucket first_bucket;
  51. Bucket cur_bucket;
  52. HttpResponse response;
  53. bool dirty = false;
  54. Stream filter;
  55. public HttpResponseStream (HttpResponse response)
  56. {
  57. this.response = response;
  58. }
  59. internal bool HaveFilter
  60. {
  61. get { return filter != null; }
  62. }
  63. public Stream Filter
  64. {
  65. get
  66. {
  67. if (filter == null)
  68. filter = new OutputFilterStream (this);
  69. return filter;
  70. }
  71. set
  72. {
  73. filter = value;
  74. }
  75. }
  76. abstract class Bucket
  77. {
  78. public Bucket Next;
  79. public virtual void Dispose ()
  80. {
  81. }
  82. public abstract void Send (HttpWorkerRequest wr);
  83. public abstract void Send (Stream stream);
  84. public abstract int Length { get; }
  85. public abstract int FreeSpace { get; }
  86. }
  87. class ByteBucket : Bucket
  88. {
  89. const int _preferredLength = 16 * 1024;
  90. int _position = 0;
  91. int _freeSpace = _preferredLength;
  92. byte [] buffer = new byte [_preferredLength];
  93. public ByteBucket ()
  94. {
  95. }
  96. public override int Length
  97. {
  98. get { return _position; }
  99. }
  100. public override int FreeSpace
  101. {
  102. get { return _freeSpace; }
  103. }
  104. public int Write (byte [] buf, int offset, int count)
  105. {
  106. if (count > _freeSpace)
  107. throw new InvalidOperationException ("Out of bucket space");
  108. Array.Copy (buf, offset, buffer, _position, count);
  109. _position += count;
  110. _freeSpace = _preferredLength - _position;
  111. return count;
  112. }
  113. public override void Dispose ()
  114. {
  115. buffer = null;
  116. }
  117. public override void Send (HttpWorkerRequest wr)
  118. {
  119. if (_position == 0)
  120. return;
  121. wr.SendResponseFromMemory (buffer, _position);
  122. }
  123. public override void Send (Stream stream)
  124. {
  125. if (_position == 0)
  126. return;
  127. stream.Write (buffer, 0, _position);
  128. }
  129. }
  130. class CharBucket : Bucket
  131. {
  132. const int _preferredLength = 16 * 1024;
  133. int _position = 0;
  134. int _freeSpace = _preferredLength;
  135. char [] buffer = new char [_preferredLength];
  136. public CharBucket ()
  137. {
  138. }
  139. public override int Length
  140. {
  141. get
  142. {
  143. HttpContext current = HttpContext.Current;
  144. Encoding enc = (current != null) ? current.Response.ContentEncoding : Encoding.UTF8;
  145. return enc.GetByteCount (buffer, 0, _position);
  146. }
  147. }
  148. public override int FreeSpace
  149. {
  150. get { return _freeSpace; }
  151. }
  152. public int Write (string buf, int offset, int count)
  153. {
  154. if (count > _freeSpace)
  155. throw new InvalidOperationException ("Out of bucket space");
  156. for (int i = offset; i < offset + count; i++)
  157. buffer [_position++] = buf [i];
  158. _freeSpace = _preferredLength - _position;
  159. return count;
  160. }
  161. public int Write (char [] buf, int offset, int count)
  162. {
  163. if (count > _freeSpace)
  164. throw new InvalidOperationException ("Out of bucket space");
  165. Array.Copy (buf, offset, buffer, _position, count);
  166. _position += count;
  167. _freeSpace = _preferredLength - _position;
  168. return count;
  169. }
  170. public override void Dispose ()
  171. {
  172. buffer = null;
  173. }
  174. public override void Send (HttpWorkerRequest wr)
  175. {
  176. if (_position == 0)
  177. return;
  178. wr.SendResponseFromMemory (buffer, _position);
  179. }
  180. public override void Send (Stream stream)
  181. {
  182. if (_position == 0)
  183. return;
  184. StreamWriter writer = new StreamWriter (stream);
  185. writer.Write (buffer, 0, _position);
  186. }
  187. }
  188. class BufferedFileBucket : Bucket
  189. {
  190. string file;
  191. long offset;
  192. long length;
  193. public BufferedFileBucket (string f, long off, long len)
  194. {
  195. file = f;
  196. offset = off;
  197. length = len;
  198. }
  199. public override int Length
  200. {
  201. get { return (int) length; }
  202. }
  203. public override int FreeSpace
  204. {
  205. get { return int.MaxValue; }
  206. }
  207. public override void Send (HttpWorkerRequest wr)
  208. {
  209. wr.SendResponseFromFile (file, offset, length);
  210. }
  211. public override void Send (Stream stream)
  212. {
  213. using (FileStream fs = File.OpenRead (file)) {
  214. byte [] buffer = new byte [Math.Min (fs.Length, 32 * 1024)];
  215. long remain = fs.Length;
  216. int n;
  217. while (remain > 0 && (n = fs.Read (buffer, 0, (int) Math.Min (remain, 32 * 1024))) != 0) {
  218. remain -= n;
  219. stream.Write (buffer, 0, n);
  220. }
  221. }
  222. }
  223. public override string ToString ()
  224. {
  225. return String.Format ("file {0} {1} bytes from position {2}", file, length, offset);
  226. }
  227. }
  228. void AppendBucket (Bucket b)
  229. {
  230. if (first_bucket == null) {
  231. cur_bucket = first_bucket = b;
  232. return;
  233. }
  234. cur_bucket.Next = b;
  235. cur_bucket = b;
  236. }
  237. //
  238. // Nothing happens here, broken by requirement.
  239. // See note at the start
  240. //
  241. public override void Flush ()
  242. {
  243. }
  244. internal void Flush (HttpWorkerRequest wr, bool final_flush)
  245. {
  246. if (!dirty && !final_flush)
  247. return;
  248. for (Bucket b = first_bucket; b != null; b = b.Next) {
  249. b.Send (wr);
  250. }
  251. wr.FlushResponse (final_flush);
  252. Clear ();
  253. }
  254. internal int GetTotalLength ()
  255. {
  256. int size = 0;
  257. for (Bucket b = first_bucket; b != null; b = b.Next)
  258. size += b.Length;
  259. return size;
  260. }
  261. internal MemoryStream GetData ()
  262. {
  263. MemoryStream stream = new MemoryStream ();
  264. for (Bucket b = first_bucket; b != null; b = b.Next)
  265. b.Send (stream);
  266. return stream;
  267. }
  268. public void WriteFile (string f, long offset, long length)
  269. {
  270. if (length == 0)
  271. return;
  272. dirty = true;
  273. AppendBucket (new BufferedFileBucket (f, offset, length));
  274. // Flush () is called from HttpResponse if needed (WriteFile/TransmitFile)
  275. }
  276. bool filtering;
  277. internal void ApplyFilter (bool close)
  278. {
  279. if (filter == null)
  280. return;
  281. filtering = true;
  282. Bucket one = first_bucket;
  283. first_bucket = null; // This will recreate new buckets for the filtered content
  284. cur_bucket = null;
  285. dirty = false;
  286. for (Bucket b = one; b != null; b = b.Next)
  287. b.Send (filter);
  288. for (Bucket b = one; b != null; b = b.Next)
  289. b.Dispose ();
  290. if (close) {
  291. filter.Flush ();
  292. filter.Close ();
  293. filter = null;
  294. }
  295. else {
  296. filter.Flush ();
  297. }
  298. filtering = false;
  299. }
  300. public void Write (char [] buffer, int offset, int count)
  301. {
  302. bool buffering = response.BufferOutput;
  303. if (buffering) {
  304. // It does not matter whether we're in ApplyFilter or not
  305. AppendBuffer (buffer, offset, count);
  306. }
  307. else if (filter == null || filtering) {
  308. response.WriteHeaders (false);
  309. HttpWorkerRequest wr = response.WorkerRequest;
  310. // Direct write because not buffering
  311. if (offset == 0) {
  312. wr.SendResponseFromMemory (buffer, count);
  313. }
  314. else {
  315. UnsafeWrite (wr, buffer, offset, count);
  316. }
  317. wr.FlushResponse (false);
  318. }
  319. else {
  320. // Write to the filter, which will call us back, and then Flush
  321. filtering = true;
  322. try {
  323. StreamWriter wr = new StreamWriter (filter, response.ContentEncoding);
  324. wr.Write (buffer, offset, count);
  325. }
  326. finally {
  327. filtering = false;
  328. }
  329. Flush (response.WorkerRequest, false);
  330. }
  331. }
  332. public void Write (string s, int offset, int count)
  333. {
  334. bool buffering = response.BufferOutput;
  335. if (buffering) {
  336. // It does not matter whether we're in ApplyFilter or not
  337. AppendBuffer (s, offset, count);
  338. }
  339. else if (filter == null || filtering) {
  340. response.WriteHeaders (false);
  341. HttpWorkerRequest wr = response.WorkerRequest;
  342. // Direct write because not buffering
  343. if (offset == 0) {
  344. wr.SendResponseFromMemory (s.ToCharArray (), count);
  345. }
  346. else {
  347. UnsafeWrite (wr, s.ToCharArray (), offset, count);
  348. }
  349. wr.FlushResponse (false);
  350. }
  351. else {
  352. // Write to the filter, which will call us back, and then Flush
  353. filtering = true;
  354. try {
  355. StreamWriter wr = new StreamWriter (filter, response.ContentEncoding);
  356. wr.Write (s, offset, count);
  357. }
  358. finally {
  359. filtering = false;
  360. }
  361. Flush (response.WorkerRequest, false);
  362. }
  363. }
  364. public override void Write (byte [] buffer, int offset, int count)
  365. {
  366. bool buffering = response.BufferOutput;
  367. if (buffering) {
  368. // It does not matter whether we're in ApplyFilter or not
  369. AppendBuffer (buffer, offset, count);
  370. }
  371. else if (filter == null || filtering) {
  372. response.WriteHeaders (false);
  373. HttpWorkerRequest wr = response.WorkerRequest;
  374. // Direct write because not buffering
  375. if (offset == 0) {
  376. wr.SendResponseFromMemory (buffer, count);
  377. }
  378. else {
  379. UnsafeWrite (wr, buffer, offset, count);
  380. }
  381. wr.FlushResponse (false);
  382. }
  383. else {
  384. // Write to the filter, which will call us back, and then Flush
  385. filtering = true;
  386. try {
  387. filter.Write (buffer, offset, count);
  388. }
  389. finally {
  390. filtering = false;
  391. }
  392. Flush (response.WorkerRequest, false);
  393. }
  394. }
  395. #if TARGET_JVM
  396. void UnsafeWrite (HttpWorkerRequest wr, byte [] buffer, int offset, int count)
  397. {
  398. if (count <= 0)
  399. return;
  400. byte [] copy = new byte [count];
  401. Array.Copy (buffer, offset, copy, 0, count);
  402. wr.SendResponseFromMemory (copy, count);
  403. }
  404. void UnsafeWrite (HttpWorkerRequest wr, char [] buffer, int offset, int count)
  405. {
  406. if (count <= 0)
  407. return;
  408. char [] copy = new char [count];
  409. Array.Copy (buffer, offset, copy, 0, count);
  410. wr.SendResponseFromMemory (copy, count);
  411. }
  412. #else
  413. unsafe void UnsafeWrite (HttpWorkerRequest wr, byte [] buffer, int offset, int count)
  414. {
  415. fixed (byte *ptr = buffer) {
  416. wr.SendResponseFromMemory ((IntPtr) (ptr + offset), count);
  417. }
  418. }
  419. #endif
  420. void AppendBuffer (byte [] buffer, int offset, int count)
  421. {
  422. if (!(cur_bucket is ByteBucket))
  423. AppendBucket (new ByteBucket ());
  424. dirty = true;
  425. while (count > 0) {
  426. if (cur_bucket.FreeSpace == 0)
  427. AppendBucket (new CharBucket ());
  428. int len = count;
  429. int freeSpace = cur_bucket.FreeSpace;
  430. if (len > freeSpace)
  431. len = freeSpace;
  432. ((ByteBucket) cur_bucket).Write (buffer, offset, len);
  433. offset += len;
  434. count -= len;
  435. }
  436. }
  437. void AppendBuffer (char [] buffer, int offset, int count)
  438. {
  439. if (!(cur_bucket is CharBucket))
  440. AppendBucket (new CharBucket ());
  441. dirty = true;
  442. while (count > 0) {
  443. if (cur_bucket.FreeSpace == 0)
  444. AppendBucket (new CharBucket ());
  445. int len = count;
  446. int freeSpace = cur_bucket.FreeSpace;
  447. if (len > freeSpace)
  448. len = freeSpace;
  449. ((CharBucket) cur_bucket).Write (buffer, offset, len);
  450. offset += len;
  451. count -= len;
  452. }
  453. }
  454. void AppendBuffer (string buffer, int offset, int count)
  455. {
  456. if (!(cur_bucket is CharBucket))
  457. AppendBucket (new CharBucket ());
  458. dirty = true;
  459. while (count > 0) {
  460. if (cur_bucket.FreeSpace == 0)
  461. AppendBucket (new CharBucket ());
  462. int len = count;
  463. int freeSpace = cur_bucket.FreeSpace;
  464. if (len > freeSpace)
  465. len = freeSpace;
  466. ((CharBucket) cur_bucket).Write (buffer, offset, len);
  467. offset += len;
  468. count -= len;
  469. }
  470. }
  471. //
  472. // This should not flush/close or anything else, its called
  473. // just to free any memory we might have allocated (when we later
  474. // implement something with unmanaged memory).
  475. //
  476. internal void ReleaseResources (bool close_filter)
  477. {
  478. if (close_filter && filter != null) {
  479. filter.Close ();
  480. filter = null;
  481. }
  482. for (Bucket b = first_bucket; b != null; b = b.Next)
  483. b.Dispose ();
  484. first_bucket = null;
  485. cur_bucket = null;
  486. }
  487. public void Clear ()
  488. {
  489. //
  490. // IMPORTANT: you must dispose *AFTER* using all the buckets Byte chunks might be
  491. // split across two buckets if there is a file between the data.
  492. //
  493. ReleaseResources (false);
  494. dirty = false;
  495. }
  496. public override bool CanRead
  497. {
  498. get
  499. {
  500. return false;
  501. }
  502. }
  503. public override bool CanSeek
  504. {
  505. get
  506. {
  507. return false;
  508. }
  509. }
  510. public override bool CanWrite
  511. {
  512. get
  513. {
  514. return true;
  515. }
  516. }
  517. const string notsupported = "HttpResponseStream is a forward, write-only stream";
  518. public override long Length
  519. {
  520. get
  521. {
  522. throw new InvalidOperationException (notsupported);
  523. }
  524. }
  525. public override long Position
  526. {
  527. get
  528. {
  529. throw new InvalidOperationException (notsupported);
  530. }
  531. set
  532. {
  533. throw new InvalidOperationException (notsupported);
  534. }
  535. }
  536. public override long Seek (long offset, SeekOrigin origin)
  537. {
  538. throw new InvalidOperationException (notsupported);
  539. }
  540. public override void SetLength (long value)
  541. {
  542. throw new InvalidOperationException (notsupported);
  543. }
  544. public override int Read (byte [] buffer, int offset, int count)
  545. {
  546. throw new InvalidOperationException (notsupported);
  547. }
  548. }
  549. }