File: SessionStateModule.cs

package info (click to toggle)
mono 6.8.0.105%2Bdfsg-3.3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,284,512 kB
  • sloc: cs: 11,172,132; xml: 2,850,069; ansic: 671,653; cpp: 122,091; perl: 59,366; javascript: 30,841; asm: 22,168; makefile: 20,093; sh: 15,020; python: 4,827; pascal: 925; sql: 859; sed: 16; php: 1
file content (1522 lines) | stat: -rw-r--r-- 65,915 bytes parent folder | download | duplicates (6)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
//------------------------------------------------------------------------------
// <copyright file="SessionStateModule.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

/*
 * SessionStateModule
 *
 * Copyright (c) 1998-2002, Microsoft Corporation
 *
 */

namespace System.Web.SessionState {

    using System;
    using System.Threading;
    using System.Collections;
    using System.Configuration;
    using System.IO;
    using System.Web.Caching;
    using System.Web.Util;
    using System.Web.Configuration;
    using System.Xml;
    using System.Security.Cryptography;
    using System.Data.SqlClient;
    using System.Globalization;
    using System.Security.Permissions;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web.Hosting;
    using System.Web.Management;
    using Microsoft.Win32;
    using System.Collections.Concurrent;
    using System.Collections.Generic;

    public delegate void SessionStateItemExpireCallback(
            string id, SessionStateStoreData item);

    class SessionOnEndTargetWorkItem {
        SessionOnEndTarget  _target;
        HttpSessionState    _sessionState;

        internal SessionOnEndTargetWorkItem(SessionOnEndTarget target, HttpSessionState sessionState) {
            _target = target;
            _sessionState = sessionState;
        }

        internal void RaiseOnEndCallback() {
            _target.RaiseOnEnd(_sessionState);
        }
    }

    /*
     * Calls the OnSessionEnd event. We use an object other than the SessionStateModule
     * because the state of the module is unknown - it could have been disposed
     * when a session ends.
     */
    class SessionOnEndTarget {
        internal int _sessionEndEventHandlerCount;

        internal SessionOnEndTarget() {
        }

        internal int SessionEndEventHandlerCount {
            get {
                return _sessionEndEventHandlerCount;
            }
            set {
                _sessionEndEventHandlerCount = value;
            }
        }

        internal void RaiseOnEnd(HttpSessionState sessionState) {
            Debug.Trace("SessionOnEnd", "Firing OnSessionEnd for " + sessionState.SessionID);

            if (_sessionEndEventHandlerCount > 0) {
                HttpApplicationFactory.EndSession(sessionState, this, EventArgs.Empty);
            }
        }

        internal void RaiseSessionOnEnd(String id, SessionStateStoreData item) {
            HttpSessionStateContainer sessionStateContainer = new HttpSessionStateContainer(
                    id,
                    item.Items,
                    item.StaticObjects,
                    item.Timeout,
                    false,
                    SessionStateModule.s_configCookieless,
                    SessionStateModule.s_configMode,
                    true);

            HttpSessionState    sessionState = new HttpSessionState(sessionStateContainer);

            if (HttpRuntime.ShutdownInProgress) {
                // call directly when shutting down
                RaiseOnEnd(sessionState);
            }
            else {
                // post via thread pool
                SessionOnEndTargetWorkItem workItem = new SessionOnEndTargetWorkItem(this, sessionState);
                WorkItem.PostInternal(new WorkItemCallback(workItem.RaiseOnEndCallback));
            }
        }

    }


    /*
     * The sesssion state module provides session state services
     * for an application.
     */

    /// <devdoc>
    ///    <para>[To be supplied.]</para>
    /// </devdoc>
    public sealed class SessionStateModule : ISessionStateModule {

        internal const string SQL_CONNECTION_STRING_DEFAULT = "data source=localhost;Integrated Security=SSPI";
        internal const string STATE_CONNECTION_STRING_DEFAULT = "tcpip=loopback:42424";
        internal const int                  TIMEOUT_DEFAULT = 20;
        internal const SessionStateMode     MODE_DEFAULT = SessionStateMode.InProc;

        private static long                 LOCKED_ITEM_POLLING_INTERVAL = 500; // in milliseconds
        static readonly TimeSpan            LOCKED_ITEM_POLLING_DELTA = new TimeSpan(250 * TimeSpan.TicksPerMillisecond);

        static readonly TimeSpan            DEFAULT_DBG_EXECUTION_TIMEOUT = new TimeSpan(0, 0, System.Web.Compilation.PageCodeDomTreeGenerator.DebugScriptTimeout);

        // When we are using Cache to store session state (InProc and StateServer),
        // can't specify a timeout value larger than 1 year because CacheEntry ctor
        // will throw an exception.
        internal const int                  MAX_CACHE_BASED_TIMEOUT_MINUTES = 365 * 24 * 60;

        bool                                s_oneTimeInit;
        static int                          s_timeout;

        #pragma warning disable 0649
        static ReadWriteSpinLock            s_lock;
        #pragma warning restore 0649

        static bool                         s_trustLevelInsufficient;

        static TimeSpan                     s_configExecutionTimeout;

        static bool                         s_configRegenerateExpiredSessionId;
        static bool                         s_useHostingIdentity;
        internal static HttpCookieMode      s_configCookieless;
        internal static SessionStateMode    s_configMode;
        
        // This is used as a perf optimization for IIS7 Integrated Mode.  If session state is released
        // in ReleaseState, we can disable the EndRequest notification if the mode is InProc or StateServer
        // because neither InProcSessionStateStore.EndRequest nor OutOfProcSessionStateStore.EndRequest
        // are implemented.
        static bool                         s_canSkipEndRequestCall;

        private static bool s_PollIntervalRegLookedUp = false;
        private static object s_PollIntervalRegLock = new object();
        
        private static ConcurrentDictionary<string, int> s_queuedRequestsNumPerSession = new ConcurrentDictionary<string, int>();
        //
        // Check if we can optmize for InProc case.
        // Optimization details:
        //
        // If we are in InProc mode, and cookieless=false, in certain scenarios we
        // can avoid reading the session ID from the cookies because that's an expensive operation.
        // To allow that, we use s_sessionEverSet to keep track of whether we've ever created
        // any session state.
        //
        // If no session has ever be created, we can optimize in the following two cases:
        //
        // Case 1: Page has disabled session state
        // In BeginAcquireState, we usually read the session ID, and reset the timeout value
        // of the session state.  However, since no session has ever been created, we can
        // skip both reading the session id and resetting the timeout.
        //
        // Case 2: Page has enabled session state
        // In this case, we will delay reading (and creating it if not found) the session ID
        // until it's really needed. (e.g. from HttpSessionStateContainer.SessionID)
        //
        // Please note that we optimize only if the app is using SessionIDManager
        // as the session ID provider; otherwise, we do not have knowledge about
        // the provider in order to optimize safely.
        //
        // And we will delay reading the id only if we are using cookie to store the session ID.  If we
        // use cookieless, in the delayed session ID creation scenario, cookieless requires a redirect,
        // and it'll be bad to do that in the middle of a page execution.
        //
        static bool                         s_allowInProcOptimization;
        static bool                         s_sessionEverSet;

