Welcome to mirror list, hosted at ThFree Co, Russian Federation.

StateRuntime.cs « State « System.Web « referencesource « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: c354c95e0f6abb606e50e3cee54f45c9223a0ce5 (plain)
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
//------------------------------------------------------------------------------
// <copyright file="StateRuntime.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>                                                                
//------------------------------------------------------------------------------

/*
 * StateWebRuntime
 * 
 * Copyright (c) 1998-1999, Microsoft Corporation
 * 
 */

namespace System.Web.SessionState {
    using System.Configuration;
    using System.Globalization;
    using System.IO;    
    using System.Runtime.InteropServices;   
    using System.Security.Permissions;
    using System.Threading;
    using System.Web;
    using System.Web.Caching;
    using System.Web.Configuration;
    using System.Web.Util;


    /// <internalonly/>
    /// <devdoc>
    /// </devdoc>
    [ComImport, Guid("7297744b-e188-40bf-b7e9-56698d25cf44"), System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)]
    public interface IStateRuntime {

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
        [SecurityPermission(SecurityAction.InheritanceDemand, Unrestricted = true)]
        void StopProcessing();

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>

        [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
        [SecurityPermission(SecurityAction.InheritanceDemand, Unrestricted = true)]
        void ProcessRequest(
               [In, MarshalAs(UnmanagedType.SysInt)]
               IntPtr tracker,
               [In, MarshalAs(UnmanagedType.I4)]
               int verb,
               [In, MarshalAs(UnmanagedType.LPWStr)]
               string uri,
               [In, MarshalAs(UnmanagedType.I4)]
               int exclusive,
               [In, MarshalAs(UnmanagedType.I4)]
               int timeout,
               [In, MarshalAs(UnmanagedType.I4)]
               int lockCookieExists,
               [In, MarshalAs(UnmanagedType.I4)]
               int lockCookie,
               [In, MarshalAs(UnmanagedType.I4)]
               int contentLength,
               [In, MarshalAs(UnmanagedType.SysInt)]
               IntPtr content);

        [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
        [SecurityPermission(SecurityAction.InheritanceDemand, Unrestricted = true)]
        void ProcessRequest(
               [In, MarshalAs(UnmanagedType.SysInt)]
               IntPtr tracker,
               [In, MarshalAs(UnmanagedType.I4)]
               int verb,
               [In, MarshalAs(UnmanagedType.LPWStr)]
               string uri,
               [In, MarshalAs(UnmanagedType.I4)]
               int exclusive,
               [In, MarshalAs(UnmanagedType.I4)]
               int extraFlags,
               [In, MarshalAs(UnmanagedType.I4)]
               int timeout,
               [In, MarshalAs(UnmanagedType.I4)]
               int lockCookieExists,
               [In, MarshalAs(UnmanagedType.I4)]
               int lockCookie,
               [In, MarshalAs(UnmanagedType.I4)]
               int contentLength,
               [In, MarshalAs(UnmanagedType.SysInt)]
               IntPtr content);

    }


    /// <internalonly/>
    /// <devdoc>
    /// </devdoc>
    [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
    public sealed class StateRuntime : IStateRuntime {
        static StateRuntime() {
            WebConfigurationFileMap webFileMap = new WebConfigurationFileMap();
            UserMapPath mapPath = new UserMapPath(webFileMap);
            HttpConfigurationSystem.EnsureInit(mapPath, false, true);

            StateApplication app = new StateApplication();

            HttpApplicationFactory.SetCustomApplication(app);

            PerfCounters.OpenStateCounters();
            ResetStateServerCounters();
        }


        /// <devdoc>
        ///    <para>
        ///       Initializes a new instance of the <see cref='System.Web.State.StateRuntime'/>
        ///       class.
        ///     </para>
        /// </devdoc>
        public StateRuntime() {
        }

        /*
         * Shutdown runtime
         */

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public void StopProcessing() {
            ResetStateServerCounters();
            HttpRuntime.Close();
        }

        static void ResetStateServerCounters() {
            PerfCounters.SetStateServiceCounter(StateServicePerfCounter.STATE_SERVICE_SESSIONS_TOTAL, 0);
            PerfCounters.SetStateServiceCounter(StateServicePerfCounter.STATE_SERVICE_SESSIONS_ACTIVE, 0);
            PerfCounters.SetStateServiceCounter(StateServicePerfCounter.STATE_SERVICE_SESSIONS_TIMED_OUT, 0);
            PerfCounters.SetStateServiceCounter(StateServicePerfCounter.STATE_SERVICE_SESSIONS_ABANDONED, 0);
        }

        public void ProcessRequest(
                  IntPtr tracker,
                  int verb,
                  string uri,
                  int exclusive,
                  int timeout,
                  int lockCookieExists,
                  int lockCookie,
                  int contentLength,
                  IntPtr content
                  ) {
            ProcessRequest(
                  tracker,
                  verb,
                  uri,
                  exclusive,
                  0,
                  timeout,
                  lockCookieExists,
                  lockCookie,
                  contentLength,
                  content);
        }

        /*
         * Process one ISAPI request
         *
         * @param ecb ECB
         */

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public void ProcessRequest(
                  IntPtr tracker,
                  int verb,
                  string uri,
                  int exclusive,
                  int extraFlags,
                  int timeout,
                  int lockCookieExists,
                  int lockCookie,
                  int contentLength,
                  IntPtr content
                  ) {

            StateHttpWorkerRequest  wr;

            wr = new StateHttpWorkerRequest(
                       tracker, (UnsafeNativeMethods.StateProtocolVerb) verb, uri, 
                       (UnsafeNativeMethods.StateProtocolExclusive) exclusive, extraFlags, timeout, 
                       lockCookieExists, lockCookie, contentLength, content);

            HttpRuntime.ProcessRequest(wr);
        }
    }

    internal static class StateHeaders {
        internal const String EXCLUSIVE_NAME = "Http_Exclusive";
        internal const String EXCLUSIVE_VALUE_ACQUIRE = "acquire";
        internal const String EXCLUSIVE_VALUE_RELEASE = "release";
        internal const String TIMEOUT_NAME = "Http_Timeout";
        internal const String TIMEOUT_NAME_RAW = "Timeout";
        internal const String LOCKCOOKIE_NAME = "Http_LockCookie";
        internal const String LOCKCOOKIE_NAME_RAW = "LockCookie";
        internal const String LOCKDATE_NAME = "Http_LockDate";
        internal const String LOCKDATE_NAME_RAW = "LockDate";
        internal const String LOCKAGE_NAME = "Http_LockAge";
        internal const String LOCKAGE_NAME_RAW = "LockAge";
        internal const String EXTRAFLAGS_NAME = "Http_ExtraFlags";
        internal const String EXTRAFLAGS_NAME_RAW = "ExtraFlags";
        internal const String ACTIONFLAGS_NAME = "Http_ActionFlags";
        internal const String ACTIONFLAGS_NAME_RAW = "ActionFlags";
    };

    internal sealed class CachedContent {
        internal byte[]             _content;
        internal IntPtr             _stateItem; // The pointer to the native memory that points to the psi
        internal bool               _locked;
        internal DateTime           _utcLockDate;
        internal int                _lockCookie;
        internal int                _extraFlags;
        #pragma warning disable 0649
        internal ReadWriteSpinLock  _spinLock;
        #pragma warning restore 0649

        internal CachedContent(
                byte []     content, 
                IntPtr      stateItem,
                bool        locked,
                DateTime    utcLockDate,
                int         lockCookie,
                int         extraFlags) {

            _content = content;
            _stateItem = stateItem;
            _locked = locked;
            _utcLockDate = utcLockDate;
            _lockCookie = lockCookie;
            _extraFlags = extraFlags;
        }
    }

    internal class StateApplication : IHttpHandler {
        CacheItemRemovedCallback _removedHandler;

        internal StateApplication() {
            if (!HttpRuntime.IsFullTrust) {
                // DevDiv #89021: This type passes user-supplied data to unmanaged code, so we need
                // to ensure that it can only be used from within a FullTrust environment.
                throw new InvalidOperationException(SR.GetString(SR.StateApplication_FullTrustOnly));
            }

            _removedHandler = new CacheItemRemovedCallback(this.OnCacheItemRemoved);
        }

        public void ProcessRequest(HttpContext context) {
            // Don't send content-type header.
            context.Response.ContentType = null;

            switch (context.Request.HttpVerb) {
                case HttpVerb.GET:
                    DoGet(context);
                    break;

                case HttpVerb.PUT:
                    DoPut(context);
                    break;

                case HttpVerb.HEAD:
                    DoHead(context);
                    break;

                case HttpVerb.DELETE:
                    DoDelete(context);
                    break;

                default:
                    DoUnknown(context);
                    break;
            }
        }

        public bool IsReusable {
            get { return true; }
        }

        private string CreateKey(HttpRequest request) {
            return CacheInternal.PrefixStateApplication + HttpUtility.UrlDecode(request.RawUrl);
        }

        private void ReportInvalidHeader(HttpContext context, String header) {
            HttpResponse    response;

            response = context.Response;
            response.StatusCode = 400;
            response.Write("<html><head><title>Bad Request</title></head>\r\n");
            response.Write("<body><h1>Http/1.1 400 Bad Request</h1>");
            response.Write("Invalid header <b>" + header + "</b></body></html>");
        }

        private void ReportLocked(HttpContext context, CachedContent content) {
            HttpResponse    response;
            DateTime        localLockDate;
            long            lockAge;

            // Note that due to a 


            response = context.Response;
            response.StatusCode = 423;
            localLockDate = DateTimeUtil.ConvertToLocalTime(content._utcLockDate);
            lockAge = (DateTime.UtcNow - content._utcLockDate).Ticks / TimeSpan.TicksPerSecond;
            response.AppendHeader(StateHeaders.LOCKDATE_NAME_RAW, localLockDate.Ticks.ToString(CultureInfo.InvariantCulture));
            response.AppendHeader(StateHeaders.LOCKAGE_NAME_RAW, lockAge.ToString(CultureInfo.InvariantCulture));
            response.AppendHeader(StateHeaders.LOCKCOOKIE_NAME_RAW, content._lockCookie.ToString(CultureInfo.InvariantCulture));
        }

        private void ReportActionFlags(HttpContext context, int flags) {
            HttpResponse    response;

            // Note that due to a 


            response = context.Response;
            response.AppendHeader(StateHeaders.ACTIONFLAGS_NAME_RAW, flags.ToString(CultureInfo.InvariantCulture));
        }

        private void ReportNotFound(HttpContext context) {
            context.Response.StatusCode = 404;
        }

        bool GetOptionalNonNegativeInt32HeaderValue(HttpContext context, string header, out int value)
        {
            bool headerValid;
            string valueAsString;

            value = -1;
            valueAsString = context.Request.Headers[header];
            if (valueAsString == null) {
                headerValid = true;
            }
            else {
                headerValid = false;
                try {
                    value = Int32.Parse(valueAsString, CultureInfo.InvariantCulture);
                    if (value >= 0) {
                        headerValid = true;
                    }
                }
                catch {
                }
            }

            if (!headerValid) {
                ReportInvalidHeader(context, header);
            }

            return headerValid;
        }

        bool GetRequiredNonNegativeInt32HeaderValue(HttpContext context, string header, out int value)
        {
            bool headerValid = GetOptionalNonNegativeInt32HeaderValue(context, header, out value);
            if (headerValid && value == -1) {
                headerValid = false;
                ReportInvalidHeader(context, header);
            }

            return headerValid;
        }

        bool GetOptionalInt32HeaderValue(HttpContext context, string header, out int value, out bool found)
        {
            bool headerValid;
            string valueAsString;

            found = false;

            value = 0;
            valueAsString = context.Request.Headers[header];
            if (valueAsString == null) {
                headerValid = true;
            }
            else {
                headerValid = false;
                try {
                    value = Int32.Parse(valueAsString, CultureInfo.InvariantCulture);
                    headerValid = true;
                    found = true;
                }
                catch {
                }
            }

            if (!headerValid) {
                ReportInvalidHeader(context, header);
            }

            return headerValid;
        }

        /*
         * Check Exclusive header for get, getexlusive, releaseexclusive
         * use the path as the id
         * Create the cache key
         * follow inproc.
         */
        internal /*public*/ void DoGet(HttpContext context) {
            HttpRequest     request = context.Request;
            HttpResponse    response = context.Response;
            Stream          responseStream;
            byte[]          buf;
            string          exclusiveAccess;
            string          key;
            CachedContent   content;
            CacheEntry      entry;
            int             lockCookie;
            int             timeout;

            key = CreateKey(request);
            entry = (CacheEntry) HttpRuntime.CacheInternal.Get(key, CacheGetOptions.ReturnCacheEntry);
            if (entry == null) {
                ReportNotFound(context);
                return;
            }

            exclusiveAccess = request.Headers[StateHeaders.EXCLUSIVE_NAME];
            content = (CachedContent) entry.Value;
            content._spinLock.AcquireWriterLock();
            try {
                if (content._content == null) {
                    ReportNotFound(context);
                    return;
                }
                
                int initialFlags;

                initialFlags = content._extraFlags;
                if ((initialFlags & (int)SessionStateItemFlags.Uninitialized) != 0) {
                    // It is an uninitialized item.  We have to remove that flag.
                    // We only allow one request to do that.
                    // For details, see inline doc for SessionStateItemFlags.Uninitialized flag.

                    // If initialFlags != return value of CompareExchange, it means another request has
                    // removed the flag.

                    if (initialFlags == Interlocked.CompareExchange(
                                            ref content._extraFlags, 
                                            initialFlags & (~((int)SessionStateItemFlags.Uninitialized)), 
                                            initialFlags)) {
                        ReportActionFlags(context, (int)SessionStateActions.InitializeItem);
                    }
                }

                if (exclusiveAccess == StateHeaders.EXCLUSIVE_VALUE_RELEASE) {
                    if (!GetRequiredNonNegativeInt32HeaderValue(context, StateHeaders.LOCKCOOKIE_NAME, out lockCookie))
                        return;
                     
                    if (content._locked) {
                        if (lockCookie == content._lockCookie) {
                            content._locked = false;
                        }
                        else {
                            ReportLocked(context, content);
                        }
                    }
                    else {
                        // should be locked but isn't.
                        context.Response.StatusCode = 200;
                    }
                } 
                else {
                    if (content._locked) {
                        ReportLocked(context, content);
                        return;
                    }

                    if (exclusiveAccess == StateHeaders.EXCLUSIVE_VALUE_ACQUIRE) {
                        content._locked = true;
                        content._utcLockDate = DateTime.UtcNow;
                        content._lockCookie++;

                        response.AppendHeader(StateHeaders.LOCKCOOKIE_NAME_RAW, (content._lockCookie).ToString(CultureInfo.InvariantCulture));
                    }

                    timeout = (int) (entry.SlidingExpiration.Ticks / TimeSpan.TicksPerMinute);
                    response.AppendHeader(StateHeaders.TIMEOUT_NAME_RAW, (timeout).ToString(CultureInfo.InvariantCulture));
                    responseStream = response.OutputStream;
                    buf = content._content;
                    responseStream.Write(buf, 0, buf.Length);
                    response.Flush();
                }
            }
            finally {
                content._spinLock.ReleaseWriterLock();
            }
        }


        internal /*public*/ void DoPut(HttpContext context) {
            IntPtr  stateItemDelete;

            stateItemDelete = FinishPut(context);
            if (stateItemDelete != IntPtr.Zero) {
                UnsafeNativeMethods.STWNDDeleteStateItem(stateItemDelete);
            }
        }

        unsafe IntPtr FinishPut(HttpContext context) {
            HttpRequest         request = context.Request;   
            HttpResponse        response = context.Response; 
            Stream              requestStream;               
            byte[]              buf;                         
            int                 timeoutMinutes;
            TimeSpan            timeout;
            int                 extraFlags;
            string              key;                         
            CachedContent       content;
            CachedContent       contentCurrent;
            int                 lockCookie;
            int                 lockCookieNew = 1;
            IntPtr              stateItem;
            CacheInternal       cacheInternal = HttpRuntime.CacheInternal;

            /* create the content */
            requestStream = request.InputStream;
            int bufferSize = (int)(requestStream.Length - requestStream.Position);
            buf = new byte[bufferSize];
            requestStream.Read(buf, 0 , buf.Length);

            fixed (byte * pBuf = buf) {
                // The ctor of StateHttpWorkerRequest convert the native pointer address
                // into an array of bytes, and in our we revert it back to an IntPtr
                stateItem = (IntPtr)(*((void **)pBuf));
            }

            /* get headers */
            if (!GetOptionalNonNegativeInt32HeaderValue(context, StateHeaders.TIMEOUT_NAME, out timeoutMinutes)) {
                return stateItem;
            }

            if (timeoutMinutes == -1) {
                timeoutMinutes = SessionStateModule.TIMEOUT_DEFAULT;
            }

            if (timeoutMinutes > SessionStateModule.MAX_CACHE_BASED_TIMEOUT_MINUTES) {
                ReportInvalidHeader(context, StateHeaders.TIMEOUT_NAME);
                return stateItem;
            }

            timeout = new TimeSpan(0, timeoutMinutes, 0);

            bool found;
            if (!GetOptionalInt32HeaderValue(context, StateHeaders.EXTRAFLAGS_NAME, out extraFlags, out found)) {
                return stateItem;
            }

            if (!found) {
                extraFlags = 0;
            }

            /* lookup current value */
            key = CreateKey(request);
            CacheEntry entry = (CacheEntry) cacheInternal.Get(key, CacheGetOptions.ReturnCacheEntry);
            if (entry != null) {
                // DevDivBugs 146875: Expired Session State race condition
                // We make sure we do not overwrite an already existing item with an uninitialized item.
                if (((int)SessionStateItemFlags.Uninitialized & extraFlags) == 1) {
                    return stateItem;
                }
                
                if (!GetOptionalNonNegativeInt32HeaderValue(context, StateHeaders.LOCKCOOKIE_NAME, out lockCookie)) {
                    return stateItem;
                }

                contentCurrent = (CachedContent) entry.Value;
                contentCurrent._spinLock.AcquireWriterLock();
                try {
                    if (contentCurrent._content == null) {
                        ReportNotFound(context);
                        return stateItem;
                    }

                    /* Only set the item if we are the owner */
                    if (contentCurrent._locked && (lockCookie == -1 || lockCookie != contentCurrent._lockCookie)) {
                        ReportLocked(context, contentCurrent);
                        return stateItem;
                    }

                    if (entry.SlidingExpiration == timeout && contentCurrent._content != null) {
                        /* delete the old state item */
                        IntPtr stateItemOld = contentCurrent._stateItem;

                        /* change the item in place */
                        contentCurrent._content = buf;
                        contentCurrent._stateItem = stateItem;
                        contentCurrent._locked = false;
                        return stateItemOld;
                    }

                    /*
                        The timeout has changed.  In this case, we are removing the old item and
                        inserting a new one.
                        Update _extraFlags to ignore the cache item removed callback (this way,
                        we will not decrease the number of active sessions).
                     */
                    contentCurrent._extraFlags |= (int)SessionStateItemFlags.IgnoreCacheItemRemoved;

                    /*
                     * If not locked, keep it locked until it is completely replaced.
                     * Prevent overwriting when we drop the lock.
                     */
                    contentCurrent._locked = true;
                    contentCurrent._lockCookie = 0;
                    lockCookieNew = lockCookie;
                }
                finally {
                    contentCurrent._spinLock.ReleaseWriterLock();
                }
            }

            content = new CachedContent(buf, stateItem, false, DateTime.MinValue, lockCookieNew, extraFlags);
            cacheInternal.UtcInsert(
                    key, content, null, Cache.NoAbsoluteExpiration, timeout,
                    CacheItemPriority.NotRemovable, _removedHandler);

            if (entry == null) {
                IncrementStateServiceCounter(StateServicePerfCounter.STATE_SERVICE_SESSIONS_TOTAL);
                IncrementStateServiceCounter(StateServicePerfCounter.STATE_SERVICE_SESSIONS_ACTIVE);
            }

            return IntPtr.Zero;
        }

        internal /*public*/ void DoDelete(HttpContext context) {
            string          key = CreateKey(context.Request);
            CacheInternal   cacheInternal = HttpRuntime.CacheInternal;
            CachedContent   content = (CachedContent) cacheInternal.Get(key);

            /* If the item isn't there, we probably took too long to run. */
            if (content == null) {
                ReportNotFound(context);
                return;
            }

            int lockCookie;
            if (!GetOptionalNonNegativeInt32HeaderValue(context, StateHeaders.LOCKCOOKIE_NAME, out lockCookie))
                return;

            content._spinLock.AcquireWriterLock();
            try {
                if (content._content == null) {
                    ReportNotFound(context);
                    return;
                }

                /* Only remove the item if we are the owner */
                if (content._locked && (lockCookie == -1 || content._lockCookie != lockCookie)) {
                    ReportLocked(context, content);
                    return;
                }

                /*
                 * If not locked, keep it locked until it is completely removed.
                 * Prevent overwriting when we drop the lock.
                 */
                content._locked = true;
                content._lockCookie = 0;
            }
            finally {
                content._spinLock.ReleaseWriterLock();
            }


            cacheInternal.Remove(key);
        }

        internal /*public*/ void DoHead(HttpContext context) {
            string  key;
            Object  item;

            key = CreateKey(context.Request);
            item = HttpRuntime.CacheInternal.Get(key);
            if (item == null) {
                ReportNotFound(context);
            }
        }

        /*
         * Unknown Http verb. Responds with "400 Bad Request".
         * Override this method to report different Http code.
         */
        internal /*public*/ void DoUnknown(HttpContext context) {
            context.Response.StatusCode = 400;
        }

        unsafe void OnCacheItemRemoved(String key, Object value, CacheItemRemovedReason reason) {
            CachedContent   content;
            IntPtr          stateItem;

            content = (CachedContent) value;

            content._spinLock.AcquireWriterLock();
            try {
                stateItem = content._stateItem;
                content._content = null;
                content._stateItem = IntPtr.Zero;
            }
            finally {
                content._spinLock.ReleaseWriterLock();
            }
           
            UnsafeNativeMethods.STWNDDeleteStateItem(stateItem);

            /* If _extraFlags have IgnoreCacheItemRemoved specified,
                don't update the counters.
             */
            if ((content._extraFlags & (int)SessionStateItemFlags.IgnoreCacheItemRemoved) != 0) {
                Debug.Trace("OnCacheItemRemoved", "OnCacheItemRemoved ignored (item removed, but counters not updated)");
                return;
            }

            switch (reason) {
                case CacheItemRemovedReason.Expired: 
                    IncrementStateServiceCounter(StateServicePerfCounter.STATE_SERVICE_SESSIONS_TIMED_OUT);
                    break;

                case CacheItemRemovedReason.Removed:
                    IncrementStateServiceCounter(StateServicePerfCounter.STATE_SERVICE_SESSIONS_ABANDONED);
                    break;

                default:
                    break;    
            }

            DecrementStateServiceCounter(StateServicePerfCounter.STATE_SERVICE_SESSIONS_ACTIVE);
        }

        private void DecrementStateServiceCounter(StateServicePerfCounter counter) {
            if (HttpRuntime.ShutdownInProgress) {
                return;
            }

            PerfCounters.DecrementStateServiceCounter(counter);
        }

        private void IncrementStateServiceCounter(StateServicePerfCounter counter) {
            if (HttpRuntime.ShutdownInProgress) {
                return;
            }

            PerfCounters.IncrementStateServiceCounter(counter);
        }

    }
}