-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathHttpWriter.cs
1829 lines (1482 loc) · 60.1 KB
/
HttpWriter.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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//------------------------------------------------------------------------------
// <copyright file="HttpWriter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
* Response Writer and Stream implementation
*
* Copyright (c) 1998 Microsoft Corporation
*/
namespace System.Web {
using System.Collections;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization.Formatters;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Web.Util;
using System.Web.Hosting;
using IIS = System.Web.Hosting.UnsafeIISMethods;
//
// HttpWriter buffer recycling support
//
/*
* Constants for buffering
*/
internal static class BufferingParams {
internal static readonly int INTEGRATED_MODE_BUFFER_SIZE = 16*1024 - 4*IntPtr.Size; // native buffer size for integrated mode
internal const int OUTPUT_BUFFER_SIZE = 31*1024; // output is a chain of this size buffers
internal const int MAX_FREE_BYTES_TO_CACHE = 4096; // don't compress when taking snapshot if free bytes < this
internal const int MAX_FREE_OUTPUT_BUFFERS = 64; // keep this number of unused buffers
internal const int CHAR_BUFFER_SIZE = 1024; // size of the buffers for chat conversion to bytes
internal const int MAX_FREE_CHAR_BUFFERS = 64; // keep this number of unused buffers
internal const int MAX_BYTES_TO_COPY = 128; // copy results of char conversion vs using recycleable buffers
internal const int MAX_RESOURCE_BYTES_TO_COPY = 4*1024; // resource strings below this size are copied to buffers
internal const int INT_BUFFER_SIZE = 128; // default size for int[] buffers
internal const int INTPTR_BUFFER_SIZE = 128; // default size for IntPtr[] buffers
}
/*
* Interface implemented by elements of the response buffer list
*/
internal interface IHttpResponseElement {
long GetSize();
byte[] GetBytes(); // required for filtering
void Send(HttpWorkerRequest wr);
}
/*
* Base class for recyclable memory buffer elements
*/
internal abstract class HttpBaseMemoryResponseBufferElement {
protected int _size;
protected int _free;
protected bool _recycle;
internal int FreeBytes {
get { return _free;}
}
internal void DisableRecycling() {
_recycle = false;
}
// abstract methods
internal abstract void Recycle();
internal abstract HttpResponseBufferElement Clone();
internal abstract int Append(byte[] data, int offset, int size);
internal abstract int Append(IntPtr data, int offset, int size);
internal abstract void AppendEncodedChars(char[] data, int offset, int size, Encoder encoder, bool flushEncoder);
}
/*
* Memory response buffer
*/
internal sealed class HttpResponseBufferElement : HttpBaseMemoryResponseBufferElement, IHttpResponseElement {
private byte[] _data;
/*
* Constructor that accepts the data buffer and holds on to it
*/
internal HttpResponseBufferElement(byte[] data, int size) {
_data = data;
_size = size;
_free = 0;
_recycle = false;
}
/*
* Close the buffer copying the data
* (needed to 'compress' buffers for caching)
*/
internal override HttpResponseBufferElement Clone() {
int clonedSize = _size - _free;
byte[] clonedData = new byte[clonedSize];
Buffer.BlockCopy(_data, 0, clonedData, 0, clonedSize);
return new HttpResponseBufferElement(clonedData, clonedSize);
}
internal override void Recycle() {
}
internal override int Append(byte[] data, int offset, int size) {
if (_free == 0 || size == 0)
return 0;
int n = (_free >= size) ? size : _free;
Buffer.BlockCopy(data, offset, _data, _size-_free, n);
_free -= n;
return n;
}
internal override int Append(IntPtr data, int offset, int size) {
if (_free == 0 || size == 0)
return 0;
int n = (_free >= size) ? size : _free;
Misc.CopyMemory(data, offset, _data, _size-_free, n);
_free -= n;
return n;
}
internal override void AppendEncodedChars(char[] data, int offset, int size, Encoder encoder, bool flushEncoder) {
int byteSize = encoder.GetBytes(data, offset, size, _data, _size-_free, flushEncoder);
_free -= byteSize;
}
//
// IHttpResponseElement implementation
//
/*
* Get number of bytes
*/
long IHttpResponseElement.GetSize() {
return(_size - _free);
}
/*
* Get bytes (for filtering)
*/
byte[] IHttpResponseElement.GetBytes() {
return _data;
}
/*
* Write HttpWorkerRequest
*/
void IHttpResponseElement.Send(HttpWorkerRequest wr) {
int n = _size - _free;
if (n > 0)
wr.SendResponseFromMemory(_data, n);
}
}
#if !FEATURE_PAL // FEATURE_PAL does not enable IIS-based hosting features
/*
* Unmanaged memory response buffer
*/
internal sealed class HttpResponseUnmanagedBufferElement : HttpBaseMemoryResponseBufferElement, IHttpResponseElement {
private IntPtr _data;
private static IntPtr s_Pool;
static HttpResponseUnmanagedBufferElement() {
if (HttpRuntime.UseIntegratedPipeline) {
s_Pool = IIS.MgdGetBufferPool(BufferingParams.INTEGRATED_MODE_BUFFER_SIZE);
}
else {
s_Pool = UnsafeNativeMethods.BufferPoolGetPool(BufferingParams.OUTPUT_BUFFER_SIZE,
BufferingParams.MAX_FREE_OUTPUT_BUFFERS);
}
}
/*
* Constructor that creates an empty buffer
*/
internal HttpResponseUnmanagedBufferElement() {
if (HttpRuntime.UseIntegratedPipeline) {
_data = IIS.MgdGetBuffer(s_Pool);
_size = BufferingParams.INTEGRATED_MODE_BUFFER_SIZE;
}
else {
_data = UnsafeNativeMethods.BufferPoolGetBuffer(s_Pool);
_size = BufferingParams.OUTPUT_BUFFER_SIZE;
}
if (_data == IntPtr.Zero) {
throw new OutOfMemoryException();
}
_free = _size;
_recycle = true;
}
/*
* dtor - frees the unmanaged buffer
*/
~HttpResponseUnmanagedBufferElement() {
IntPtr data = Interlocked.Exchange(ref _data, IntPtr.Zero);
if (data != IntPtr.Zero) {
if (HttpRuntime.UseIntegratedPipeline) {
IIS.MgdReturnBuffer(data);
}
else {
UnsafeNativeMethods.BufferPoolReleaseBuffer(data);
}
}
}
/*
* Clone the buffer copying the data int managed buffer
* (needed to 'compress' buffers for caching)
*/
internal override HttpResponseBufferElement Clone() {
int clonedSize = _size - _free;
byte[] clonedData = new byte[clonedSize];
Misc.CopyMemory(_data, 0, clonedData, 0, clonedSize);
return new HttpResponseBufferElement(clonedData, clonedSize);
}
internal override void Recycle() {
if (_recycle)
ForceRecycle();
}
private void ForceRecycle() {
IntPtr data = Interlocked.Exchange(ref _data, IntPtr.Zero);
if (data != IntPtr.Zero) {
_free = 0;
_recycle = false;
if (HttpRuntime.UseIntegratedPipeline) {
IIS.MgdReturnBuffer(data);
}
else {
UnsafeNativeMethods.BufferPoolReleaseBuffer(data);
}
System.GC.SuppressFinalize(this);
}
}
internal override int Append(byte[] data, int offset, int size) {
if (_free == 0 || size == 0)
return 0;
int n = (_free >= size) ? size : _free;
Misc.CopyMemory(data, offset, _data, _size-_free, n);
_free -= n;
return n;
}
internal override int Append(IntPtr data, int offset, int size) {
if (_free == 0 || size == 0)
return 0;
int n = (_free >= size) ? size : _free;
Misc.CopyMemory(data, offset, _data, _size-_free, n);
_free -= n;
return n;
}
// manually adjust the size
// used after file reads directly into a buffer
internal void AdjustSize(int size) {
_free -= size;
}
internal override void AppendEncodedChars(char[] data, int offset, int size, Encoder encoder, bool flushEncoder) {
int byteSize = UnsafeAppendEncodedChars(data, offset, size, _data, _size - _free, _free, encoder, flushEncoder);
_free -= byteSize;
#if DBG
Debug.Trace("UnmanagedBuffers", "Encoding chars, charCount=" + size + ", byteCount=" + byteSize);
#endif
}
private unsafe static int UnsafeAppendEncodedChars(char[] src, int srcOffset, int srcSize, IntPtr dest, int destOffset, int destSize, Encoder encoder, bool flushEncoder) {
int numBytes = 0;
byte* destBytes = ((byte*)dest) + destOffset;
fixed (char* charSrc = src) {
numBytes = encoder.GetBytes(charSrc+srcOffset, srcSize, destBytes, destSize, flushEncoder);
}
return numBytes;
}
//
// IHttpResponseElement implementation
//
/*
* Get number of bytes
*/
long IHttpResponseElement.GetSize() {
return (_size - _free);
}
/*
* Get bytes (for filtering)
*/
byte[] IHttpResponseElement.GetBytes() {
int n = (_size - _free);
if (n > 0) {
byte[] data = new byte[n];
Misc.CopyMemory(_data, 0, data, 0, n);
return data;
}
else {
return null;
}
}
/*
* Write HttpWorkerRequest
*/
void IHttpResponseElement.Send(HttpWorkerRequest wr) {
int n = _size - _free;
if (n > 0) {
wr.SendResponseFromMemory(_data, n, true);
}
#if DBG
Debug.Trace("UnmanagedBuffers", "Sending data, byteCount=" + n + ", freeBytes=" + _free);
#endif
}
internal unsafe IntPtr FreeLocation {
get {
int n = _size - _free;
byte * p = (byte*) _data.ToPointer();
p += n;
return new IntPtr(p);
}
}
}
#endif // !FEATURE_PAL
/*
* Response element where data comes from resource
*/
internal sealed class HttpResourceResponseElement : IHttpResponseElement {
private IntPtr _data;
private int _offset;
private int _size;
internal HttpResourceResponseElement(IntPtr data, int offset, int size) {
_data = data;
_offset = offset;
_size = size;
}
//
// IHttpResponseElement implementation
//
/*
* Get number of bytes
*/
long IHttpResponseElement.GetSize() {
return _size;
}
/*
* Get bytes (used only for filtering)
*/
byte[] IHttpResponseElement.GetBytes() {
if (_size > 0) {
byte[] data = new byte[_size];
Misc.CopyMemory(_data, _offset, data, 0, _size);
return data;
}
else {
return null;
}
}
/*
* Write HttpWorkerRequest
*/
void IHttpResponseElement.Send(HttpWorkerRequest wr) {
if (_size > 0) {
wr.SendResponseFromMemory(new IntPtr(_data.ToInt64()+_offset), _size, isBufferFromUnmanagedPool: false);
}
}
}
/*
* Response element where data comes from file
*/
internal sealed class HttpFileResponseElement : IHttpResponseElement {
private String _filename;
private long _offset;
private long _size;
private bool _isImpersonating;
private bool _useTransmitFile;
/**
* Constructor from filename, uses TransmitFile
*/
internal HttpFileResponseElement(String filename, long offset, long size, bool isImpersonating, bool supportsLongTransmitFile) :
this (filename, offset, size, isImpersonating, true, supportsLongTransmitFile) {
}
/*
* Constructor from filename and range (doesn't use TransmitFile)
*/
internal HttpFileResponseElement(String filename, long offset, long size) :
this (filename, offset, size, false, false, false) {
}
private HttpFileResponseElement(string filename,
long offset,
long size,
bool isImpersonating,
bool useTransmitFile,
bool supportsLongTransmitFile)
{
if ((!supportsLongTransmitFile && size > Int32.MaxValue) || (size < 0)) {
throw new ArgumentOutOfRangeException("size", size, SR.GetString(SR.Invalid_size));
}
if ((!supportsLongTransmitFile && offset > Int32.MaxValue) || (offset < 0)) {
throw new ArgumentOutOfRangeException("offset", offset, SR.GetString(SR.Invalid_size));
}
_filename = filename;
_offset = offset;
_size = size;
_isImpersonating = isImpersonating;
_useTransmitFile = useTransmitFile;
}
internal string FileName { get { return _filename; } }
internal long Offset { get { return _offset; } }
//
// IHttpResponseElement implementation
//
/*
* Get number of bytes
*/
long IHttpResponseElement.GetSize() {
return _size;
}
/*
* Get bytes (for filtering)
*/
byte[] IHttpResponseElement.GetBytes() {
if (_size == 0)
return null;
byte[] data = null;
FileStream f = null;
try {
f = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.Read);
long fileSize = f.Length;
if (_offset < 0 || _size > fileSize - _offset)
throw new HttpException(SR.GetString(SR.Invalid_range));
if (_offset > 0)
f.Seek(_offset, SeekOrigin.Begin);
int intSize = (int)_size;
data = new byte[intSize];
int bytesRead = 0;
do {
int n = f.Read(data, bytesRead, intSize);
if (n == 0) {
break;
}
bytesRead += n;
intSize -= n;
} while (intSize > 0);
// Technically here, the buffer may not be full after the loop, but we choose to ignore
// this very rare condition (the file became shorter between the time we looked at its length
// and the moment we read it). In this case, we would just have a few zero bytes at the end
// of the byte[], which is fine.
}
finally {
if (f != null)
f.Close();
}
return data;
}
/*
* Write HttpWorkerRequest
*/
void IHttpResponseElement.Send(HttpWorkerRequest wr) {
if (_size > 0) {
if (_useTransmitFile) {
wr.TransmitFile(_filename, _offset, _size, _isImpersonating); // This is for IIS 6, in-proc TransmitFile
}
else {
wr.SendResponseFromFile(_filename, _offset, _size);
}
}
}
}
/*
* Response element for substituiton
*/
internal sealed class HttpSubstBlockResponseElement : IHttpResponseElement {
private HttpResponseSubstitutionCallback _callback;
private IHttpResponseElement _firstSubstitution;
private IntPtr _firstSubstData;
private int _firstSubstDataSize;
private bool _isIIS7WorkerRequest;
// used by OutputCache
internal HttpResponseSubstitutionCallback Callback { get { return _callback; } }
/*
* Constructor given the name and the data (fill char converted to bytes)
* holds on to the data
*/
internal HttpSubstBlockResponseElement(HttpResponseSubstitutionCallback callback, Encoding encoding, Encoder encoder, IIS7WorkerRequest iis7WorkerRequest) {
_callback = callback;
if (iis7WorkerRequest != null) {
_isIIS7WorkerRequest = true;
String s = _callback(HttpContext.Current);
if (s == null) {
throw new ArgumentNullException("substitutionString");
}
CreateFirstSubstData(s, iis7WorkerRequest, encoder);
}
else {
_firstSubstitution = Substitute(encoding);
}
}
// special constructor used by OutputCache
internal HttpSubstBlockResponseElement(HttpResponseSubstitutionCallback callback) {
_callback = callback;
}
// WOS 1926509: ASP.NET: WriteSubstitution in integrated mode needs to support callbacks that return String.Empty
private unsafe void CreateFirstSubstData(String s, IIS7WorkerRequest iis7WorkerRequest, Encoder encoder) {
Debug.Assert(s != null, "s != null");
IntPtr pbBuffer;
int numBytes = 0;
int cch = s.Length;
if (cch > 0) {
fixed (char * pch = s) {
int cbBuffer = encoder.GetByteCount(pch, cch, true /*flush*/);
pbBuffer = iis7WorkerRequest.AllocateRequestMemory(cbBuffer);
if (pbBuffer != IntPtr.Zero) {
numBytes = encoder.GetBytes(pch, cch, (byte*)pbBuffer, cbBuffer, true /*flush*/);
}
}
}
else {
// deal with empty string
pbBuffer = iis7WorkerRequest.AllocateRequestMemory(1);
}
if (pbBuffer == IntPtr.Zero) {
throw new OutOfMemoryException();
}
_firstSubstData = pbBuffer;
_firstSubstDataSize = numBytes;
}
/*
* Performs substition -- return the resulting HttpResponseBufferElement
* holds on to the data
*/
internal IHttpResponseElement Substitute(Encoding e) {
String s = _callback(HttpContext.Current);
byte[] data = e.GetBytes(s);
return new HttpResponseBufferElement(data, data.Length);
}
internal bool PointerEquals(IntPtr ptr) {
Debug.Assert(HttpRuntime.UseIntegratedPipeline, "HttpRuntime.UseIntegratedPipeline");
return _firstSubstData == ptr;
}
//
// IHttpResponseElement implementation (doesn't do anything)
//
/*
* Get number of bytes
*/
long IHttpResponseElement.GetSize() {
if (_isIIS7WorkerRequest) {
return _firstSubstDataSize;
}
else {
return _firstSubstitution.GetSize();
}
}
/*
* Get bytes (for filtering)
*/
byte[] IHttpResponseElement.GetBytes() {
if (_isIIS7WorkerRequest) {
if (_firstSubstDataSize > 0) {
byte[] data = new byte[_firstSubstDataSize];
Misc.CopyMemory(_firstSubstData, 0, data, 0, _firstSubstDataSize);
return data;
}
else {
// WOS 1926509: ASP.NET: WriteSubstitution in integrated mode needs to support callbacks that return String.Empty
return (_firstSubstData == IntPtr.Zero) ? null : new byte[0];
}
}
else {
return _firstSubstitution.GetBytes();
}
}
/*
* Write HttpWorkerRequest
*/
void IHttpResponseElement.Send(HttpWorkerRequest wr) {
if (_isIIS7WorkerRequest) {
IIS7WorkerRequest iis7WorkerRequest = wr as IIS7WorkerRequest;
if (iis7WorkerRequest != null) {
// buffer can have size of zero if the subst block is an emptry string
iis7WorkerRequest.SendResponseFromIISAllocatedRequestMemory(_firstSubstData, _firstSubstDataSize);
}
}
else {
_firstSubstitution.Send(wr);
}
}
}
/*
* Stream object synchronized with Writer
*/
internal class HttpResponseStream : Stream {
private HttpWriter _writer;
internal HttpResponseStream(HttpWriter writer) {
_writer = writer;
}
//
// Public Stream method implementations
//
public override bool CanRead {
get { return false;}
}
public override bool CanSeek {
get { return false;}
}
public override bool CanWrite {
get { return true;}
}
public override long Length {
get {throw new NotSupportedException();}
}
public override long Position {
get {throw new NotSupportedException();}
set {throw new NotSupportedException();}
}
protected override void Dispose(bool disposing) {
try {
if (disposing)
_writer.Close();
}
finally {
base.Dispose(disposing);
}
}
public override void Flush() {
_writer.Flush();
}
public override long Seek(long offset, SeekOrigin origin) {
throw new NotSupportedException();
}
public override void SetLength(long value) {
throw new NotSupportedException();
}
public override int Read(byte[] buffer, int offset, int count) {
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count) {
if (_writer.IgnoringFurtherWrites) {
return;
}
// Dev10 Bug 507392: Do as Stream does.
if (buffer == null)
throw new ArgumentNullException("buffer");
if (offset < 0)
throw new ArgumentOutOfRangeException("offset");
if (count < 0)
throw new ArgumentOutOfRangeException("count");
if (buffer.Length - offset < count)
throw new ArgumentException(SR.GetString(SR.InvalidOffsetOrCount, "offset", "count"));
if (count == 0)
return;
_writer.WriteFromStream(buffer, offset, count);
}
}
/*
* Stream serving as sink for filters
*/
internal sealed class HttpResponseStreamFilterSink : HttpResponseStream {
private bool _filtering = false;
internal HttpResponseStreamFilterSink(HttpWriter writer) : base(writer) {
}
private void VerifyState() {
// throw exception on unexpected filter writes
if (!_filtering)
throw new HttpException(SR.GetString(SR.Invalid_use_of_response_filter));
}
internal bool Filtering {
get { return _filtering;}
set { _filtering = value;}
}
//
// Stream methods just go to the base class with exception of Close and Flush that do nothing
//
protected override void Dispose(bool disposing) {
// do nothing
base.Dispose(disposing);
}
public override void Flush() {
// do nothing (this is not a buffering stream)
}
public override void Write(byte[] buffer, int offset, int count) {
VerifyState();
base.Write(buffer, offset, count);
}
}
/*
* TextWriter synchronized with the response object
*/
/// <devdoc>
/// <para>A TextWriter class synchronized with the Response object.</para>
/// </devdoc>
public sealed class HttpWriter : TextWriter {
private HttpResponse _response;
private HttpResponseStream _stream;
private HttpResponseStreamFilterSink _filterSink; // sink stream for the filter writes
private Stream _installedFilter; // installed filtering stream
private HttpBaseMemoryResponseBufferElement _lastBuffer;
private ArrayList _buffers;
private char[] _charBuffer;
private int _charBufferLength;
private int _charBufferFree;
private ArrayList _substElements = null;
static IAllocatorProvider s_DefaultAllocator = null;
IAllocatorProvider _allocator = null; // Use only via HttpWriter.AllocationProvider to ensure proper fallback
// cached data from the response
// can be invalidated via UpdateResponseXXX methods
private bool _responseBufferingOn;
private Encoding _responseEncoding;
private bool _responseEncodingUsed;
private bool _responseEncodingUpdated;
private Encoder _responseEncoder;
private int _responseCodePage;
private bool _responseCodePageIsAsciiCompat;
private bool _ignoringFurtherWrites;
private bool _hasBeenClearedRecently;
internal HttpWriter(HttpResponse response): base(null) {
_response = response;
_stream = new HttpResponseStream(this);
_buffers = new ArrayList();
_lastBuffer = null;
// Setup the buffer on demand using CharBuffer property
_charBuffer = null;
_charBufferLength = 0;
_charBufferFree = 0;
UpdateResponseBuffering();
// delay getting response encoding until it is really needed
// UpdateResponseEncoding();
}
internal ArrayList SubstElements {
get {
if (_substElements == null) {
_substElements = new ArrayList();
// dynamic compression is not compatible with post cache substitution
_response.Context.Request.SetDynamicCompression(false /*enable*/);
}
return _substElements;
}
}
/// <devdov>
/// True if the writer is ignoring all writes
/// </devdoc>
internal bool IgnoringFurtherWrites {
get {
return _ignoringFurtherWrites;
}
}
/// <devdov>
/// </devdoc>
internal void IgnoreFurtherWrites() {
_ignoringFurtherWrites = true;
}
internal void UpdateResponseBuffering() {
_responseBufferingOn = _response.BufferOutput;
}
internal void UpdateResponseEncoding() {
if (_responseEncodingUpdated) { // subsequent update
if (_charBufferLength != _charBufferFree)
FlushCharBuffer(true);
}
_responseEncoding = _response.ContentEncoding;
_responseEncoder = _response.ContentEncoder;
_responseCodePage = _responseEncoding.CodePage;
_responseCodePageIsAsciiCompat = CodePageUtils.IsAsciiCompatibleCodePage(_responseCodePage);
_responseEncodingUpdated = true;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override Encoding Encoding {
get {
if (!_responseEncodingUpdated) {
UpdateResponseEncoding();
}
return _responseEncoding;
}
}
internal Encoder Encoder {
get {
if (!_responseEncodingUpdated) {
UpdateResponseEncoding();
}
return _responseEncoder;
}
}
private HttpBaseMemoryResponseBufferElement CreateNewMemoryBufferElement() {
return new HttpResponseUnmanagedBufferElement(); /* using unmanaged buffers */
}
internal void DisposeIntegratedBuffers() {
Debug.Assert(HttpRuntime.UseIntegratedPipeline);
// don't recycle char buffers here (ClearBuffers will)
// do recycle native output buffers
if (_buffers != null) {
int n = _buffers.Count;
for (int i = 0; i < n; i++) {
HttpBaseMemoryResponseBufferElement buf = _buffers[i] as HttpBaseMemoryResponseBufferElement;
// if this is a native buffer, this will bump down the ref count
// the native side also keeps a ref count (see mgdhandler.cxx)
if (buf != null) {
buf.Recycle();
}
}
_buffers = null;
}
// finish by clearing buffers
ClearBuffers();
}
internal void RecycleBuffers() {
// recycle char buffers
if (_charBuffer != null) {
AllocatorProvider.CharBufferAllocator.ReuseBuffer(_charBuffer);
_charBuffer = null;
}
// recycle output buffers
RecycleBufferElements();
}
internal static void ReleaseAllPooledBuffers() {
if (s_DefaultAllocator != null) {
s_DefaultAllocator.TrimMemory();
}
}
internal void ClearSubstitutionBlocks() {
_substElements = null;
}
internal IAllocatorProvider AllocatorProvider {
private get {
if (_allocator == null) {
if (s_DefaultAllocator == null) {
// Create default static allocator
IBufferAllocator charAllocator = new CharBufferAllocator(BufferingParams.CHAR_BUFFER_SIZE, BufferingParams.MAX_FREE_CHAR_BUFFERS);
AllocatorProvider alloc = new AllocatorProvider();
alloc.CharBufferAllocator = new BufferAllocatorWrapper<char>(charAllocator);
Interlocked.CompareExchange(ref s_DefaultAllocator, alloc, null);
}
_allocator = s_DefaultAllocator;
}
return _allocator;
}
set {
_allocator = value;
}
}
private void RecycleBufferElements() {
if (_buffers != null) {
int n = _buffers.Count;
for (int i = 0; i < n; i++) {
HttpBaseMemoryResponseBufferElement buf = _buffers[i] as HttpBaseMemoryResponseBufferElement;
if (buf != null) {
buf.Recycle();
}
}
_buffers = null;
}
}
private void ClearCharBuffer() {
_charBufferFree = _charBufferLength;
}
private char[] CharBuffer {
get {
if (_charBuffer == null) {
_charBuffer = AllocatorProvider.CharBufferAllocator.GetBuffer();
_charBufferLength = _charBuffer.Length;
_charBufferFree = _charBufferLength;