/
_ConnectStream.cs
3233 lines (2662 loc) · 130 KB
/
_ConnectStream.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="_ConnectStream.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Net {
using System.Diagnostics;
using System.IO;
using System.Net.Security;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Threading;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Permissions;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Configuration;
using System.Globalization;
internal struct WriteHeadersCallbackState{
internal HttpWebRequest request;
internal ConnectStream stream;
internal WriteHeadersCallbackState(HttpWebRequest request, ConnectStream stream){
this.request = request;
this.stream = stream;
}
}
/*++
ConnectStream - a stream interface to a Connection object.
This class implements the Stream interface, as well as a
WriteHeaders call. Inside this stream we handle details like
chunking, dechunking and tracking of ContentLength. To write
or read data, we call a method on the connection object. The
connection object is responsible for protocol stuff that happens
'below' the level of the HTTP request, for example MUX or SSL
--*/
internal class ConnectStream : Stream, ICloseEx, IRequestLifetimeTracker
{
#if DEBUG
internal IAsyncResult _PendingResult;
#endif
// These would be defined in the IOControlCode enum but we don't want them to be public.
private const int ApplyTransportSetting = unchecked((int)0x98000013);
private const int QueryTransportSetting = unchecked((int)0x98000014);
private static class Nesting {
public const int Idle = 0;
public const int IoInProgress = 1; // we are doing read or write
public const int Closed = 2; // stream was closed if that is done in IoInProgress on write, the write will resume delayed close part.
public const int InError = 3; // IO is not allowed due to error stream state
public const int InternalIO = 4; // stream is used by us, this is internal error if public IO sees that value
}
private int m_CallNesting; // see Nesting enum for details
private ScatterGatherBuffers
m_BufferedData; // list of sent buffers in case of resubmit (redirect/authentication).
private bool m_SuppressWrite; // don't write data to the connection, only buffer it
private bool m_BufferOnly; // don't write data to the connection, only buffer it
private long m_BytesLeftToWrite; // Total bytes left to be written.
private int m_BytesAlreadyTransferred; // Bytes already read/written in the current operation.
private Connection m_Connection; // Connection for I/O.
private byte[] m_ReadBuffer; // Read buffer for read stream.
private int m_ReadOffset; // Offset into m_ReadBuffer.
private int m_ReadBufferSize; // Bytes left in m_ReadBuffer.
private long m_ReadBytes; // Total bytes to read on stream, -1 for read to end.
private bool m_Chunked; // True if we're doing chunked read.
private int m_DoneCalled; // 0 at init, 1 after we've called Read/Write Done
private int m_ShutDown; // 0 at init, 1 after we've called Complete
private Exception m_ErrorException; // non-null if we've seen an error on this connection.
private bool m_ChunkEofRecvd; // True, if we've seen an EOF, or reached a EOF state for no more reads
private ChunkParser m_ChunkParser; // Helper object used for parsing chunked responses.
private HttpWriteMode m_HttpWriteMode;
private int m_ReadTimeout; // timeout in ms for reads
private int m_WriteTimeout; // timeout in ms for writes
private RequestLifetimeSetter m_RequestLifetimeSetter;
private const long c_MaxDrainBytes = 64 * 1024; // 64 K - greater than, we should just close the connection
// These two must not be static because the socket will use them when caching the user context.
private readonly AsyncCallback m_ReadCallbackDelegate;
private readonly AsyncCallback m_WriteCallbackDelegate;
private static readonly AsyncCallback m_WriteHeadersCallback = new AsyncCallback(WriteHeadersCallback);
// Special value indicating that an asynchronous read operation is intentionally zero-length.
private static readonly object ZeroLengthRead = new object();
private HttpWebRequest m_Request;
private static volatile int responseDrainTimeoutMilliseconds = Timeout.Infinite;
private const int defaultResponseDrainTimeoutMilliseconds = 500;
private const string responseDrainTimeoutAppSetting = "responseDrainTimeout";
//
// Timeout - timeout in ms for sync reads & writes, passed in HttpWebRequest
//
public override bool CanTimeout {
get {return true;}
}
public override int ReadTimeout {
get {
return m_ReadTimeout;
}
set {
if (value<=0 && value!=System.Threading.Timeout.Infinite) {
throw new ArgumentOutOfRangeException("value", SR.GetString(SR.net_io_timeout_use_gt_zero));
}
m_ReadTimeout = value;
}
}
public override int WriteTimeout {
get {
return m_WriteTimeout;
}
set {
if (value<=0 && value!=System.Threading.Timeout.Infinite) {
throw new ArgumentOutOfRangeException("value", SR.GetString(SR.net_io_timeout_use_gt_zero));
}
m_WriteTimeout = value;
}
}
// We will be done with this stream/connection after the user finishes uploading (redirected)
internal bool FinishedAfterWrite { get; set; }
//
// If IgnoreSocketErrors==true then no data will be sent to the wire
//
private bool m_IgnoreSocketErrors;
internal bool IgnoreSocketErrors {
get {
return m_IgnoreSocketErrors;
}
}
//
// If the KeepAlive=true then we must be prepares for a write socket errors trying to flush the body
// If the KeepAlive=false then we should cease body writing as the connection is probably dead
// If fatal=true then the connection is dead due to IO fault (discovered during read), throw IO exception
//
// m_IgnoreSocketErrors and m_ThrowSocketError are mostly for a write type of streams.
// However a response read stream may have this member set when draning a response on resubmit.
//
// This this isn't synchronized, we also check after receiving an exception from the transport whether these have been set
// and take them into account if they have (on writes).
private bool m_ErrorResponseStatus;
internal void ErrorResponseNotify(bool isKeepAlive) {
m_ErrorResponseStatus = true;
m_IgnoreSocketErrors |= !isKeepAlive;
GlobalLog.Print((WriteStream?"Write-":"Read-") + "ConnectStream#"+ ValidationHelper.HashString(this) + "::Got notification on an Error Response, m_IgnoreSocketErrors:" + m_IgnoreSocketErrors);
}
// This means we should throw a connection closed exception from now on (write only).
// It's unclear whether this needs to be better synchronized with m_ErrorResponseStatus, such as if ErrorResponseNotify
// were called (asynchronously) while a m_ErrorException was already set.
internal void FatalResponseNotify()
{
if (m_ErrorException == null)
{
Interlocked.CompareExchange<Exception>(ref m_ErrorException, new IOException(SR.GetString(SR.net_io_readfailure, SR.GetString(SR.net_io_connectionclosed))), null);
}
m_ErrorResponseStatus = false;
GlobalLog.Print((WriteStream ? "Write-" : "Read-") + "ConnectStream#" + ValidationHelper.HashString(this) + "::Got notification on a Fatal Response");
}
/*++
Write Constructor for this class. This is the write constructor;
it takes as a parameter the amount of entity body data to be written,
with a value of -1 meaning to write it out as chunked. The other
parameter is the Connection of which we'll be writing.
Right now we use the DefaultBufferSize for the stream. In
the future we'd like to pass a 0 and have the stream be
unbuffered for write.
Input:
Conn - Connection for this stream.
BytesToWrite - Total bytes to be written, or -1
if we're doing chunked encoding.
Returns:
Nothing.
--*/
public ConnectStream(Connection connection, HttpWebRequest request) {
GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::.ctor(Write)");
m_Connection = connection;
m_ReadTimeout = m_WriteTimeout = System.Threading.Timeout.Infinite;
//
// we need to save a reference to the request for two things
// 1. In case of buffer-only we kick in actual submition when the stream is closed by a user
// 2. In case of write stream abort() we notify the request so the response stream is handled properly
//
m_Request = request;
m_HttpWriteMode = request.HttpWriteMode;
GlobalLog.Assert(m_HttpWriteMode != HttpWriteMode.Unknown, "ConnectStream#{0}::.ctor()|HttpWriteMode:{1}", ValidationHelper.HashString(this), m_HttpWriteMode);
m_BytesLeftToWrite = m_HttpWriteMode==HttpWriteMode.ContentLength ? request.ContentLength : -1;
if (request.HttpWriteMode==HttpWriteMode.Buffer) {
m_BufferOnly = true;
EnableWriteBuffering();
}
GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::.ctor() Connection:" + ValidationHelper.HashString(m_Connection) + " BytesToWrite:" + BytesLeftToWrite);
m_ReadCallbackDelegate = new AsyncCallback(ReadCallback);
m_WriteCallbackDelegate = new AsyncCallback(WriteCallback);
}
/*++
Read constructor for this class. This constructor takes in
the connection and some information about a buffer that already
contains data. Reads from this stream will read first from the
buffer, and after that is exhausted will read from the connection.
We also take in a size of bytes to read, or -1 if we're to read
to connection close, and a flag indicating whether or now
we're chunked.
Input:
Conn - Connection for this stream.
buffer - Initial buffer to read from.
offset - offset into buffer to start reading.
size - number of bytes in buffer to read.
readSize - Number of bytes allowed to be read from
the stream, -1 for read to connection
close.
chunked - True if we're doing chunked decoding.
Returns:
Nothing.
--*/
public ConnectStream(Connection connection, byte[] buffer, int offset, int bufferCount, long readCount, bool chunked, HttpWebRequest request)
{
GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::.ctor(Read)");
if(Logging.On)Logging.PrintInfo(Logging.Web, this, "ConnectStream", SR.GetString(SR.net_log_buffered_n_bytes, readCount));
m_ReadBytes = readCount;
m_ReadTimeout = m_WriteTimeout = System.Threading.Timeout.Infinite;
m_Chunked = chunked;
m_Connection = connection;
if (m_Chunked)
{
m_ChunkParser = new ChunkParser(m_Connection, buffer, offset, bufferCount,
request.MaximumResponseHeadersLength * 1024);
}
else
{
m_ReadBuffer = buffer;
m_ReadOffset = offset;
m_ReadBufferSize = bufferCount;
}
//
// A request reference is used to verify (by the connection class) that this request should start a next one on Close.
//
m_Request = request;
GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::.ctor() Connection:" + ValidationHelper.HashString(m_Connection) +
" m_ReadOffset:" + m_ReadOffset + " m_ReadBufferSize: " + m_ReadBufferSize +
" ContentLength: " + m_ReadBytes + " m_Chunked:" + m_Chunked.ToString());
m_ReadCallbackDelegate = new AsyncCallback(ReadCallback);
m_WriteCallbackDelegate = new AsyncCallback(WriteCallback);
}
internal void SwitchToContentLength(){
m_HttpWriteMode = HttpWriteMode.ContentLength;
}
internal bool SuppressWrite {
/* Consider Removing
get {
return m_SuppressWrite;
}
*/
set{
m_SuppressWrite = value;
}
}
internal Connection Connection {
get {
return m_Connection;
}
}
internal bool BufferOnly {
get {
return m_BufferOnly;
}
}
internal ScatterGatherBuffers BufferedData {
get {
return m_BufferedData;
}
set {
m_BufferedData = value;
}
}
private bool WriteChunked {
get {
return m_HttpWriteMode==HttpWriteMode.Chunked;
}
}
internal long BytesLeftToWrite {
get {
return m_BytesLeftToWrite;
}
set {
m_BytesLeftToWrite = value;
}
}
// True if this is a write stream.
bool WriteStream {
get {
return m_HttpWriteMode != HttpWriteMode.Unknown;
}
}
internal bool IsPostStream {
get {
return m_HttpWriteMode != HttpWriteMode.None;
}
}
/*++
ErrorInStream - indicates an exception was caught
internally due to a stream error, and that I/O
operations should not continue
Input: Nothing.
Returns: True if there is an error
--*/
internal bool ErrorInStream {
get {
return m_ErrorException!=null;
}
}
/*++
CallDone - calls out to the Connection that spawned this
Stream (using the DoneRead/DoneWrite method).
If the Connection specified that we don't need to
do this, or if we've already done this already, then
we return silently.
Input: Nothing.
Returns: Nothing.
--*/
internal void CallDone()
{
CallDone(null);
}
private void CallDone(ConnectionReturnResult returnResult)
{
GlobalLog.Enter("ConnectStream#" + ValidationHelper.HashString(this) + "::CallDone");
if ( Interlocked.Increment( ref m_DoneCalled) == 1 )
{
if (!WriteStream)
{
#if DEBUG
GlobalLog.DebugRemoveRequest(m_Request);
#endif
if (returnResult == null) {
//readstartnextrequest will call setresponses internally.
if (m_Chunked)
{
int leftoverBufferOffset;
int leftoverBufferSize;
byte[] leftoverBuffer;
if (m_ChunkParser.TryGetLeftoverBytes(out leftoverBuffer, out leftoverBufferOffset,
out leftoverBufferSize))
{
m_Connection.SetLeftoverBytes(leftoverBuffer, leftoverBufferOffset, leftoverBufferSize);
}
}
m_Connection.ReadStartNextRequest(m_Request, ref returnResult);
}
else{
ConnectionReturnResult.SetResponses(returnResult);
}
}
else
{
m_Request.WriteCallDone(this, returnResult);
}
}
GlobalLog.Leave("ConnectStream#" + ValidationHelper.HashString(this) + "::CallDone");
}
internal void ProcessWriteCallDone(ConnectionReturnResult returnResult)
{
GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::ProcessWriteCallDone()");
try {
if (returnResult == null) {
m_Connection.WriteStartNextRequest(m_Request, ref returnResult);
// If the request is Sync, then we do our Read here for data
if (!m_Request.Async)
{
object syncReaderResult = m_Request.ConnectionReaderAsyncResult.InternalWaitForCompletion();
//we should only do a syncread if we didn't already read the response
//via poll when we handed back the request stream
if (syncReaderResult == null && m_Request.NeedsToReadForResponse)
#if DEBUG
// Remove once mixed sync/async requests are supported.
using (GlobalLog.SetThreadKind(ThreadKinds.Sync))
#endif
{
m_Connection.SyncRead(m_Request, true, false);
}
}
m_Request.NeedsToReadForResponse = true;
}
ConnectionReturnResult.SetResponses(returnResult);
}
finally {
// This will decrement the response window on the write side AND may
// result in either immediate or delayed processing of a response for the m_Request instance
if (IsPostStream || m_Request.Async)
m_Request.CheckWriteSideResponseProcessing();
}
}
internal bool IsClosed {
get {
return m_ShutDown != 0;
}
}
/*++
Read property for this class. We return the readability of
this stream. This is a read only property.
Input: Nothing.
Returns: True if this is a read stream, false otherwise.
--*/
public override bool CanRead {
get {
return !WriteStream && !IsClosed;
}
}
/*++
Seek property for this class. Since this stream is not
seekable, we just return false. This is a read only property.
Input: Nothing.
Returns: false
--*/
public override bool CanSeek {
get {
return false;
}
}
/*++
CanWrite property for this class. We return the writeability of
this stream. This is a read only property.
Input: Nothing.
Returns: True if this is a write stream, false otherwise.
--*/
public override bool CanWrite {
get {
return WriteStream && !IsClosed;
}
}
/*++
Length property for this class. Since we don't support seeking,
this property just throws a NotSupportedException.
Input: Nothing.
Returns: Throws exception.
--*/
public override long Length {
get {
throw new NotSupportedException(SR.GetString(SR.net_noseek));
}
}
/*++
Position property for this class. Since we don't support seeking,
this property just throws a NotSupportedException.
Input: Nothing.
Returns: Throws exception.
--*/
public override long Position {
get {
throw new NotSupportedException(SR.GetString(SR.net_noseek));
}
set {
throw new NotSupportedException(SR.GetString(SR.net_noseek));
}
}
/*++
Eof property to indicate when the read is no longer allowed,
because all data has been already read from socket.
Input: Nothing.
Returns: true/false depending on whether we are complete
--*/
internal bool Eof {
get {
if (ErrorInStream) {
return true;
}
else if (m_Chunked) {
return m_ChunkEofRecvd;
}
else if (m_ReadBytes == 0) {
return true;
}
else if (m_ReadBytes == -1) {
return(m_DoneCalled > 0 && m_ReadBufferSize <= 0);
}
else {
return false;
}
}
}
/*++
Uses an old Stream to resubmit buffered data using the current
stream, this is used in cases of POST, or authentication,
where we need to buffer upload data so that it can be resubmitted
Input:
OldStream - Old Stream that was previously used
Returns:
Nothing.
--*/
//
internal void ResubmitWrite(ConnectStream oldStream, bool suppressWrite) {
GlobalLog.Enter("ConnectStream#" + ValidationHelper.HashString(this) + "::ResubmitWrite", ValidationHelper.HashString(oldStream));
GlobalLog.ThreadContract(ThreadKinds.Sync, "ConnectStream#" + ValidationHelper.HashString(this) + "::ResubmitWrite");
//
//
//
// we're going to resubmit
//
try {
Interlocked.CompareExchange(ref m_CallNesting, Nesting.InternalIO, Nesting.Idle);
GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::ResubmitWrite() Inc: " + m_CallNesting.ToString());
GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::ResubmitWrite(), callNesting : " + m_CallNesting.ToString() + " IsClosed = " + IsClosed);
//
// no need to buffer here:
// we're already resubmitting buffered data give it to the connection to put it on the wire again
// we set BytesLeftToWrite to 0 'cause even on failure there can be no recovery,
// so just leave it to IOError() to clean up and don't call ResubmitWrite()
//
ScatterGatherBuffers bufferedData = oldStream.BufferedData;
SafeSetSocketTimeout(SocketShutdown.Send);
if (!WriteChunked) {
if (!suppressWrite)
m_Connection.Write(bufferedData);
}
else {
// we have the data buffered, but we still want to chunk.
// first set this to disable Close() from sending a chunk terminator.
GlobalLog.Assert(m_HttpWriteMode != HttpWriteMode.None, "ConnectStream#{0}::ResubmitWrite()|m_HttpWriteMode == HttpWriteMode.None", ValidationHelper.HashString(this));
m_HttpWriteMode = HttpWriteMode.ContentLength;
if (bufferedData.Length==0) {
m_Connection.Write(NclConstants.ChunkTerminator, 0, NclConstants.ChunkTerminator.Length);
}
else {
int chunkHeaderOffset = 0;
byte[] chunkHeaderBuffer = GetChunkHeader(bufferedData.Length, out chunkHeaderOffset);
BufferOffsetSize[] dataBuffers = bufferedData.GetBuffers();
BufferOffsetSize[] buffers = new BufferOffsetSize[dataBuffers.Length + 3];
buffers[0] = new BufferOffsetSize(chunkHeaderBuffer, chunkHeaderOffset, chunkHeaderBuffer.Length - chunkHeaderOffset, false);
int index = 0;
foreach (BufferOffsetSize buffer in dataBuffers) {
buffers[++index] = buffer;
}
buffers[++index] = new BufferOffsetSize(NclConstants.CRLF, 0, NclConstants.CRLF.Length, false);
buffers[++index] = new BufferOffsetSize(NclConstants.ChunkTerminator, 0, NclConstants.ChunkTerminator.Length, false);
SplitWritesState splitState = new SplitWritesState(buffers);
BufferOffsetSize[] sendBuffers = splitState.GetNextBuffers();
while(sendBuffers != null){
m_Connection.MultipleWrite(sendBuffers);
sendBuffers = splitState.GetNextBuffers();
}
}
}
if(Logging.On && bufferedData.GetBuffers() != null) {
foreach (BufferOffsetSize bufferOffsetSize in bufferedData.GetBuffers()) {
if (bufferOffsetSize == null) {
Logging.Dump(Logging.Web, this, "ResubmitWrite", null, 0, 0);
}
else {
Logging.Dump(Logging.Web, this, "ResubmitWrite", bufferOffsetSize.Buffer, bufferOffsetSize.Offset, bufferOffsetSize.Size);
}
}
}
GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::ResubmitWrite() sent:" + bufferedData.Length.ToString() );
}
catch (Exception exception)
{
if (NclUtilities.IsFatal(exception)) throw;
// A Fatal error
WebException we = new WebException(NetRes.GetWebStatusString("net_connclosed", WebExceptionStatus.SendFailure),
WebExceptionStatus.SendFailure,
WebExceptionInternalStatus.RequestFatal,
exception);
IOError(we, false);
}
finally {
Interlocked.CompareExchange(ref m_CallNesting, Nesting.Idle, Nesting.InternalIO);
GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::ResubmitWrite(), callNesting : " + m_CallNesting.ToString() + " IsClosed = " + IsClosed);
}
m_BytesLeftToWrite = 0;
CallDone();
GlobalLog.Leave("ConnectStream#" + ValidationHelper.HashString(this) + "::ResubmitWrite", BytesLeftToWrite.ToString());
}
//
// called by HttpWebRequest if AllowWriteStreamBuffering is true on that instance
//
internal void EnableWriteBuffering() {
GlobalLog.Assert(WriteStream, "ConnectStream#{0}::EnableWriteBuffering()|!WriteStream", ValidationHelper.HashString(this));
if (BufferedData==null) {
// create stream on demand, only if needed
GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::EnableWriteBuffering() Write() creating ScatterGatherBuffers WriteChunked:" + WriteChunked.ToString() + " BytesLeftToWrite:" + BytesLeftToWrite.ToString());
if (WriteChunked)
{
BufferedData = new ScatterGatherBuffers();
}
else
{
BufferedData = new ScatterGatherBuffers(BytesLeftToWrite);
}
}
}
/*++
FillFromBufferedData - This fills in a buffer from data that we have buffered.
This method pulls out the buffered data that may have been provided as
excess actual data from the header parsing
Input:
buffer - Buffer to read into.
offset - Offset in buffer to read into.
size - Size in bytes to read.
Returns:
Number of bytes read.
--*/
internal int FillFromBufferedData(byte [] buffer, ref int offset, ref int size ) {
//
// if there's no stuff in our read buffer just return 0
//
if (m_ReadBufferSize == 0) {
return 0;
}
//
// There's stuff in our read buffer. Figure out how much to take,
// which is the minimum of what we have and what we're to read,
// and copy it out.
//
int BytesTransferred = Math.Min(size, m_ReadBufferSize);
GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::FillFromBufferedData() Filling bytes: " + BytesTransferred.ToString());
Buffer.BlockCopy(
m_ReadBuffer,
m_ReadOffset,
buffer,
offset,
BytesTransferred);
// Update our internal read buffer state with what we took.
m_ReadOffset += BytesTransferred;
m_ReadBufferSize -= BytesTransferred;
// If the read buffer size has gone to 0, null out our pointer
// to it so maybe it'll be garbage-collected faster.
if (m_ReadBufferSize == 0) {
m_ReadBuffer = null;
}
// Update what we're to read and the caller's offset.
size -= BytesTransferred;
offset += BytesTransferred;
return BytesTransferred;
}
/*++
Write
This function write data to the network. If we were given a definite
content length when constructed, we won't write more than that amount
of data to the network. If the caller tries to do that, we'll throw
an exception. If we're doing chunking, we'll chunk it up before
sending to the connection.
Input:
buffer - buffer to write.
offset - offset in buffer to write from.
size - size in bytes to write.
Returns:
Nothing.
--*/
public override void Write(byte[] buffer, int offset, int size) {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) {
#endif
if (Logging.On) Logging.Enter(Logging.Web, this, "Write", "");
//
// Basic parameter validation
//
if (!WriteStream) {
throw new NotSupportedException(SR.GetString(SR.net_readonlystream));
}
if (buffer==null) {
throw new ArgumentNullException("buffer");
}
if (offset<0 || offset>buffer.Length) {
throw new ArgumentOutOfRangeException("offset");
}
if (size<0 || size>buffer.Length-offset) {
throw new ArgumentOutOfRangeException("size");
}
if(Logging.On) Logging.Dump(Logging.Web, this, "Write", buffer, offset, size);
InternalWrite(false, buffer, offset, size, null, null );
if(Logging.On)Logging.Exit(Logging.Web, this, "Write", "");
#if DEBUG
}
#endif
}
/*++
BeginWrite - Does async write to the Stream
Splits the operation into two outcomes, for the
non-chunking case, we calculate size to write,
then call BeginWrite on the Connection directly,
and then we're finish, for the Chunked case,
we procede with use two callbacks to continue the
chunking after the first write, and then second write.
In order that all of the Chunk data/header/terminator,
in the correct format are sent.
Input:
buffer - Buffer to write into.
offset - Offset in buffer to write into.
size - Size in bytes to write.
callback - the callback to be called on result
state - object to be passed to callback
Returns:
IAsyncResult - the async result
--*/
[HostProtection(ExternalThreading=true)]
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state ) {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::BeginWrite " + ValidationHelper.HashString(m_Connection) + ", " + offset.ToString() + ", " + size.ToString());
if(Logging.On)Logging.Enter(Logging.Web, this, "BeginWrite", "");
//
// Basic parameter validation
//
if (!WriteStream) {
throw new NotSupportedException(SR.GetString(SR.net_readonlystream));
}
if (buffer==null) {
throw new ArgumentNullException("buffer");
}
if (offset<0 || offset>buffer.Length) {
throw new ArgumentOutOfRangeException("offset");
}
if (size<0 || size>buffer.Length-offset) {
throw new ArgumentOutOfRangeException("size");
}
if (Logging.On) Logging.Dump(Logging.Web, this, "BeginWrite", buffer, offset, size);
IAsyncResult result = InternalWrite(true, buffer, offset, size, callback, state);
if(Logging.On)Logging.Exit(Logging.Web, this, "BeginWrite", result);
return result;
#if DEBUG
}
#endif
}
//
// Handles either async or sync Writing for *public* stream API
//
private IAsyncResult InternalWrite(bool async, byte[] buffer, int offset, int size, AsyncCallback callback, object state ) {
//
// if we have a stream error, or we've already shut down this socket
// then we must prevent new BeginRead/BeginWrite's from getting
// submited to the socket, since we've already closed the stream.
//
if (ErrorInStream) {
GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternalWrite() throwing:" + m_ErrorException.ToString());
throw m_ErrorException;
}
if (IsClosed && !IgnoreSocketErrors) {
GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternalWrite() throwing");
throw new WebException(
NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.ConnectionClosed),
WebExceptionStatus.ConnectionClosed);
}
if (m_Request.Aborted && !IgnoreSocketErrors) {
GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternalWrite() throwing");
throw new WebException(
NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled),
WebExceptionStatus.RequestCanceled);
}
int nesting = Interlocked.CompareExchange(ref m_CallNesting, Nesting.IoInProgress, Nesting.Idle);
GlobalLog.Print((async?"Async ":"") + "InternalWrite() In: callNesting : " + nesting.ToString());
if (nesting != Nesting.Idle && nesting != Nesting.Closed)
{
throw new NotSupportedException(SR.GetString(SR.net_no_concurrent_io_allowed));
}
//
// buffer data to the ScatterGatherBuffers
// regardles of chunking, we buffer the data as if we were not chunking
// and on resubmit, we don't bother chunking.
//
if (BufferedData!=null && size != 0 && (m_Request.ContentLength != 0 || !IsPostStream || !m_Request.NtlmKeepAlive)) {
//
// if we don't need to, we shouldn't send data on the wire as well
// but in this case we gave a stream to the user so we have transport
//
BufferedData.Write(buffer, offset, size);
}
LazyAsyncResult asyncResult = null;
bool completeSync = false;
try
{
if (size == 0 || BufferOnly || m_SuppressWrite || IgnoreSocketErrors)
{
//
// We're not putting this data on the wire, then we're done
//
if(m_SuppressWrite && m_BytesLeftToWrite > 0 && size > 0)
{
m_BytesLeftToWrite -= size;
}
GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternalWrite() ----ing: size==0 || BufferOnly || IgnoreSocketErrors= " + (size==0) + BufferOnly + IgnoreSocketErrors);
if (async) {
asyncResult = new LazyAsyncResult(this, state, callback);
completeSync = true;
}
return asyncResult;
}
else if (WriteChunked) {
//
// We're chunking. Write the chunk header out first,
// then the data, then a CRLF.
// for this we'll use BeginMultipleSend();
//
int chunkHeaderOffset = 0;
byte[] chunkHeaderBuffer = GetChunkHeader(size, out chunkHeaderOffset);
BufferOffsetSize[] buffers;
GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternalWrite() m_ErrorResponseStatus:" + m_ErrorResponseStatus);
if (m_ErrorResponseStatus) {
//if we already got a (>200) response, then just terminate chunking and
//switch to simple buffering (if any)
GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternalWrite() setting m_IgnoreSocketErrors to True (was:" + m_IgnoreSocketErrors + ") sending chunk terminator");
m_IgnoreSocketErrors = true;
buffers = new BufferOffsetSize[1];
buffers[0] = new BufferOffsetSize(NclConstants.ChunkTerminator, 0, NclConstants.ChunkTerminator.Length, false);
}
else {
buffers = new BufferOffsetSize[3];
buffers[0] = new BufferOffsetSize(chunkHeaderBuffer, chunkHeaderOffset, chunkHeaderBuffer.Length - chunkHeaderOffset, false);
buffers[1] = new BufferOffsetSize(buffer, offset, size, false);
buffers[2] = new BufferOffsetSize(NclConstants.CRLF, 0, NclConstants.CRLF.Length, false);
}
asyncResult = (async) ? new NestedMultipleAsyncResult(this, state, callback, buffers) : null;
//
// after setting up the buffers and error checking do the async Write Call
//
try {
if (async) {
m_Connection.BeginMultipleWrite(buffers, m_WriteCallbackDelegate, asyncResult);
}
else {
SafeSetSocketTimeout(SocketShutdown.Send);