Repository navigation
Expand file tree
/
Copy path_Connection.cs
More file actions
3975 lines (3368 loc) · 188 KB
/
Copy path_Connection.cs
File metadata and controls
3975 lines (3368 loc) · 188 KB
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="_Connection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Net {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Net.Configuration;
using System.Net.Sockets;
using System.Threading;
using System.Security;
using System.Security.Authentication;
internal enum ReadState {
Start,
StatusLine, // about to parse status line
Headers, // reading headers
Data // now read data
}
internal enum DataParseStatus {
NeedMoreData = 0, // need more data
ContinueParsing, // continue parsing
Done, // done
Invalid, // bad data format
DataTooBig, // data exceeds the allowed size
}
internal enum WriteBufferState {
Disabled,
Headers,
Buffer,
Playback,
}
// The enum lietrals will be displayed to the user in the exception message
internal enum WebParseErrorSection {
Generic,
ResponseHeader,
ResponseStatusLine,
ResponseBody
}
// The enum literal will be used to look up an error string in the resource file
internal enum WebParseErrorCode {
Generic,
InvalidHeaderName,
InvalidContentLength,
IncompleteHeaderLine,
CrLfError,
InvalidChunkFormat,
UnexpectedServerResponse
}
// Only defined for DataParseStatus.Invalid
struct WebParseError {
public WebParseErrorSection Section;
public WebParseErrorCode Code;
}
struct TunnelStateObject {
internal TunnelStateObject(HttpWebRequest r, Connection c){
Connection = c;
OriginalRequest = r;
}
internal Connection Connection;
internal HttpWebRequest OriginalRequest;
}
//
// ConnectionReturnResult - used to spool requests that have been completed,
// and need to be notified.
//
internal class ConnectionReturnResult {
private static readonly WaitCallback s_InvokeConnectionCallback = new WaitCallback(InvokeConnectionCallback);
private struct RequestContext {
internal HttpWebRequest Request;
internal object CoreResponse;
internal RequestContext(HttpWebRequest request, object coreResponse)
{
Request = request;
CoreResponse = coreResponse;
}
}
private List<RequestContext> m_Context;
internal ConnectionReturnResult()
{
m_Context = new List<RequestContext>(5);
}
internal ConnectionReturnResult(int capacity)
{
m_Context = new List<RequestContext>(capacity);
}
internal bool IsNotEmpty {
get {
return m_Context.Count != 0;
}
}
internal static void Add(ref ConnectionReturnResult returnResult, HttpWebRequest request, CoreResponseData coreResponseData)
{
if (coreResponseData == null)
throw new InternalException(); //This may cause duplicate requests if we let it through in retail
if (returnResult == null) {
returnResult = new ConnectionReturnResult();
}
#if DEBUG
//This may cause duplicate requests if we let it through in retail but it's may be expensive to catch here
for (int j = 0; j < returnResult.m_Context.Count; ++j)
if ((object)returnResult.m_Context[j].Request == (object) request)
throw new InternalException();
#endif
returnResult.m_Context.Add(new RequestContext(request, coreResponseData));
}
internal static void AddExceptionRange(ref ConnectionReturnResult returnResult, HttpWebRequest [] requests, Exception exception)
{
AddExceptionRange(ref returnResult, requests, 0, exception, exception);
}
internal static void AddExceptionRange(ref ConnectionReturnResult returnResult, HttpWebRequest [] requests, int abortedPipelinedRequestIndex, Exception exception, Exception firstRequestException)
{
//This may cause duplicate requests if we let it through in retail
if (exception == null)
throw new InternalException();
if (returnResult == null) {
returnResult = new ConnectionReturnResult(requests.Length);
}
// "abortedRequestExeption" is assigned to the "abortedRequest" or to the very first request if the latest is null
// Everyone else will get "exception"
for (int i = 0; i < requests.Length; ++i)
{
#if DEBUG
//This may cause duplicate requests if we let it through in retail but it's may be expensive to catch here
for (int j = 0; j < returnResult.m_Context.Count; ++j)
if ((object)returnResult.m_Context[j].Request == (object) requests[i])
throw new InternalException();
#endif
// The request being aborted might be part of a series of pipelined requests.
// The 'abortedPipelinedRequestIndex' represents the index of the request in the
// connection's m_WriteList array. These are requests that have started and whose
// request headers have been sent to the server. But the server has not yet sent
// back the response readers.
if (i == abortedPipelinedRequestIndex)
returnResult.m_Context.Add(new RequestContext(requests[i], firstRequestException));
else
returnResult.m_Context.Add(new RequestContext(requests[i], exception));
}
}
internal static void SetResponses(ConnectionReturnResult returnResult) {
if (returnResult==null){
return;
}
GlobalLog.Print("ConnectionReturnResult#" + ValidationHelper.HashString(returnResult) + "::SetResponses() count=" + returnResult.m_Context.Count.ToString());
for (int i = 0; i < returnResult.m_Context.Count; i++)
{
try {
HttpWebRequest request = returnResult.m_Context[i].Request;
#if DEBUG
CoreResponseData coreResponseData = returnResult.m_Context[i].CoreResponse as CoreResponseData;
if (coreResponseData == null)
GlobalLog.DebugRemoveRequest(request);
#endif
request.SetAndOrProcessResponse(returnResult.m_Context[i].CoreResponse);
}
catch(Exception e) {
//ASYNCISSUE
// on error, with more than one callback need to queue others off to another thread
GlobalLog.Print("ConnectionReturnResult#" + ValidationHelper.HashString(returnResult) + "::Exception"+e);
returnResult.m_Context.RemoveRange(0,(i+1));
if (returnResult.m_Context.Count > 0)
{
ThreadPool.UnsafeQueueUserWorkItem(s_InvokeConnectionCallback, returnResult);
}
throw;
}
}
returnResult.m_Context.Clear();
}
private static void InvokeConnectionCallback(object objectReturnResult)
{
ConnectionReturnResult returnResult = (ConnectionReturnResult)objectReturnResult;
SetResponses(returnResult);
}
}
//
// Connection - this is the Connection used to parse
// server responses, queue requests, and pipeline requests
//
internal class Connection : PooledStream {
//
// thread statics - these values must be per thread, because
// other requests and operations can take place concurrently on this Connection.
// Our concern is to make sure that a nested call does not get confused with an
// operation on another thread. Parameter passing cannot be used, because
// the call stack may exit and then reenter the same Connection object.
//
[ThreadStatic]
private static int t_SyncReadNesting;
private const int CRLFSize = 2;
private const long c_InvalidContentLength = -2L;
//
// Buffer manager that allocates and reuses 4k buffers.
//
private const int CachedBufferSize = 4096;
private static PinnableBufferCache s_PinnableBufferCache = new PinnableBufferCache("System.Net.Connection", CachedBufferSize);
//
// Little status line holder.
//
private class StatusLineValues
{
internal int MajorVersion;
internal int MinorVersion;
internal int StatusCode;
internal string StatusDescription;
}
private class WaitListItem
{
private HttpWebRequest request;
private long queueStartTime;
public HttpWebRequest Request
{
get { return request; }
}
public long QueueStartTime
{
get { return queueStartTime; }
}
public WaitListItem(HttpWebRequest request, long queueStartTime)
{
this.request = request;
this.queueStartTime = queueStartTime;
}
}
//
// class members
//
private WebExceptionStatus m_Error;
internal Exception m_InnerException;
internal int m_IISVersion = -1; //-1 means unread
private byte[] m_ReadBuffer;
private bool m_ReadBufferFromPinnableCache; // If we get our m_readBuffer from the Pinnable cache we have to explicitly free it
private int m_BytesRead;
private int m_BytesScanned;
private int m_TotalResponseHeadersLength;
private int m_MaximumResponseHeadersLength;
private long m_MaximumUnauthorizedUploadLength;
private CoreResponseData m_ResponseData;
private ReadState m_ReadState;
private StatusLineValues m_StatusLineValues;
private int m_StatusState;
private List<WaitListItem> m_WaitList;
private ArrayList m_WriteList;
private IAsyncResult m_LastAsyncResult;
private TimerThread.Timer m_RecycleTimer;
private WebParseError m_ParseError;
private bool m_AtLeastOneResponseReceived;
private static readonly WaitCallback m_PostReceiveDelegate = new WaitCallback(PostReceiveWrapper);
private static readonly AsyncCallback m_ReadCallback = new AsyncCallback(ReadCallbackWrapper);
private static readonly AsyncCallback m_TunnelCallback = new AsyncCallback(TunnelThroughProxyWrapper);
private static byte[] s_NullBuffer = new byte[0];
//
// Abort handling variables. When trying to abort the
// connection, we set Aborted = true, and close m_AbortSocket
// if its non-null. m_AbortDelegate, is returned to every
// request from our SubmitRequest method. Calling m_AbortDelegate
// drives us into Abort mode.
//
private HttpAbortDelegate m_AbortDelegate;
private ConnectionGroup m_ConnectionGroup;
private UnlockConnectionDelegate m_ConnectionUnlock;
//
// ReadDone and m_Write - no two vars are so complicated,
// as these two. Used for m_WriteList managment, most be under crit
// section when accessing.
//
// ReadDone tracks the item at the end or
// just recenlty removed from the m_WriteList. While a
// pending BeginRead is in place, we need this to be false, in
// order to indicate to tell the WriteDone callback, that we can
// handle errors/resets. The only exception is when the m_WriteList
// is empty, and there are no outstanding requests, then all it can
// be true.
//
// WriteDone tracks the item just added at the begining of the m_WriteList.
// this needs to be false while we about to write something, but have not
// yet begin or finished the write. Upon completion, its set to true,
// so that DoneReading/ReadStartNextRequest can close the socket, without fear
// of a errand writer still banging away on another thread.
//
private DateTime m_PrepareCloseConnectionSocketCalledUtc;
private DateTime m_AbortSocketCalledUtc;
private DateTime m_IdleSinceUtc;
private HttpWebRequest m_LockedRequest;
private HttpWebRequest m_CurrentRequest; // This is the request whose response is being parsed, same as WriteList[0] but could be different if request was aborted.
private bool m_CanPipeline;
private bool m_Free = true;
private bool m_Idle = true;
private bool m_KeepAlive = true;
private bool m_Pipelining;
private int m_ReservedCount;
private bool m_ReadDone;
private bool m_WriteDone;
private bool m_RemovedFromConnectionList;
private bool m_NonKeepAliveRequestPipelined;
// Pipeline Throttling: m_IsPipelinePaused==true when we stopped and false when it's ok to add to the pipeline.
private bool m_IsPipelinePaused;
private static int s_MaxPipelinedCount = 10;
private static int s_MinPipelinedCount = 5;
#if TRAVE
private bool q_Tunnelling;
#endif
internal override ServicePoint ServicePoint {
get {
return ConnectionGroup.ServicePoint;
}
}
private ConnectionGroup ConnectionGroup {
get {
return m_ConnectionGroup;
}
}
//
// LockedRequest is the request that needs exclusive access to this connection
// the ConnectionGroup should proctect the Connection object from any new
// Requests being queued, until this m_LockedRequest is finished.
//
internal HttpWebRequest LockedRequest {
get {
return m_LockedRequest;
}
set {
HttpWebRequest myLock = m_LockedRequest;
GlobalLog.Print("Connection#" + ValidationHelper.HashString(this) + "::LockedRequest_set() old#"+ ((myLock!=null)?myLock.GetHashCode().ToString():"null") + " new#" + ((value!=null)?value.GetHashCode().ToString():"null"));
if ((object)value == (object)myLock)
{
if (value != null && (object)value.UnlockConnectionDelegate != (object) m_ConnectionUnlock)
{
throw new InternalException();
}
return;
}
object myDelegate = myLock == null? null: myLock.UnlockConnectionDelegate;
if (myDelegate != null && (value != null || (object)m_ConnectionUnlock != (object)myDelegate))
throw new InternalException();
if (value == null)
{
m_LockedRequest = null;
myLock.UnlockConnectionDelegate = null;
return;
}
UnlockConnectionDelegate chkDelegate = value.UnlockConnectionDelegate;
//
// If "value" request was already locking a connection that is not "this", unlock that other connection
//
if ((object)chkDelegate != null)
{
if ((object)chkDelegate == (object)m_ConnectionUnlock)
throw new InternalException();
GlobalLog.Print("Connection#" + ValidationHelper.HashString(this) + "::LockedRequest_set() Unlocking old request Connection");
chkDelegate();
}
value.UnlockConnectionDelegate = m_ConnectionUnlock;
m_LockedRequest = value;
}
}
/// <devdoc>
/// <para>
/// Delegate called when the request is finished using this Connection
/// exclusively. Called in Abort cases and after NTLM authenticaiton completes.
/// </para>
/// </devdoc>
private void UnlockRequest() {
GlobalLog.Print("Connection#" + ValidationHelper.HashString(this) + "::UnlockRequest() LockedRequest#" + ValidationHelper.HashString(LockedRequest));
LockedRequest = null;
if (ConnectionGroup != null) {
GlobalLog.Print("Connection#" + ValidationHelper.HashString(this) + "::UnlockRequest() - forcing call to ConnectionGoneIdle()");
ConnectionGroup.ConnectionGoneIdle();
}
}
#if TRAVE
/*
private string MyLocalEndPoint {
get {
try {
return NetworkStream.InternalSocket.LocalEndPoint.ToString();
}
catch {
return "no connection";
}
}
}
*/
private string MyLocalPort {
get {
try {
if (NetworkStream == null || !NetworkStream.Connected) {
return "no connection";
}
return ((IPEndPoint)NetworkStream.InternalSocket.LocalEndPoint).Port.ToString();
}
catch {
return "no connection";
}
}
}
#endif
internal Connection(ConnectionGroup connectionGroup) : base(null) {
//
// add this Connection to the pool in the connection group,
// keep a weak reference to it
//
m_MaximumUnauthorizedUploadLength = SettingsSectionInternal.Section.MaximumUnauthorizedUploadLength;
if(m_MaximumUnauthorizedUploadLength > 0){
m_MaximumUnauthorizedUploadLength*=1024;
}
m_ResponseData = new CoreResponseData();
m_ConnectionGroup = connectionGroup;
if (ServicePointManager.UseHttpPipeliningAndBufferPooling)
{
m_ReadBuffer = s_PinnableBufferCache.AllocateBuffer();
m_ReadBufferFromPinnableCache = true;
}
else
{
m_ReadBuffer = new byte[CachedBufferSize];
}
m_ReadState = ReadState.Start;
m_WaitList = new List<WaitListItem>();
m_WriteList = new ArrayList();
m_AbortDelegate = new HttpAbortDelegate(AbortOrDisassociate);
m_ConnectionUnlock = new UnlockConnectionDelegate(UnlockRequest);
// for status line parsing
m_StatusLineValues = new StatusLineValues();
m_RecycleTimer = ConnectionGroup.ServicePoint.ConnectionLeaseTimerQueue.CreateTimer();
// the following line must be the last line of the constructor
ConnectionGroup.Associate(this);
m_ReadDone = true;
m_WriteDone = true;
m_Error = WebExceptionStatus.Success;
if (PinnableBufferCacheEventSource.Log.IsEnabled())
{
PinnableBufferCacheEventSource.Log.DebugMessage1("CTOR: In System.Net.Connection.Connnection", this.GetHashCode());
}
}
~Connection() {
if (m_ReadBufferFromPinnableCache)
{
if (PinnableBufferCacheEventSource.Log.IsEnabled())
{
PinnableBufferCacheEventSource.Log.DebugMessage1("DTOR: ERROR Needing to Free m_ReadBuffer in Connection Destructor", m_ReadBuffer.GetHashCode());
}
}
FreeReadBuffer();
}
// If the buffer came from the the pinnable cache, return it to the cache.
// NOTE: This method is called from multiple places in the Connection object
// including this object's finalizer and thus should not access any member objects.
void FreeReadBuffer() {
if (m_ReadBufferFromPinnableCache) {
s_PinnableBufferCache.FreeBuffer(m_ReadBuffer);
m_ReadBufferFromPinnableCache = false;
}
m_ReadBuffer = null;
}
protected override void Dispose(bool disposing) {
if (PinnableBufferCacheEventSource.Log.IsEnabled()) {
PinnableBufferCacheEventSource.Log.DebugMessage1("In System.Net.Connection.Dispose()", this.GetHashCode());
}
base.Dispose(disposing);
}
internal int BusyCount {
get {
return (m_ReadDone?0:1) + 2 * (m_WaitList.Count + m_WriteList.Count) + m_ReservedCount;
}
}
internal int IISVersion{
get{
return m_IISVersion;
}
}
internal bool AtLeastOneResponseReceived {
get {
return m_AtLeastOneResponseReceived;
}
}
/*++
SubmitRequest - Submit a request for sending.
The core submit handler. This is called when a request needs to be
submitted to the network. This routine is asynchronous; the caller
passes in an HttpSubmitDelegate that we invoke when the caller
can use the underlying network. The delegate is invoked with the
stream that it can right to.
On the Sync path, we work by attempting to gain control of the Connection
for writing and reading. If some other thread is using the Connection,
We wait inside of a LazyAsyncResult until it is availble.
Input:
request - request that's being submitted.
SubmitDelegate - Delegate to be invoked.
forcedsubmit - Queue the request even if connection is going to close.
Returns:
True when the request will be handled by this connection.
False when the request cannot be handled by this connection.
--*/
// userReqeustThread says whether we can post IO from this thread or not.
[SuppressMessage("Microsoft.Reliability","CA2002:DoNotLockOnObjectsWithWeakIdentity", Justification="Re-Baseline System violations from 3.5 SP1 due to added parameter")]
internal bool SubmitRequest(HttpWebRequest request, bool forcedsubmit)
{
GlobalLog.Enter("Connection#" + ValidationHelper.HashString(this) + "::SubmitRequest", "request#" + ValidationHelper.HashString(request));
GlobalLog.ThreadContract(ThreadKinds.Unknown, "Connection#" + ValidationHelper.HashString(this) + "::SubmitRequest");
GlobalLog.Print("Connection#" + ValidationHelper.HashString(this) + "::SubmitRequest() Free:" + m_Free.ToString() + " m_WaitList.Count:" + m_WaitList.Count.ToString());
TriState startRequestResult = TriState.Unspecified;
ConnectionReturnResult returnResult = null;
bool expiredIdleConnection = false;
// See if the connection is free, and if the underlying socket or
// stream is set up. If it is, we can assign this connection to the
// request right now. Otherwise we'll have to put this request on
// on the wait list until it its turn.
lock(this)
{
request.AbortDelegate = m_AbortDelegate;
if (request.Aborted)
{
// Note that request is not on the connection list yet and Abort() will push the response on the request
GlobalLog.Leave("Connection#" + ValidationHelper.HashString(this) + "::SubmitRequest - (Request was aborted before being submitted)", true);
UnlockIfNeeded(request);
return true;
}
//
// There is a race condition between FindConnection and PrepareCloseConnectionSocket
// Some request may already try to submit themselves while the connection is dying.
//
// Retry if that's the case
//
if (!CanBePooled)
{
GlobalLog.Leave("Connection#" + ValidationHelper.HashString(this) + "::SubmitRequest", "false - can't be pooled");
UnlockIfNeeded(request);
return false;
}
//
// There is a race condition between SubmitRequest and FindConnection. A non keep-alive request may
// get submitted on this connection just after we check for it. So make sure that if we are queueing
// behind non keep-alive request then its a forced submit.
// Retry if that's not the case.
//
if (!forcedsubmit && NonKeepAliveRequestPipelined)
{
GlobalLog.Leave("Connection#" + ValidationHelper.HashString(this) + "::SubmitRequest", "false - behind non keep-alive request");
UnlockIfNeeded(request);
return false;
}
// See if our timer still matches the SerivcePoint. If not, get rid of it.
if (m_RecycleTimer.Duration != ServicePoint.ConnectionLeaseTimerQueue.Duration) {
m_RecycleTimer.Cancel();
m_RecycleTimer = ServicePoint.ConnectionLeaseTimerQueue.CreateTimer();
}
//
// If the connection level KeepAlive timer has expired, we need to ensure that the connection will
// be closed. In order to avoid failing any requests that may currently be written and waiting for
// a response, we just set the current request up so that it will close the connection on completion.
// Modifying the submitted request like this is a bad pattern, but changing this now would potentially
// introduce side-effects that might affect application compatibility.
//
// This will result in m_NonKeepAliveRequestPipelined being set to true at the connection level later
// in this method, which causes the ConnectionGroup to avoid queueing requests to this connection if
// possible.
//
if (m_RecycleTimer.HasExpired) {
request.KeepAlive = false;
}
//
// If the connection has already been locked by another request, then
// we fail the submission on this Connection.
//
if (LockedRequest != null && LockedRequest != request) {
GlobalLog.Leave("Connection#" + ValidationHelper.HashString(this) + "::SubmitRequest", "false");
return false;
}
//free means no one in the wait list. We should only add a request
//if the request can pipeline, or pipelining isn't available
GlobalLog.Print("Connection#" + ValidationHelper.HashString(this) + "::SubmitRequest WriteDone:" + m_WriteDone.ToString() + ", ReadDone:" + m_ReadDone.ToString() + ", m_WriteList.Count:" + m_WriteList.Count.ToString());
//
// If this request is marked as non keep-alive, we should stop pipelining more requests on this
// connection. The keep-alive context is transfered to the connection from request only after we start
// receiving response for the request.
//
if (!forcedsubmit && !m_NonKeepAliveRequestPipelined) {
m_NonKeepAliveRequestPipelined = (!request.KeepAlive && !request.NtlmKeepAlive);
}
//
// This statement determines if a request will be placed on m_WriteList or on m_WaitList.
//
// Several conditions have to be true for a write to be possible. First, there must not be
// a write in progress, and the connection must not have received or sent a "connection: close"
// header. Those conditions are tracked by m_Free and m_WriteDone. If both are true, the
// m_WriteList must also either be empty, or able to pipeline another request.
//
// The connection should never pipeline a force submitted request, as this implies a non
// keep-alive request is ahead in the pipeline, and the request will likely fail. However,
// if no requests are on m_WriteList then we can assume that the non-keep alive request was
// cancelled, and it is safe to write the force submitted request.
//
if (m_Free && m_WriteDone && (m_WriteList.Count == 0 || (request.Pipelined && !request.HasEntityBody && m_CanPipeline && m_Pipelining && !m_IsPipelinePaused && !forcedsubmit))) {
// Connection is free. Mark it as busy and see if underlying
// socket is up.
GlobalLog.Print("Connection#" + ValidationHelper.HashString(this) + "::SubmitRequest - Free ");
m_Free = false;
// This codepath handles the case where the server has closed the Connection by
// returning false below: the request will be resubmitted on a different Connection.
startRequestResult = StartRequest(request, true);
if (startRequestResult == TriState.Unspecified)
{
Debug.Assert(m_WriteList.Count == 0);
expiredIdleConnection = true;
PrepareCloseConnectionSocket(ref returnResult);
// Hard Close the socket.
Close(0);
}
}
else {
//
// Requests that are added to m_WaitList will not be written to the connection until another
// completed request pulls them from m_WaitList to m_WriteList. If the connection is later closed,
// the requests waiting in m_WaitList will be retried on another connection.
//
m_WaitList.Add(new WaitListItem(request, NetworkingPerfCounters.GetTimestamp()));
NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.HttpWebRequestQueued);
GlobalLog.Print("Connection#" + ValidationHelper.HashString(this) + "::SubmitRequest - Request added to WaitList#"+ValidationHelper.HashString(request));
#if TRAVE
if (q_Tunnelling) {
GlobalLog.Print("Connection#" + ValidationHelper.HashString(this) + "::SubmitRequest() MyLocalPort:" + MyLocalPort + " ERROR: adding HttpWebRequest#" + ValidationHelper.HashString(request) +" to tunnelling WaitList");
}
else {
GlobalLog.Print("Connection#" + ValidationHelper.HashString(this) + "::SubmitRequest() MyLocalPort:" + MyLocalPort + " adding HttpWebRequest#" + ValidationHelper.HashString(request) +" to non-tunnelling WaitList m_WaitList.Count:" + m_WaitList.Count);
}
#endif
CheckNonIdle();
}
}
if (expiredIdleConnection)
{
GlobalLog.Leave("Connection#" + ValidationHelper.HashString(this) + "::SubmitRequest(), expired idle connection", false);
ConnectionReturnResult.SetResponses(returnResult);
return false;
}
GlobalLog.DebugAddRequest(request, this, 0);
if(Logging.On)Logging.Associate(Logging.Web, this, request);
if (startRequestResult != TriState.Unspecified) {
CompleteStartRequest(true, request, startRequestResult);
}
// On Sync, we wait for the Connection to be come availble here,
if (!request.Async)
{
object responseObject = request.ConnectionAsyncResult.InternalWaitForCompletion();
ConnectStream writeStream = responseObject as ConnectStream;
AsyncTriState triStateAsync = null;
if (writeStream == null)
triStateAsync = responseObject as AsyncTriState;
GlobalLog.Print("Connection#" + ValidationHelper.HashString(this) + "::SubmitRequest() Pipelining:"+m_Pipelining);
if (startRequestResult == TriState.Unspecified && triStateAsync != null) {
// May need to recreate Connection here (i.e. call Socket.Connect)
CompleteStartRequest(true, request, triStateAsync.Value);
}
else if (writeStream != null)
{
// return the Stream to the Request
request.SetRequestSubmitDone(writeStream);
}
#if DEBUG
else if (responseObject is Exception)
{
Exception exception = responseObject as Exception;
WebException webException = responseObject as WebException;
GlobalLog.Leave("Connection#" + ValidationHelper.HashString(this) + "::SubmitRequest (SYNC) - Error waiting for a connection: " + exception.Message,
"Status:" + (webException == null? exception.GetType().FullName: (webException.Status.ToString() + " Internal Status: " + webException.InternalStatus.ToString())));
return true;
}
#endif
}
GlobalLog.Leave("Connection#" + ValidationHelper.HashString(this) + "::SubmitRequest", true);
return true;
}
private void UnlockIfNeeded(HttpWebRequest request) {
if (LockedRequest == request) {
UnlockRequest();
}
}
// Wrapper for TriState for marhshalling across Thread boundaries
private class AsyncTriState {
public TriState Value;
public AsyncTriState(TriState newValue) {
Value = newValue;
}
}
/*++
StartRequest - Start a request going.
Routine to start a request. Called when we know the connection is
free and we want to get a request going. This routine initializes
some state, adds the request to the write queue, and checks to
see whether or not the underlying connection is alive. If it's
not, it queues a request to get it going. If the connection
was alive we call the callback delegate of the request.
CompleteStartRequest should be called with the result of StartRequest,
in order to handle any necessary socket reconnects and call the request
write callback.
This routine MUST BE called with the critcal section held.
Input:
request - request that's being started.
canPollRead - whether the calling code handles
Unspecified due to the Connection
being closed by the server.
Returns:
True if the underlying socket is closed and needs to be connected.
False if the underlying socket is healthy and the request is started.
Unspecified if the socket is open but is otherwise unhealthy.
--*/
private TriState StartRequest(HttpWebRequest request, bool canPollRead)
{
GlobalLog.Enter(
"Connection#" + ValidationHelper.HashString(this) +
"::StartRequest",
"HttpWebRequest#" + ValidationHelper.HashString(request) +
" WriteDone:"+ m_WriteDone +
" ReadDone:" + m_ReadDone +
" WaitList:" + m_WaitList.Count +
" WriteList:" + m_WriteList.Count);
GlobalLog.ThreadContract(ThreadKinds.Unknown,
"Connection#" + ValidationHelper.HashString(this) +
"::StartRequest");
if (m_WriteList.Count == 0)
{
// check if we consider connection timed out
if (ServicePoint.MaxIdleTime != -1 &&
m_IdleSinceUtc != DateTime.MinValue &&
m_IdleSinceUtc +
TimeSpan.FromMilliseconds(ServicePoint.MaxIdleTime) <
DateTime.UtcNow)
{
// This idle keep-alive connection timed out.
GlobalLog.Leave(
"Connection#" + ValidationHelper.HashString(this) +
"::StartRequest()" +
" Expired connection was idle for "
+ (int)
((DateTime.UtcNow - m_IdleSinceUtc).TotalSeconds) +
" secs, request will be retried: #" +
ValidationHelper.HashString(request));
return TriState.Unspecified; // don't use it
} else if (canPollRead) {
// Not timed out from our perspective.
// Check if the connection can be reused.
if (!IsConnectionReusable()) {
GlobalLog.Leave(
"Connection#" + ValidationHelper.HashString(this) +
"::StartRequest() " +
"Idle connection remotely closed, " +
"request will be retried: #" +
ValidationHelper.HashString(request));
return TriState.Unspecified; // don't use it
}
}
}
TriState needReConnect = TriState.False;
// Starting a request means the connection is not idle anymore
m_IdleSinceUtc = DateTime.MinValue;
// Initialze state, and add the request to the write queue.
//
// Note that m_Pipelining shold be only set here but the sanity check is made by the caller
// means if the caller has found that it is safe to pipeline the below result must be true as well
//
if (!m_IsPipelinePaused)
m_IsPipelinePaused = m_WriteList.Count >= s_MaxPipelinedCount;
m_Pipelining = m_CanPipeline && request.Pipelined && (!request.HasEntityBody);
// start of write process, disable done-ness flag
GlobalLog.Print("Connection#" + ValidationHelper.HashString(this) + "::StartRequest() setting WriteDone:" + m_WriteDone.ToString() + " to false");
m_WriteDone = false;
GlobalLog.Print("Connection#" + ValidationHelper.HashString(this) + "::StartRequest() m_WriteList adding HttpWebRequest#" + ValidationHelper.HashString(request));
m_WriteList.Add(request);
GlobalLog.Print(m_WriteList.Count+" requests queued");
CheckNonIdle();
// with no network stream around, we will have to create one, therefore, we can't have
// the possiblity to even have a DoneReading().
if (IsInitalizing)
needReConnect = TriState.True;
#if TRAVE
if (request.IsTunnelRequest) {
GlobalLog.Print("Connection#" + ValidationHelper.HashString(this) + "::StartRequest() MyLocalPort:" + MyLocalPort + " setting Tunnelling to true HttpWebRequest#" + ValidationHelper.HashString(request));
q_Tunnelling = true;
}
else {
GlobalLog.Assert(!q_Tunnelling, "Connection#{0}::StartRequest()|MyLocalPort:{1} ERROR: Already tunnelling during non-tunnel request HttpWebRequest#{2}.", ValidationHelper.HashString(this), MyLocalPort, ValidationHelper.HashString(request));
}
#endif
GlobalLog.Leave("Connection#" + ValidationHelper.HashString(this) + "::StartRequest", needReConnect.ToString());
return needReConnect;
}
private bool IsConnectionReusable() {
try {
if (PollRead()) {
// PollRead() returns true if there is
// data still left to read from the socket or
// the socket has been closed (FIN). So, we can't
// reuse this connection.
return false;
}
}
catch (SocketException ex) {
// PollRead() can also throw SocketException for other problems
// with the socket (i.e. RST).
if (Logging.On) Logging.PrintError(Logging.Web, this, "IsConnectionReusable", ex.ToString());
return false;
}
return true;
}
private void CompleteStartRequest(bool onSubmitThread, HttpWebRequest request, TriState needReConnect) {
GlobalLog.Enter("Connection#" + ValidationHelper.HashString(this) + "::CompleteStartRequest", ValidationHelper.HashString(request));
GlobalLog.ThreadContract(ThreadKinds.Unknown, "Connection#" + ValidationHelper.HashString(this) + "::CompleteStartRequest");
if (needReConnect == TriState.True) {
// Socket is not alive.
GlobalLog.Print("Connection#" + ValidationHelper.HashString(this) + "::CompleteStartRequest() Queue StartConnection Delegate ");
try {
if (request.Async) {
CompleteStartConnection(true, request);
}
else if (onSubmitThread) {
CompleteStartConnection(false, request);
}
// else - fall through and wake up other thread
}
catch (Exception exception) {
GlobalLog.Print("Connection#" + ValidationHelper.HashString(this) + "::CompleteStartRequest(): exception: " + exception.ToString());
if (NclUtilities.IsFatal(exception)) throw;
//
// Should not be here because CompleteStartConnection and below tries to catch everything
//
GlobalLog.Assert(exception.ToString());
}
// If neeeded wake up other thread where SubmitRequest was called
if (!request.Async) {
GlobalLog.Print("Connection#" + ValidationHelper.HashString(this) + "::CompleteStartRequest() Invoking Async Result");
request.ConnectionAsyncResult.InvokeCallback(new AsyncTriState(needReConnect));
}
GlobalLog.Leave("Connection#" + ValidationHelper.HashString(this) + "::CompleteStartRequest", "needReConnect");
return;
}
//
// From now on the request.SetRequestSubmitDone must be called or it may hang
// For a sync request the write side reponse windowwas opened in HttpWebRequest.SubmitRequest
if (request.Async)
request.OpenWriteSideResponseWindow();
ConnectStream writeStream = new ConnectStream(this, request);
// Call the request to let them know that we have a write-stream, this might invoke Send() call
if (request.Async || onSubmitThread) {
request.SetRequestSubmitDone(writeStream);
}
else {
GlobalLog.Print("Connection#" + ValidationHelper.HashString(this) + "::CompleteStartRequest() Invoking Async Result");
request.ConnectionAsyncResult.InvokeCallback(writeStream);
}
GlobalLog.Leave("Connection#" + ValidationHelper.HashString(this) + "::CompleteStartRequest");
}