        //
        // Another optimization is to delay the creation of a new session state store item
        // until it's needed.
        static bool                         s_allowDelayedStateStoreItemCreation;
        static HttpSessionStateContainer    s_delayedSessionState = new HttpSessionStateContainer();

        /* per application vars */
        EventHandler                   _sessionStartEventHandler;
        Timer                          _timer;
        TimerCallback                  _timerCallback;
        volatile int                   _timerId;
        ISessionIDManager              _idManager;
        bool                           _usingAspnetSessionIdManager;
        SessionStateStoreProviderBase  _store;
        bool                           _supportSessionExpiry;
        IPartitionResolver             _partitionResolver;
        bool                           _ignoreImpersonation;
        readonly SessionOnEndTarget    _onEndTarget = new SessionOnEndTarget();

        /* per request data goes in _rq* variables */
        bool                            _acquireCalled;
        bool                            _releaseCalled;
        HttpSessionStateContainer       _rqSessionState;
        String                          _rqId;
        bool                            _rqIdNew;
        ISessionStateItemCollection     _rqSessionItems;
        HttpStaticObjectsCollection     _rqStaticObjects;
        bool                            _rqIsNewSession;
        bool                            _rqSessionStateNotFound;
        bool                            _rqReadonly;
        HttpContext                     _rqContext;
        HttpAsyncResult                 _rqAr;
        SessionStateStoreData           _rqItem;
        object                          _rqLockId;  // The id of its SessionStateItem ownership
                                                    // If the ownership change hands (e.g. this ownership
                                                    // times out), the lockId of the item at the store
                                                    // will change.
        int                             _rqInCallback;
        DateTime                        _rqLastPollCompleted;
        TimeSpan                        _rqExecutionTimeout;
        bool                            _rqAddedCookie;
        SessionStateActions             _rqActionFlags;
        ImpersonationContext            _rqIctx;
        internal int                    _rqChangeImpersonationRefCount;
        ImpersonationContext            _rqTimerThreadImpersonationIctx;
        bool                            _rqSupportSessionIdReissue;

        /// <devdoc>
        ///    <para>
        ///       Initializes a new instance of the <see cref='System.Web.State.SessionStateModule'/>
        ///       class.
        ///     </para>
        /// </devdoc>
        [SecurityPermission(SecurityAction.Demand, Unrestricted=true)]
        public SessionStateModule() {
        }

        static bool CheckTrustLevel(SessionStateSection config) {
            switch (config.Mode) {
                case SessionStateMode.SQLServer:
                case SessionStateMode.StateServer:
                    return HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Medium);

                default:
                case SessionStateMode.Off:
                case SessionStateMode.InProc: // In-proc session doesn't require any trust level (part of ASURT 124513)
                    return true;
            }
        }

        [AspNetHostingPermission(SecurityAction.Assert, Level=AspNetHostingPermissionLevel.Low)]
        private SessionStateStoreProviderBase SecureInstantiateProvider(ProviderSettings settings) {
            return (SessionStateStoreProviderBase)ProvidersHelper.InstantiateProvider(settings, typeof(SessionStateStoreProviderBase));
        }

        // Create an instance of the custom store as specified in the config file
        SessionStateStoreProviderBase InitCustomStore(SessionStateSection config) {
            string          providerName = config.CustomProvider;
            ProviderSettings  ps;

            if (String.IsNullOrEmpty(providerName)) {
                throw new ConfigurationErrorsException(
                        SR.GetString(SR.Invalid_session_custom_provider, providerName),
                        config.ElementInformation.Properties["customProvider"].Source, config.ElementInformation.Properties["customProvider"].LineNumber);
            }

            ps = config.Providers[providerName];
            if (ps == null) {
                throw new ConfigurationErrorsException(
                        SR.GetString(SR.Missing_session_custom_provider, providerName),
                        config.ElementInformation.Properties["customProvider"].Source, config.ElementInformation.Properties["customProvider"].LineNumber);
            }

            return SecureInstantiateProvider(ps);
        }

        IPartitionResolver InitPartitionResolver(SessionStateSection config) {
            string  partitionResolverType = config.PartitionResolverType;
            Type    resolverType;
            IPartitionResolver  iResolver;

            if (String.IsNullOrEmpty(partitionResolverType)) {
                return null;
            }

            if (config.Mode != SessionStateMode.StateServer &&
                config.Mode != SessionStateMode.SQLServer) {
                    throw new ConfigurationErrorsException(SR.GetString(SR.Cant_use_partition_resolve),
                        config.ElementInformation.Properties["partitionResolverType"].Source, config.ElementInformation.Properties["partitionResolverType"].LineNumber);
            }


            resolverType = ConfigUtil.GetType(partitionResolverType, "partitionResolverType", config);
            ConfigUtil.CheckAssignableType(typeof(IPartitionResolver), resolverType, config, "partitionResolverType");

            iResolver = (IPartitionResolver)HttpRuntime.CreatePublicInstance(resolverType);
            iResolver.Initialize();

            return iResolver;
        }

        ISessionIDManager InitSessionIDManager(SessionStateSection config) {
            string  sessionIDManagerType = config.SessionIDManagerType;
            ISessionIDManager  iManager;

            if (String.IsNullOrEmpty(sessionIDManagerType)) {
                iManager = new SessionIDManager();
                _usingAspnetSessionIdManager = true;
            }
            else {
                Type    managerType;

                managerType = ConfigUtil.GetType(sessionIDManagerType, "sessionIDManagerType", config);
                ConfigUtil.CheckAssignableType(typeof(ISessionIDManager), managerType, config, "sessionIDManagerType");

                iManager = (ISessionIDManager)HttpRuntime.CreatePublicInstance(managerType);
            }

            iManager.Initialize();

            return iManager;
        }

