/
HttpResponseStream.cs
707 lines (610 loc) · 16.3 KB
/
HttpResponseStream.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
//
// System.Web.HttpResponseStream.cs
//
//
// Author:
// Miguel de Icaza (miguel@novell.com)
// Ben Maurer (bmaurer@ximian.com)
//
//
// Copyright (C) 2005-2009 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Text;
using System.Globalization;
using System.Runtime.InteropServices;
namespace System.Web
{
//
// HttpResponseStream implements the "OutputStream" from HttpResponse
//
// The MS implementation is broken in that it does not hook up this
// to HttpResponse, so calling "Flush" on Response.OutputStream does not
// flush the contents and produce the headers.
//
// You must call HttpResponse.Flush which does the actual header generation
// and actual data flushing
//
class HttpResponseStream : Stream
{
Bucket first_bucket;
Bucket cur_bucket;
HttpResponse response;
internal long total;
Stream filter;
byte [] chunk_buffer = new byte [24];
public HttpResponseStream (HttpResponse response)
{
this.response = response;
}
internal bool HaveFilter {
get { return filter != null; }
}
public Stream Filter {
get {
if (filter == null)
filter = new OutputFilterStream (this);
return filter;
}
set {
filter = value;
}
}
unsafe sealed class BlockManager {
const int PreferredLength = 128 * 1024;
byte *data;
int position;
int block_size;
public BlockManager ()
{
}
public int Position {
get { return position; }
}
void EnsureCapacity (int capacity)
{
if (block_size >= capacity)
return;
capacity += PreferredLength;
capacity = (capacity / PreferredLength) * PreferredLength;
data = data == null
? (byte *) Marshal.AllocHGlobal (capacity)
: (byte *) Marshal.ReAllocHGlobal ((IntPtr) data, (IntPtr) capacity);
block_size = capacity;
}
public void Write (byte [] buffer, int offset, int count)
{
if (count == 0)
return;
EnsureCapacity (position + count);
Marshal.Copy (buffer, offset, (IntPtr) (data + position), count);
position += count;
}
public void Write (IntPtr ptr, int count)
{
if (count == 0)
return;
EnsureCapacity (position + count);
byte *src = (byte *) ptr.ToPointer ();
if (count < 32) {
byte *dest = (data + position);
for (int i = 0; i < count; i++)
*dest++ = *src++;
} else {
memcpy (data + position, src, count);
}
position += count;
}
public void Send (HttpWorkerRequest wr, int start, int end)
{
if (end - start <= 0)
return;
wr.SendResponseFromMemory ((IntPtr) (data + start), end - start);
}
public void Send (Stream stream, int start, int end)
{
int len = end - start;
if (len <= 0)
return;
byte [] buffer = new byte [Math.Min (len, 32 * 1024)];
int size = buffer.Length;
while (len > 0) {
Marshal.Copy ((IntPtr) (data + start), buffer, 0, size);
stream.Write (buffer, 0, size);
start += size;
len -= size;
if (len > 0 && len < size)
size = len;
}
}
public void Dispose ()
{
if ((IntPtr) data != IntPtr.Zero) {
Marshal.FreeHGlobal ((IntPtr) data);
data = (byte *) IntPtr.Zero;
}
}
}
abstract class Bucket {
public Bucket Next;
public virtual void Dispose ()
{
}
public abstract void Send (HttpWorkerRequest wr);
public abstract void Send (Stream stream);
public abstract int Length { get; }
}
unsafe
class ByteBucket : Bucket {
int start;
int length;
public BlockManager blocks;
public bool Expandable = true;
public ByteBucket () : this (null)
{
}
public ByteBucket (BlockManager blocks)
{
if (blocks == null)
blocks = new BlockManager ();
this.blocks = blocks;
start = blocks.Position;
}
public override int Length {
get { return length; }
}
public unsafe int Write (byte [] buf, int offset, int count)
{
if (Expandable == false)
throw new Exception ("This should not happen.");
fixed (byte *p = &buf[0]) {
IntPtr p2 = new IntPtr (p + offset);
blocks.Write (p2, count);
}
length += count;
return count;
}
public int Write (IntPtr ptr, int count)
{
if (Expandable == false)
throw new Exception ("This should not happen.");
blocks.Write (ptr, count);
length += count;
return count;
}
public override void Dispose ()
{
blocks.Dispose ();
}
public override void Send (HttpWorkerRequest wr)
{
if (length == 0)
return;
blocks.Send (wr, start, length);
}
public override void Send (Stream stream)
{
if (length == 0)
return;
blocks.Send (stream, start, length);
}
}
class BufferedFileBucket : Bucket {
string file;
long offset;
long length;
public BufferedFileBucket (string f, long off, long len)
{
file = f;
offset = off;
length = len;
}
public override int Length {
get { return (int) length; }
}
public override void Send (HttpWorkerRequest wr)
{
wr.SendResponseFromFile (file, offset, length);
}
public override void Send (Stream stream)
{
using (FileStream fs = File.OpenRead (file)) {
byte [] buffer = new byte [Math.Min (fs.Length, 32*1024)];
long remain = fs.Length;
int n;
while (remain > 0 && (n = fs.Read (buffer, 0, (int) Math.Min (remain, 32*1024))) != 0){
remain -= n;
stream.Write (buffer, 0, n);
}
}
}
public override string ToString ()
{
return "file " + file + " " + length.ToString () + " bytes from position " + offset.ToString ();
}
}
void AppendBucket (Bucket b)
{
if (first_bucket == null) {
cur_bucket = first_bucket = b;
return;
}
cur_bucket.Next = b;
cur_bucket = b;
}
//
// Nothing happens here, broken by requirement.
// See note at the start
//
public override void Flush ()
{
}
void SendChunkSize (long l, bool last)
{
if (l == 0 && !last)
return;
int i = 0;
if (l >= 0) {
string s = l.ToString ("x");
for (; i < s.Length; i++)
chunk_buffer [i] = (byte) s [i];
}
chunk_buffer [i++] = 13;
chunk_buffer [i++] = 10;
if (last) {
chunk_buffer [i++] = 13;
chunk_buffer [i++] = 10;
}
response.WorkerRequest.SendResponseFromMemory (chunk_buffer, i);
}
internal void Flush (HttpWorkerRequest wr, bool final_flush)
{
if (total == 0 && !final_flush)
return;
if (response.use_chunked)
SendChunkSize (total, false);
for (Bucket b = first_bucket; b != null; b = b.Next) {
b.Send (wr);
}
if (response.use_chunked) {
SendChunkSize (-1, false);
if (final_flush)
SendChunkSize (0, true);
}
wr.FlushResponse (final_flush);
Clear ();
}
internal int GetTotalLength ()
{
int size = 0;
for (Bucket b = first_bucket; b != null; b = b.Next)
size += b.Length;
return size;
}
internal MemoryStream GetData ()
{
MemoryStream stream = new MemoryStream ();
for (Bucket b = first_bucket; b != null; b = b.Next)
b.Send (stream);
return stream;
}
public void WriteFile (string f, long offset, long length)
{
if (length == 0)
return;
ByteBucket bb = cur_bucket as ByteBucket;
if (bb != null) {
bb.Expandable = false;
bb = new ByteBucket (bb.blocks);
}
total += length;
AppendBucket (new BufferedFileBucket (f, offset, length));
if (bb != null)
AppendBucket (bb);
// Flush () is called from HttpResponse if needed (WriteFile/TransmitFile)
}
bool filtering;
internal void ApplyFilter (bool close)
{
if (filter == null)
return;
filtering = true;
Bucket one = first_bucket;
first_bucket = null; // This will recreate new buckets for the filtered content
cur_bucket = null;
total = 0;
for (Bucket b = one; b != null; b = b.Next)
b.Send (filter);
for (Bucket b = one; b != null; b = b.Next)
b.Dispose ();
if (close) {
filter.Flush ();
filter.Close ();
filter = null;
} else {
filter.Flush ();
}
filtering = false;
}
public void WritePtr (IntPtr ptr, int length)
{
if (length == 0)
return;
bool buffering = response.BufferOutput;
if (buffering) {
// It does not matter whether we're in ApplyFilter or not
AppendBuffer (ptr, length);
} else if (filter == null || filtering) {
response.WriteHeaders (false);
HttpWorkerRequest wr = response.WorkerRequest;
// Direct write because not buffering
wr.SendResponseFromMemory (ptr, length);
wr.FlushResponse (false);
} else {
// Write to the filter, which will call us back, and then Flush
filtering = true;
try {
byte [] bytes = new byte [length];
Marshal.Copy (ptr, bytes, 0, length);
filter.Write (bytes, 0, length);
bytes = null;
} finally {
filtering = false;
}
Flush (response.WorkerRequest, false);
}
}
public override void Write (byte [] buffer, int offset, int count)
{
bool buffering = response.BufferOutput;
if (buffer == null)
throw new ArgumentNullException ("buffer");
int max_count = buffer.Length - offset;
if (offset < 0 || max_count <= 0)
throw new ArgumentOutOfRangeException ("offset");
if (count < 0)
throw new ArgumentOutOfRangeException ("count");
if (count > max_count)
count = max_count;
if (buffering) {
// It does not matter whether we're in ApplyFilter or not
AppendBuffer (buffer, offset, count);
} else if (filter == null || filtering) {
response.WriteHeaders (false);
HttpWorkerRequest wr = response.WorkerRequest;
// Direct write because not buffering
if (offset == 0) {
wr.SendResponseFromMemory (buffer, count);
} else {
UnsafeWrite (wr, buffer, offset, count);
}
wr.FlushResponse (false);
} else {
// Write to the filter, which will call us back, and then Flush
filtering = true;
try {
filter.Write (buffer, offset, count);
} finally {
filtering = false;
}
Flush (response.WorkerRequest, false);
}
}
unsafe void UnsafeWrite (HttpWorkerRequest wr, byte [] buffer, int offset, int count)
{
fixed (byte *ptr = buffer) {
wr.SendResponseFromMemory ((IntPtr) (ptr + offset), count);
}
}
void AppendBuffer (byte [] buffer, int offset, int count)
{
if (!(cur_bucket is ByteBucket))
AppendBucket (new ByteBucket ());
total += count;
((ByteBucket) cur_bucket).Write (buffer, offset, count);
}
void AppendBuffer (IntPtr ptr, int count)
{
if (!(cur_bucket is ByteBucket))
AppendBucket (new ByteBucket ());
total += count;
((ByteBucket) cur_bucket).Write (ptr, count);
}
//
// This should not flush/close or anything else, its called
// just to free any memory we might have allocated (when we later
// implement something with unmanaged memory).
//
internal void ReleaseResources (bool close_filter)
{
if (close_filter && filter != null) {
filter.Close ();
filter = null;
}
for (Bucket b = first_bucket; b != null; b = b.Next)
b.Dispose ();
first_bucket = null;
cur_bucket = null;
}
public void Clear ()
{
//
// IMPORTANT: you must dispose *AFTER* using all the buckets Byte chunks might be
// split across two buckets if there is a file between the data.
//
ReleaseResources (false);
total = 0;
}
// Do not use directly. Use memcpy.
static unsafe void memcpy4 (byte *dest, byte *src, int size) {
/*while (size >= 32) {
// using long is better than int and slower than double
// FIXME: enable this only on correct alignment or on platforms
// that can tolerate unaligned reads/writes of doubles
((double*)dest) [0] = ((double*)src) [0];
((double*)dest) [1] = ((double*)src) [1];
((double*)dest) [2] = ((double*)src) [2];
((double*)dest) [3] = ((double*)src) [3];
dest += 32;
src += 32;
size -= 32;
}*/
while (size >= 16) {
((int*)dest) [0] = ((int*)src) [0];
((int*)dest) [1] = ((int*)src) [1];
((int*)dest) [2] = ((int*)src) [2];
((int*)dest) [3] = ((int*)src) [3];
dest += 16;
src += 16;
size -= 16;
}
while (size >= 4) {
((int*)dest) [0] = ((int*)src) [0];
dest += 4;
src += 4;
size -= 4;
}
while (size > 0) {
((byte*)dest) [0] = ((byte*)src) [0];
dest += 1;
src += 1;
--size;
}
}
// Do not use directly. Use memcpy.
static unsafe void memcpy2 (byte *dest, byte *src, int size) {
while (size >= 8) {
((short*)dest) [0] = ((short*)src) [0];
((short*)dest) [1] = ((short*)src) [1];
((short*)dest) [2] = ((short*)src) [2];
((short*)dest) [3] = ((short*)src) [3];
dest += 8;
src += 8;
size -= 8;
}
while (size >= 2) {
((short*)dest) [0] = ((short*)src) [0];
dest += 2;
src += 2;
size -= 2;
}
if (size > 0)
((byte*)dest) [0] = ((byte*)src) [0];
}
// Do not use directly. Use memcpy.
static unsafe void memcpy1 (byte *dest, byte *src, int size) {
while (size >= 8) {
((byte*)dest) [0] = ((byte*)src) [0];
((byte*)dest) [1] = ((byte*)src) [1];
((byte*)dest) [2] = ((byte*)src) [2];
((byte*)dest) [3] = ((byte*)src) [3];
((byte*)dest) [4] = ((byte*)src) [4];
((byte*)dest) [5] = ((byte*)src) [5];
((byte*)dest) [6] = ((byte*)src) [6];
((byte*)dest) [7] = ((byte*)src) [7];
dest += 8;
src += 8;
size -= 8;
}
while (size >= 2) {
((byte*)dest) [0] = ((byte*)src) [0];
((byte*)dest) [1] = ((byte*)src) [1];
dest += 2;
src += 2;
size -= 2;
}
if (size > 0)
((byte*)dest) [0] = ((byte*)src) [0];
}
static unsafe void memcpy (byte *dest, byte *src, int size) {
// FIXME: if pointers are not aligned, try to align them
// so a faster routine can be used. Handle the case where
// the pointers can't be reduced to have the same alignment
// (just ignore the issue on x86?)
if ((((int)dest | (int)src) & 3) != 0) {
if (((int)dest & 1) != 0 && ((int)src & 1) != 0 && size >= 1) {
dest [0] = src [0];
++dest;
++src;
--size;
}
if (((int)dest & 2) != 0 && ((int)src & 2) != 0 && size >= 2) {
((short*)dest) [0] = ((short*)src) [0];
dest += 2;
src += 2;
size -= 2;
}
if ((((int)dest | (int)src) & 1) != 0) {
memcpy1 (dest, src, size);
return;
}
if ((((int)dest | (int)src) & 2) != 0) {
memcpy2 (dest, src, size);
return;
}
}
memcpy4 (dest, src, size);
}
public override bool CanRead {
get {
return false;
}
}
public override bool CanSeek {
get {
return false;
}
}
public override bool CanWrite {
get {
return true;
}
}
const string notsupported = "HttpResponseStream is a forward, write-only stream";
public override long Length {
get {
throw new NotSupportedException (notsupported);
}
}
public override long Position {
get {
throw new NotSupportedException (notsupported);
}
set {
throw new NotSupportedException (notsupported);
}
}
public override long Seek (long offset, SeekOrigin origin)
{
throw new NotSupportedException (notsupported);
}
public override void SetLength (long value)
{
throw new NotSupportedException (notsupported);
}
public override int Read (byte [] buffer, int offset, int count)
{
throw new NotSupportedException (notsupported);
}
}
}