        void InitModuleFromConfig(HttpApplication app, SessionStateSection config) {
            if (config.Mode == SessionStateMode.Off) {
                return;
            }

            app.AddOnAcquireRequestStateAsync(
                    new BeginEventHandler(this.BeginAcquireState),
                    new EndEventHandler(this.EndAcquireState));

            app.ReleaseRequestState += new EventHandler(this.OnReleaseState);
            app.EndRequest += new EventHandler(this.OnEndRequest);

            _partitionResolver = InitPartitionResolver(config);

            switch (config.Mode) {
                case SessionStateMode.InProc:
                    if (HttpRuntime.UseIntegratedPipeline) {
                        s_canSkipEndRequestCall = true;
                    }
                    _store = new InProcSessionStateStore();
                    _store.Initialize(null, null);
                    break;

#if !FEATURE_PAL // FEATURE_PAL does not enable out of proc session state
                case SessionStateMode.StateServer:
                    if (HttpRuntime.UseIntegratedPipeline) {
                        s_canSkipEndRequestCall = true;
                    }
                    _store = new OutOfProcSessionStateStore();
                    ((OutOfProcSessionStateStore)_store).Initialize(null, null, _partitionResolver);
                    break;

                case SessionStateMode.SQLServer:
                    _store = new SqlSessionStateStore();
                    ((SqlSessionStateStore)_store).Initialize(null, null, _partitionResolver);
#if DBG
                    ((SqlSessionStateStore)_store).SetModule(this);
#endif
                    break;
#else // !FEATURE_PAL
                case SessionStateMode.StateServer:
                    throw new NotImplementedException("ROTORTODO");
                    break;

                case SessionStateMode.SQLServer:
                    throw new NotImplementedException("ROTORTODO");
                    break;
#endif // !FEATURE_PAL

                case SessionStateMode.Custom:
                    _store = InitCustomStore(config);
                    break;

                default:
                    break;
            }

            // We depend on SessionIDManager to manage session id
            _idManager = InitSessionIDManager(config);

            if ((config.Mode == SessionStateMode.InProc || config.Mode == SessionStateMode.StateServer) &&
                _usingAspnetSessionIdManager) {
                // If we're using InProc mode or StateServer mode, and also using our own session id module,
                // we know we don't care about impersonation in our all session state store read/write
                // and session id read/write.
                _ignoreImpersonation = true;
            }

        }

        public void Init(HttpApplication app) {
            bool initModuleCalled = false;
            SessionStateSection config = RuntimeConfig.GetAppConfig().SessionState;

            if (!s_oneTimeInit) {
                s_lock.AcquireWriterLock();
                try {
                    if (!s_oneTimeInit) {
                        InitModuleFromConfig(app, config);
                        initModuleCalled = true;

                        if (!CheckTrustLevel(config))
                            s_trustLevelInsufficient = true;

                        s_timeout = (int)config.Timeout.TotalMinutes;

                        s_useHostingIdentity = config.UseHostingIdentity;

                        // See if we can try InProc optimization. See inline doc of s_allowInProcOptimization
                        // for details.
                        if (config.Mode == SessionStateMode.InProc &&
                            _usingAspnetSessionIdManager) {
                            s_allowInProcOptimization = true;
                        }

                        if (config.Mode != SessionStateMode.Custom &&
                            config.Mode != SessionStateMode.Off &&
                            !config.RegenerateExpiredSessionId) {
                            s_allowDelayedStateStoreItemCreation = true;
                        }

                        s_configExecutionTimeout = RuntimeConfig.GetConfig().HttpRuntime.ExecutionTimeout;

                        s_configRegenerateExpiredSessionId = config.RegenerateExpiredSessionId;
                        s_configCookieless = config.Cookieless;
                        s_configMode = config.Mode;

                        // The last thing to set in this if-block.
                        s_oneTimeInit = true;

                        Debug.Trace("SessionStateModuleInit",
                                    "Configuration: _mode=" + config.Mode +
                                    ";Timeout=" + config.Timeout +
                                    ";CookieMode=" + config.Cookieless +
                                    ";SqlConnectionString=" + config.SqlConnectionString +
                                    ";StateConnectionString=" + config.StateConnectionString +
                                    ";s_allowInProcOptimization=" + s_allowInProcOptimization +
                                    ";s_allowDelayedStateStoreItemCreation=" + s_allowDelayedStateStoreItemCreation);

                    }
                }
                finally {
                    s_lock.ReleaseWriterLock();
                }
            }

            if (!initModuleCalled) {
                InitModuleFromConfig(app, config);
            }

            if (s_trustLevelInsufficient) {
                throw new HttpException(SR.GetString(SR.Session_state_need_higher_trust));
            }
        }


        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public void Dispose() {
            if (_timer != null) {
                ((IDisposable)_timer).Dispose();
            }

            if (_store != null) {
                _store.Dispose();
            }
        }

        void ResetPerRequestFields() {
            Debug.Assert(_rqIctx == null, "_rqIctx == null");
            Debug.Assert(_rqChangeImpersonationRefCount == 0, "_rqChangeImpersonationRefCount == 0");

            _rqSessionState = null;
            _rqId = null;
            _rqSessionItems = null;
            _rqStaticObjects = null;
            _rqIsNewSession = false;
            _rqSessionStateNotFound = true;
            _rqReadonly = false;
            _rqItem = null;
            _rqContext = null;
            _rqAr = null;
            _rqLockId = null;
            _rqInCallback = 0;
            _rqLastPollCompleted = DateTime.MinValue;
            _rqExecutionTimeout = TimeSpan.Zero;
            _rqAddedCookie = false;
            _rqIdNew = false;
            _rqActionFlags = 0;
            _rqIctx = null;
            _rqChangeImpersonationRefCount = 0;
            _rqTimerThreadImpersonationIctx = null;
            _rqSupportSessionIdReissue = false;
        }

        /*
         * Add a OnStart event handler.
         *
         * @param sessionEventHandler
         */

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public event EventHandler Start {
            add {
                _sessionStartEventHandler += value;
            }
            remove {
                _sessionStartEventHandler -= value;
            }
        }

        void RaiseOnStart(EventArgs e) {
            if (_sessionStartEventHandler == null)
                return;

            Debug.Trace("SessionStateModuleRaiseOnStart",
                "Session_Start called for session id:" + _rqId);

            // Session_OnStart for ASPCOMPAT pages has to be raised from an STA thread
            // 
            if (HttpRuntime.ApartmentThreading || _rqContext.InAspCompatMode) {
#if !FEATURE_PAL // FEATURE_PAL does not enable COM
                AspCompatApplicationStep.RaiseAspCompatEvent(
                    _rqContext,
                    _rqContext.ApplicationInstance,
                    null,
                    _sessionStartEventHandler,
                    this,
                    e);
#else // !FEATURE_PAL
                throw new NotImplementedException ("ROTORTODO");
#endif // !FEATURE_PAL

            }
            else {
                if (HttpContext.Current == null) {
                    // This can happen if it's called by a timer thread
                    DisposableHttpContextWrapper.SwitchContext(_rqContext);
                }

                _sessionStartEventHandler(this, e);
            }
        }

        /*
         * Fire the OnStart event.
         *
         * @param e
         */
        void OnStart(EventArgs e) {
            RaiseOnStart(e);
        }

        /*
         * Add a OnEnd event handler.
         *
         * @param sessionEventHandler
         */

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public event EventHandler End {
            add {
                lock(_onEndTarget) {
                    if (_store != null && _onEndTarget.SessionEndEventHandlerCount == 0) {
                        _supportSessionExpiry = _store.SetItemExpireCallback(
                                new SessionStateItemExpireCallback(_onEndTarget.RaiseSessionOnEnd));
                    }
                    ++_onEndTarget.SessionEndEventHandlerCount;
                }
            }
            remove {
                lock(_onEndTarget) {
                    --_onEndTarget.SessionEndEventHandlerCount;
                    // 
                    if (_store != null && _onEndTarget.SessionEndEventHandlerCount == 0) {
                        _store.SetItemExpireCallback(null);
                        _supportSessionExpiry = false;
                    }
                }
            }
        }

        /*
         * Acquire session state
         */
        IAsyncResult BeginAcquireState(Object source, EventArgs e, AsyncCallback cb, Object extraData) {
            bool                requiresState;
            bool                isCompleted = true;
            bool                skipReadingId = false;

            Debug.Trace("SessionStateModuleOnAcquireState", "Beginning SessionStateModule::OnAcquireState");

            _acquireCalled = true;
            _releaseCalled = false;
            ResetPerRequestFields();

            _rqContext = ((HttpApplication)source).Context;
            _rqAr = new HttpAsyncResult(cb, extraData);

            ChangeImpersonation(_rqContext, false);

            try {
                if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.AppSvc)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_SESSION_DATA_BEGIN, _rqContext.WorkerRequest);

                /* Notify the store we are beginning to get process request */
                _store.InitializeRequest(_rqContext);

                /* determine if the request requires state at all */
                requiresState = _rqContext.RequiresSessionState;

                // SessionIDManager may need to do a redirect if cookieless setting is AutoDetect
                if (_idManager.InitializeRequest(_rqContext, false, out _rqSupportSessionIdReissue)) {
                    _rqAr.Complete(true, null, null);
                    if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.AppSvc)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_SESSION_DATA_END, _rqContext.WorkerRequest);
                    return _rqAr;
                }

                // See if we can skip reading the session id.  See inline doc of s_allowInProcOptimization
                // for details.
                if (s_allowInProcOptimization &&
                    !s_sessionEverSet &&
                     (!requiresState ||             // Case 1
                      !((SessionIDManager)_idManager).UseCookieless(_rqContext)) ) {  // Case 2

                    skipReadingId = true;

#if DBG
                    if (!requiresState) {
                        // Case 1
                        Debug.Trace("SessionStateModuleOnAcquireState", "Skip reading id because page has disabled session state");
                    }
                    else {
                        // Case 2
                        Debug.Trace("SessionStateModuleOnAcquireState", "Delay reading id because we're using InProc optimization, and we are not using cookieless");
                    }
#endif
                }
                else {
                    /* Get sessionid */
                    _rqId = _idManager.GetSessionID(_rqContext);
                    Debug.Trace("SessionStateModuleOnAcquireState", "Current request id=" + _rqId);
                }

                if (!requiresState) {
                    if (_rqId == null) {
                        Debug.Trace("SessionStateModuleOnAcquireState",
                                    "Handler does not require state, " +
                                    "session id skipped or no id found, " +
                                    "skipReadingId=" + skipReadingId +
                                    "\nReturning from SessionStateModule::OnAcquireState");
                    }
                    else {
                        Debug.Trace("SessionStateModuleOnAcquireState",
                                    "Handler does not require state, " +
                                    "resetting timeout for SessionId=" + _rqId +
                                    "\nReturning from SessionStateModule::OnAcquireState");

                        // Still need to update the sliding timeout to keep session alive.
                        // There is a plan to skip this for perf reason.  But it was postponed to
                        // after Whidbey.
                        _store.ResetItemTimeout(_rqContext, _rqId);
                    }

                    _rqAr.Complete(true, null, null);

                    if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.AppSvc)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_SESSION_DATA_END, _rqContext.WorkerRequest);
                    return _rqAr;
                }

                _rqExecutionTimeout = _rqContext.Timeout;

                // If the page is marked as DEBUG, HttpContext.Timeout will return a very large value (~1 year)
                // In this case, we want to use the executionTimeout value specified in the config to avoid
                // PollLockedSession to run forever.
                if (_rqExecutionTimeout == DEFAULT_DBG_EXECUTION_TIMEOUT) {
                    _rqExecutionTimeout = s_configExecutionTimeout;
                }

                /* determine if we need just read-only access */
                _rqReadonly = _rqContext.ReadOnlySessionState;

                if (_rqId != null) {
                    /* get the session state corresponding to this session id */
                    isCompleted = GetSessionStateItem();
                }
                else if (!skipReadingId) {
                    /* if there's no id yet, create it */
                    bool    redirected = CreateSessionId();

                    _rqIdNew = true;

                    if (redirected) {
                        if (s_configRegenerateExpiredSessionId) {
                            // See inline comments in CreateUninitializedSessionState()
                            CreateUninitializedSessionState();
                        }

                        _rqAr.Complete(true, null, null);

                        if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.AppSvc)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_SESSION_DATA_END, _rqContext.WorkerRequest);
                        return _rqAr;
                    }
                }

                if (isCompleted) {
                    CompleteAcquireState();
                    _rqAr.Complete(true, null, null);
                }

                return _rqAr;
            }
            finally {
                RestoreImpersonation();
            }
        }

        internal bool CreateSessionId() {
            // CreateSessionId should be called only if:
            Debug.Assert(_rqId == null ||               // Session id isn't found in the request, OR

                (_rqSessionStateNotFound &&             // The session state isn't found, AND
                 s_configRegenerateExpiredSessionId &&  // We are regenerating expired session id, AND
                 _rqSupportSessionIdReissue &&          // This request supports session id re-issue, AND
                 !_rqIdNew),                            // The above three condition should imply the session id
                                                        // isn't just created, but is sent by the request.
                "CreateSessionId should be called only if we're generating new id, or re-generating expired one");
            Debug.Assert(_rqChangeImpersonationRefCount > 0, "Must call ChangeImpersonation first");

            bool redirected;
            _rqId = _idManager.CreateSessionID(_rqContext);
            _idManager.SaveSessionID(_rqContext, _rqId, out redirected, out _rqAddedCookie);

            return redirected;
        }

        internal void EnsureStateStoreItemLocked() {
            // DevDiv 665141: 
            // Ensure ownership of the session state item here as the session ID now can be put on the wire (by Response.Flush)
            // and the client can initiate a request before this one reaches OnReleaseState and thus causing a race condition.
            // Note: It changes when we call into the Session Store provider. Now it may happen at BeginAcquireState instead of OnReleaseState.

            // Item is locked yet here only if this is a new session
            if (!_rqSessionStateNotFound) {
                return;
            }

            Debug.Assert(_rqId != null, "Session State ID must exist");
            Debug.Assert(_rqItem != null, "Session State item must exist");

            ChangeImpersonation(_rqContext, false);

            try {
                // Store the item if already have been created
                _store.SetAndReleaseItemExclusive(_rqContext, _rqId, _rqItem, _rqLockId, true /*_rqSessionStateNotFound*/);

                // Lock Session State Item in Session State Store
                LockSessionStateItem();
            }
            catch {
                throw;
            }
            finally {
                RestoreImpersonation();
            }

            // Mark as old session here. The SessionState is fully initialized, the item is locked
            _rqSessionStateNotFound = false;
            s_sessionEverSet = true;
        }
 
        // Called when AcquireState is done.  This function will add the returned
        // SessionStateStore item to the request context.
        void CompleteAcquireState() {
            Debug.Trace("SessionStateModuleOnAcquireState", "Item retrieved=" + (_rqItem != null).ToString(CultureInfo.InvariantCulture));
            bool delayInitStateStoreItem = false;

            Debug.Assert(!(s_allowDelayedStateStoreItemCreation && s_configRegenerateExpiredSessionId),
                "!(s_allowDelayedStateStoreItemCreation && s_configRegenerateExpiredSessionId)");

            try {
                if (_rqItem != null) {
                    _rqSessionStateNotFound = false;

                    if ((_rqActionFlags & SessionStateActions.InitializeItem) != 0) {
                        Debug.Trace("SessionStateModuleOnAcquireState", "Initialize an uninit item");
                        _rqIsNewSession = true;
                    }
                    else {
                        _rqIsNewSession = false;
                    }
                }
                else {
                    _rqIsNewSession = true;
                    _rqSessionStateNotFound = true;

                    if (s_allowDelayedStateStoreItemCreation) {
                        Debug.Trace("SessionStateModuleOnAcquireState", "Delay creating new session state");
                        delayInitStateStoreItem = true;
                    }

                    // We couldn't find the session state.
                    if (!_rqIdNew &&                            // If the request has a session id, that means the session state has expired
                        s_configRegenerateExpiredSessionId &&   // And we're asked to regenerate expired session
                        _rqSupportSessionIdReissue) {           // And this request support session id reissue

                        // We will generate a new session id for this expired session state
                        bool redirected = CreateSessionId();

                        Debug.Trace("SessionStateModuleOnAcquireState", "Complete re-creating new id; redirected=" + redirected);

                        if (redirected) {
                            Debug.Trace("SessionStateModuleOnAcquireState", "Will redirect because we've reissued a new id and it's cookieless");
                            CreateUninitializedSessionState();
                            return;
                        }
                    }
                }

                if (delayInitStateStoreItem) {
                    _rqSessionState = s_delayedSessionState;
                }
                else {
                    InitStateStoreItem(true);
                }

                // Set session state module
                SessionStateUtility.AddHttpSessionStateModuleToContext(_rqContext, this, delayInitStateStoreItem);

                if (_rqIsNewSession) {
                    Debug.Trace("SessionStateModuleOnAcquireState", "Calling OnStart");
                    OnStart(EventArgs.Empty);
                }
            }
            finally {
                if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.AppSvc)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_SESSION_DATA_END, _rqContext.WorkerRequest);
            }

#if DBG
            if (_rqIsNewSession) {
                if (_rqId == null) {
                    Debug.Assert(s_allowInProcOptimization, "s_allowInProcOptimization");
                    Debug.Trace("SessionStateModuleOnAcquireState", "New session: session id reading is delayed"+
                                "\nReturning from SessionStateModule::OnAcquireState");
                }
                else {
                    Debug.Trace("SessionStateModuleOnAcquireState", "New session: SessionId= " + _rqId +
                                "\nReturning from SessionStateModule::OnAcquireState");
                }

            }
            else {
                Debug.Trace("SessionStateModuleOnAcquireState", "Retrieved old session, SessionId= " + _rqId +
                            "\nReturning from SessionStateModule::OnAcquireState");

            }
#endif
        }

        void CreateUninitializedSessionState() {
            Debug.Assert(_rqChangeImpersonationRefCount > 0, "Must call ChangeImpersonation first");

            // When we generate a new session id in cookieless case, and if "reissueExpiredSession" is
            // true, we need to generate a new temporary empty session and save it
            // under the new session id, otherwise when the next request (i.e. when the browser is
            // redirected back to the web server) comes in, we will think it's accessing an expired session.
            _store.CreateUninitializedItem(_rqContext, _rqId, s_timeout);
        }

        internal void InitStateStoreItem(bool addToContext) {
            Debug.Assert(_rqId != null || s_allowInProcOptimization, "_rqId != null || s_allowInProcOptimization");

            ChangeImpersonation(_rqContext, false);
            try {

                if (_rqItem == null) {
                    Debug.Trace("InitStateStoreItem", "Creating new session state");
                    _rqItem = _store.CreateNewStoreData(_rqContext, s_timeout);
                }

                _rqSessionItems = _rqItem.Items;
                if (_rqSessionItems == null) {
                    throw new HttpException(SR.GetString(SR.Null_value_for_SessionStateItemCollection));
                }

                // No check for null because we allow our custom provider to return a null StaticObjects.
                _rqStaticObjects = _rqItem.StaticObjects;

                _rqSessionItems.Dirty = false;

                _rqSessionState = new HttpSessionStateContainer(
                        this,
                        _rqId,            // could be null if we're using InProc optimization
                        _rqSessionItems,
                        _rqStaticObjects,
                        _rqItem.Timeout,
                        _rqIsNewSession,
                        s_configCookieless,
                        s_configMode,
                        _rqReadonly);

                if (addToContext) {
                    SessionStateUtility.AddHttpSessionStateToContext(_rqContext, _rqSessionState);
                }
            }
            finally {
                RestoreImpersonation();
            }
        }

        // Used for InProc session id optimization
        internal string DelayedGetSessionId() {
            Debug.Assert(s_allowInProcOptimization, "Shouldn't be called if we don't allow InProc optimization");
            Debug.Assert(_rqId == null, "Shouldn't be called if we already have the id");
            Debug.Assert(!((SessionIDManager)_idManager).UseCookieless(_rqContext), "We can delay session id only if we are not using cookieless");

            Debug.Trace("DelayedOperation", "Delayed getting session id");

            bool    redirected;

            ChangeImpersonation(_rqContext, false);
            try {
                _rqId = _idManager.GetSessionID(_rqContext);

                if (_rqId == null) {
                    Debug.Trace("DelayedOperation", "Delayed creating session id");

                    redirected = CreateSessionId();
                    Debug.Assert(!redirected, "DelayedGetSessionId shouldn't redirect us here.");
                }
            }
            finally {
                RestoreImpersonation();
            }

            return _rqId;
        }

        void LockSessionStateItem() {
            bool locked;
            TimeSpan lockAge;

            Debug.Assert(_rqId != null, "_rqId != null");
            Debug.Assert(_rqChangeImpersonationRefCount > 0, "Must call ChangeImpersonation first");

            if (!_rqReadonly) {
                SessionStateStoreData storedItem = _store.GetItemExclusive(_rqContext, _rqId, out locked, out lockAge, out _rqLockId, out _rqActionFlags);
                Debug.Assert(storedItem != null, "Must succeed in locking session state item.");
            }
        }
        
        bool GetSessionStateItem() {
            bool            isCompleted = true;
            bool            locked;
            TimeSpan        lockAge;

            Debug.Assert(_rqId != null, "_rqId != null");
            Debug.Assert(_rqChangeImpersonationRefCount > 0, "Must call ChangeImpersonation first");

            if (_rqReadonly) {
                _rqItem = _store.GetItem(_rqContext, _rqId, out locked, out lockAge, out _rqLockId, out _rqActionFlags);
            }
            else {
                _rqItem = _store.GetItemExclusive(_rqContext, _rqId, out locked, out lockAge, out _rqLockId, out _rqActionFlags);
                
                // DevDiv Bugs 146875: WebForm and WebService Session Access Concurrency Issue
                // If we have an expired session, we need to insert the state in the store here to
                // ensure serialized access in case more than one entity requests it simultaneously.
                // If the state has already been created before, CreateUninitializedSessionState is a no-op.
                if (_rqItem == null && locked == false && _rqId != null) {
                    if (!(s_configCookieless == HttpCookieMode.UseUri && s_configRegenerateExpiredSessionId == true)) {
                        CreateUninitializedSessionState();
                        _rqItem = _store.GetItemExclusive(_rqContext, _rqId, out locked, out lockAge, out _rqLockId, out _rqActionFlags);
                    }
                }
            }

            // We didn't get it because it's locked....
            if (_rqItem == null && locked) {
                // 
                if (lockAge >= _rqExecutionTimeout) {
                    /* Release the lock on the item, which is held by another thread*/
                    Debug.Trace("SessionStateModuleOnAcquireState",
                                "Lock timed out, lockAge=" + lockAge +
                                ", id=" + _rqId);

                    _store.ReleaseItemExclusive(_rqContext, _rqId, _rqLockId);
                }

                Debug.Trace("SessionStateModuleOnAcquireState",
                            "Item is locked, will poll, id=" + _rqId);

                isCompleted = false;
                PollLockedSession();
            }

            return isCompleted;
        }

        void PollLockedSession() {
            EnsureRequestTimeout();                        

            if (_timerCallback == null) {
                _timerCallback = new TimerCallback(this.PollLockedSessionCallback);
            }

            if (_timer == null) {
                _timerId++;

                // Only call this method once when setting up timer to poll the session item.
                // It should not be called in timer's callback
                QueueRef();
#if DBG
                if (!Debug.IsTagPresent("Timer") || Debug.IsTagEnabled("Timer"))
#endif
                {
                    if (!s_PollIntervalRegLookedUp)
                        LookUpRegForPollInterval();
                    _timer = new Timer(_timerCallback, _timerId, LOCKED_ITEM_POLLING_INTERVAL, LOCKED_ITEM_POLLING_INTERVAL);
                }
            }
        }

        private void EnsureRequestTimeout() {
            // Request may be blocked in acquiring state longer than execution timeout.
            // In that case, it will be timeout anyway after it gets the session item.
            // So it makes sense to timeout it when waiting longer than executionTimeout.
            if (_rqContext.HasTimeoutExpired) {
                throw new HttpException(SR.GetString(SR.Request_timed_out));
            }
        }

        private static bool IsRequestQueueEnabled {
            get {
                return (AppSettings.RequestQueueLimitPerSession != AppSettings.UnlimitedRequestsPerSession);
            }
        } 

        private void QueueRef() {
            if (!IsRequestQueueEnabled || _rqId == null) { 
                return;
            }

            //
            // Check the limit
            int count = 0;
            s_queuedRequestsNumPerSession.TryGetValue(_rqId, out count);

            if (count >= AppSettings.RequestQueueLimitPerSession) {
                throw new HttpException(SR.GetString(SR.Request_Queue_Limit_Per_Session_Exceeded));
            }

            //
            // Add ref
            s_queuedRequestsNumPerSession.AddOrUpdate(_rqId, 1, (key, value) => value + 1);
        }

        private void DequeRef() {
            if (!IsRequestQueueEnabled || _rqId == null) { 
                return;
            }

            // Decrement the counter
            if (s_queuedRequestsNumPerSession.AddOrUpdate(_rqId, 0, (key, value) => value - 1) == 0) {
                //
                // Remove the element when no more references
                ((ICollection<KeyValuePair<string, int>>)s_queuedRequestsNumPerSession).Remove(new KeyValuePair<string,int>(_rqId, 0));
            }
        }

        [RegistryPermission(SecurityAction.Assert, Unrestricted = true)]
        private static void LookUpRegForPollInterval() {
            lock (s_PollIntervalRegLock) {
                if (s_PollIntervalRegLookedUp)
                    return;
                try {
                    object o = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ASP.NET", "SessionStateLockedItemPollInterval", 0);
                    if (o != null && (o is int || o is uint) && ((int)o) > 0)
                        LOCKED_ITEM_POLLING_INTERVAL = (int) o;
                    s_PollIntervalRegLookedUp = true;
                }
                catch { // ignore exceptions
                }
            }
        }


        void ResetPollTimer() {
            _timerId++;
            if (_timer != null) {
                ((IDisposable)_timer).Dispose();
                _timer = null;
            }
        }

        void ChangeImpersonation(HttpContext context, bool timerThread) {
#if !FEATURE_PAL // FEATURE_PAL doesn't enable impersonation
            _rqChangeImpersonationRefCount++;

            if (_ignoreImpersonation) {
                return;
            }

            // If SQL store isn't using integrated security, and we're using our own session id module,
            // we know we don't care about impersonation in our all session state store read/write
            // and session id read/write.
            if (s_configMode == SessionStateMode.SQLServer &&
                ((SqlSessionStateStore)_store).KnowForSureNotUsingIntegratedSecurity &&
                _usingAspnetSessionIdManager) {
                return;
            }

            // Please note that there are two types of calls coming in.  One is from a request thread,
            // where timerThread==false; the other is from PollLockedSessionCallback, where
            // timerThread==true.

            if (s_useHostingIdentity) {
                // If we're told to use Application Identity, in each case we should impersonate,
                // if not called yet.
                if (_rqIctx == null) {
                    _rqIctx = new ApplicationImpersonationContext();
                }
            }
            else {
                if (timerThread) {
                    // For the timer thread, we should explicity impersonate back to what the HttpContext was
                    // orginally impersonating.
                    _rqTimerThreadImpersonationIctx = new ClientImpersonationContext(context, false);
                }
                else {
                    // For a request thread, if we're told to not use hosting id, there's no need
                    // to do anything special.
                    Debug.Assert(_rqIctx == null, "_rqIctx == null");
                    return;
                }
            }
#endif // !FEATURE_PAL
        }

        void RestoreImpersonation() {
            Debug.Assert(_rqChangeImpersonationRefCount != 0, "_rqChangeImpersonationRefCount != 0");

            _rqChangeImpersonationRefCount--;

            if (_rqChangeImpersonationRefCount == 0) {
                Debug.Assert(!(_rqIctx != null && _rqTimerThreadImpersonationIctx != null), "Should not have mixed mode of impersonation");

                if (_rqIctx != null) {
                    _rqIctx.Undo();
                    _rqIctx = null;
                }

                if (_rqTimerThreadImpersonationIctx != null) {
                    Debug.Assert(_rqContext != null, "_rqContext != null");
                    _rqTimerThreadImpersonationIctx.Undo();
                    _rqTimerThreadImpersonationIctx = null;
                }
            }
        }

        void PollLockedSessionCallback(object state) {
            Debug.Assert(_rqId != null, "_rqId != null");
            Debug.Trace("SessionStateModuleOnAcquireState",
                        "Polling callback called from timer, id=" + _rqId);

            bool isCompleted = false;
            Exception error = null;

            /* check whether we are currently in a callback */
            if (Interlocked.CompareExchange(ref _rqInCallback, 1, 0) != 0)
                return;

            try {
                /*
                 * check whether this callback is for the current request,
                 * and whether sufficient time has passed since the last poll
                 * to try again.
                 */
                int timerId = (int) state;
                if (    (timerId == _timerId) &&
                        (DateTime.UtcNow - _rqLastPollCompleted >= LOCKED_ITEM_POLLING_DELTA)) {

                    ChangeImpersonation(_rqContext, true);

                    try {
                        isCompleted = GetSessionStateItem();
                        _rqLastPollCompleted = DateTime.UtcNow;
                        if (isCompleted) {
                            Debug.Assert(_timer != null, "_timer != null");
                            ResetPollTimer();
                            CompleteAcquireState();
                        }
                    }
                    finally {
                        RestoreImpersonation();
                    }
                }
            }
            catch (Exception e) {
                ResetPollTimer();
                error = e;
            }
            finally {
                Interlocked.Exchange(ref _rqInCallback, 0);
            }

            if (isCompleted || error != null) {
                DequeRef();

                _rqAr.Complete(false, null, error);
            }
        }


        void EndAcquireState(IAsyncResult ar) {
            ((HttpAsyncResult)ar).End();
        }

        // Called by OnReleaseState to get the session id.
        string ReleaseStateGetSessionID() {
            if (_rqId == null) {
                Debug.Assert(s_allowInProcOptimization, "s_allowInProcOptimization");
                DelayedGetSessionId();
            }

            Debug.Assert(_rqId != null, "_rqId != null");
            return _rqId;
        }

        /*
         * Release session state
         */

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        void OnReleaseState(Object source, EventArgs eventArgs) {
            HttpApplication             app;
            HttpContext                 context;
            bool                        setItemCalled = false;

            Debug.Trace("SessionStateOnReleaseState", "Beginning SessionStateModule::OnReleaseState");

            Debug.Assert(!(_rqAddedCookie && !_rqIsNewSession),
                "If session id was added to the cookie, it must be a new session.");

            // !!!
            // Please note that due to InProc session id optimization, this function should not
            // use _rqId directly because it can still be null.  Instead, use DelayedGetSessionId().

            _releaseCalled = true;

            app = (HttpApplication)source;
            context = app.Context;

            ChangeImpersonation(context, false);

            try {
                if (_rqSessionState != null) {
                    bool delayedSessionState = (_rqSessionState == s_delayedSessionState);

                    Debug.Trace("SessionStateOnReleaseState", "Remove session state from context");
                    SessionStateUtility.RemoveHttpSessionStateFromContext(_rqContext, delayedSessionState);

                    /*
                     * Don't store untouched new sessions.
                     */

                    if (
                                // The store doesn't have the session state.
                                // ( Please note we aren't checking _rqIsNewSession because _rqIsNewSession
                                // is lalso true if the item is converted from temp to perm in a GetItemXXX() call.)
                                _rqSessionStateNotFound

                                // OnStart is not defined
                               && _sessionStartEventHandler == null

                               // Nothing has been stored in session state
                               && (delayedSessionState || !_rqSessionItems.Dirty)
                               && (delayedSessionState || _rqStaticObjects == null || _rqStaticObjects.NeverAccessed)
                        ) {

                        Debug.Trace("SessionStateOnReleaseState", "Not storing unused new session.");
                    }
                    else if (_rqSessionState.IsAbandoned) {
                        Debug.Trace("SessionStateOnReleaseState", "Removing session due to abandonment, SessionId=" + _rqId);

                        if (_rqSessionStateNotFound) {
                            // The store provider doesn't have it, and so we don't need to remove it from the store.

                            // However, if the store provider supports session expiry, and we have a Session_End in global.asax,
                            // we need to explicitly call Session_End.
                            if (_supportSessionExpiry) {
                                if (delayedSessionState) {
                                    Debug.Assert(s_allowDelayedStateStoreItemCreation, "s_allowDelayedStateStoreItemCreation");
                                    Debug.Assert(_rqItem == null, "_rqItem == null");

                                    InitStateStoreItem(false /*addToContext*/);
                                }

                                _onEndTarget.RaiseSessionOnEnd(ReleaseStateGetSessionID(), _rqItem);
                            }
                        }
                        else {
                            Debug.Assert(_rqItem != null, "_rqItem cannot null if it's not a new session");

                            // Remove it from the store because the session is abandoned.
                            _store.RemoveItem(_rqContext, ReleaseStateGetSessionID(), _rqLockId, _rqItem);
                        }
                    }
                    else if (!_rqReadonly ||
                             (_rqReadonly &&
                              _rqIsNewSession &&
                              _sessionStartEventHandler != null &&
                              !SessionIDManagerUseCookieless)) {
                        // We need to save it since it isn't read-only
                        // See Dev10 588711: Issuing a redirect from inside of Session_Start event 
                        // triggers an infinite loop when using pages with read-only session state

                        // We save it only if there is no error, and if something has changed (unless it's a new session)
                        if (    context.Error == null   // no error
                                && (    _rqSessionStateNotFound
                                    || _rqSessionItems.Dirty    // SessionItems has changed.
                                    || (_rqStaticObjects != null && !_rqStaticObjects.NeverAccessed) // Static objects have been accessed
                                    || _rqItem.Timeout != _rqSessionState.Timeout   // Timeout value has changed
                                    )
                            ) {

                            if (delayedSessionState) {
                                Debug.Assert(_rqIsNewSession, "Saving a session and delayedSessionState is true: _rqIsNewSession must be true");
                                Debug.Assert(s_allowDelayedStateStoreItemCreation, "Saving a session and delayedSessionState is true: s_allowDelayedStateStoreItemCreation");
                                Debug.Assert(_rqItem == null, "Saving a session and delayedSessionState is true: _rqItem == null");

                                InitStateStoreItem(false /*addToContext*/);
                            }

#if DBG
                            if (_rqSessionItems.Dirty) {
                                Debug.Trace("SessionStateOnReleaseState", "Setting new session due to dirty SessionItems, SessionId=" + _rqId);
                            }
                            else if (_rqStaticObjects != null && !_rqStaticObjects.NeverAccessed) {
                                Debug.Trace("SessionStateOnReleaseState", "Setting new session due to accessed Static Objects, SessionId=" + _rqId);
                            }
                            else if (_rqSessionStateNotFound) {
                                Debug.Trace("SessionStateOnReleaseState", "Setting new session because it's not found, SessionId=" + _rqId);
                            }
                            else {
                                Debug.Trace("SessionStateOnReleaseState", "Setting new session due to options change, SessionId=" + _rqId +
                                            "\n\t_rq.timeout=" + _rqItem.Timeout.ToString(CultureInfo.InvariantCulture) +
                                            ", _rqSessionState.timeout=" + _rqSessionState.Timeout.ToString(CultureInfo.InvariantCulture));
                            }
#endif
                            if (_rqItem.Timeout != _rqSessionState.Timeout) {
                                _rqItem.Timeout = _rqSessionState.Timeout;
                            }

                            s_sessionEverSet = true;
                            setItemCalled = true;
                            _store.SetAndReleaseItemExclusive(_rqContext, ReleaseStateGetSessionID(), _rqItem, _rqLockId, _rqSessionStateNotFound);
                        }
                        else {
                            // Can't save it because of various reason.  Just release our exclusive lock on it.
                            Debug.Trace("SessionStateOnReleaseState", "Release exclusive lock on session, SessionId=" + _rqId);

                            if (!_rqSessionStateNotFound) {
                                Debug.Assert(_rqItem != null, "_rqItem cannot null if it's not a new session");
                                _store.ReleaseItemExclusive(_rqContext, ReleaseStateGetSessionID(), _rqLockId);
                            }
                        }
                    }
#if DBG
                    else {
                        Debug.Trace("SessionStateOnReleaseState", "Session is read-only, ignoring SessionId=" + _rqId);
                    }
#endif

                    Debug.Trace("SessionStateOnReleaseState", "Returning from SessionStateModule::OnReleaseState");
                }

                if (_rqAddedCookie && !setItemCalled && context.Response.IsBuffered()) {
                    _idManager.RemoveSessionID(_rqContext);
                }

            }
            finally {
                RestoreImpersonation();
            }

            // WOS 1679798: PERF: Session State Module should disable EndRequest on successful cleanup
            bool implementsIRequiresSessionState = context.RequiresSessionState;
            if (HttpRuntime.UseIntegratedPipeline 
                && (context.NotificationContext.CurrentNotification == RequestNotification.ReleaseRequestState) 
                && (s_canSkipEndRequestCall || !implementsIRequiresSessionState)) {
                context.DisableNotifications(RequestNotification.EndRequest, 0 /*postNotifications*/);
                _acquireCalled = false;
                _releaseCalled = false;
                ResetPerRequestFields();
            }
        }

        /*
         * End of request processing. Possibly does release if skipped due to errors
         */

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        void OnEndRequest(Object source, EventArgs eventArgs) {
            HttpApplication app;
            HttpContext context;
            String id;

            Debug.Trace("SessionStateOnEndRequest", "Beginning SessionStateModule::OnEndRequest");

            app = (HttpApplication)source;
            context = app.Context;

            /* determine if the request requires state at all */
            if (!context.RequiresSessionState) {
                return;
            }

            ChangeImpersonation(context, false);

            try {
                if (!_releaseCalled) {
                    if (_acquireCalled) {
                        /*
                         * need to do release here if the request short-circuited due to an error
                         */
                        OnReleaseState(source, eventArgs);
                    }
                    else {
                        /*
                         * 'advise' -- update session timeout
                         */

                        if (_rqContext == null) {
                            _rqContext = context;
                        }

                        // We haven't called BeginAcquireState.  So we have to call these InitializeRequest
                        // methods here.
                        bool    dummy;
                        _store.InitializeRequest(_rqContext);
                        _idManager.InitializeRequest(_rqContext, true, out dummy);

                        id = _idManager.GetSessionID(context);
                        if (id != null) {
                            Debug.Trace("SessionStateOnEndRequest", "Resetting timeout for SessionId=" + id);
                            _store.ResetItemTimeout(context, id);
                        }
#if DBG
                        else {
                            Debug.Trace("SessionStateOnEndRequest", "No session id found.");
                        }
#endif
                    }
                }

                /* Notify the store we are finishing a request */
                _store.EndRequest(_rqContext);
            }
            finally {
                _acquireCalled = false;
                _releaseCalled = false;
                RestoreImpersonation();
                ResetPerRequestFields();
            }

            Debug.Trace("SessionStateOnEndRequest", "Returning from SessionStateModule::OnEndRequest");
        }

        internal static void ReadConnectionString(SessionStateSection config, ref string cntString, string propName) {
            ConfigsHelper.GetRegistryStringAttribute(ref cntString, config, propName);
            HandlerBase.CheckAndReadConnectionString(ref cntString, true);
        }

        internal bool SessionIDManagerUseCookieless {
            get {
                // See VSWhidbey 399907
                if (!_usingAspnetSessionIdManager) {
                    return s_configCookieless == HttpCookieMode.UseUri;
                }
                else {
                    return ((SessionIDManager)_idManager).UseCookieless(_rqContext);
                }
            }
        }
        
        public void ReleaseSessionState(HttpContext context) {
            if (HttpRuntime.UseIntegratedPipeline && _acquireCalled && !_releaseCalled) {
                try {
                    OnReleaseState(context.ApplicationInstance, null);
                }
                catch { }
            }
        }

        public Task ReleaseSessionStateAsync(HttpContext context) {
            ReleaseSessionState(context);
            return TaskAsyncHelper.CompletedTask;
        }
    }
}