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
|
//------------------------------------------------------------------------------
// <copyright file="InProcStateClientManager.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.SessionState {
using System.Threading;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.Text;
using System.Collections;
using System.IO;
using System.Web;
using System.Web.Caching;
using System.Web.Util;
using System.Xml;
using System.Collections.Specialized;
using System.Configuration.Provider;
internal sealed class InProcSessionStateStore : SessionStateStoreProviderBase {
internal static readonly int CACHEKEYPREFIXLENGTH = CacheInternal.PrefixInProcSessionState.Length;
internal static readonly int NewLockCookie = 1;
CacheItemRemovedCallback _callback;
SessionStateItemExpireCallback _expireCallback;
/*
* Handle callbacks from the cache for session state expiry
*/
public void OnCacheItemRemoved(String key, Object value, CacheItemRemovedReason reason) {
InProcSessionState state;
String id;
Debug.Trace("SessionOnEnd", "OnCacheItemRemoved called, reason = " + reason);
PerfCounters.DecrementCounter(AppPerfCounter.SESSIONS_ACTIVE);
state = (InProcSessionState) value;
if ((state._flags & (int)SessionStateItemFlags.IgnoreCacheItemRemoved) != 0 ||
(state._flags & (int)SessionStateItemFlags.Uninitialized) != 0) {
Debug.Trace("SessionOnEnd", "OnCacheItemRemoved ignored");
return;
}
switch (reason) {
case CacheItemRemovedReason.Expired:
PerfCounters.IncrementCounter(AppPerfCounter.SESSIONS_TIMED_OUT);
break;
case CacheItemRemovedReason.Removed:
PerfCounters.IncrementCounter(AppPerfCounter.SESSIONS_ABANDONED);
break;
default:
break;
}
TraceSessionStats();
if (_expireCallback != null) {
id = key.Substring(CACHEKEYPREFIXLENGTH);
_expireCallback(id, SessionStateUtility.CreateLegitStoreData(null,
state._sessionItems,
state._staticObjects,
state._timeout));
}
}
private string CreateSessionStateCacheKey(String id) {
return CacheInternal.PrefixInProcSessionState + id;
}
public override void Initialize(string name, NameValueCollection config)
{
if (String.IsNullOrEmpty(name))
name = "InProc Session State Provider";
base.Initialize(name, config);
_callback = new CacheItemRemovedCallback(this.OnCacheItemRemoved);
}
public override bool SetItemExpireCallback(SessionStateItemExpireCallback expireCallback)
{
_expireCallback = expireCallback;
return true;
}
public override void Dispose()
{
}
public override void InitializeRequest(HttpContext context)
{
}
SessionStateStoreData DoGet(HttpContext context,
String id,
bool exclusive,
out bool locked,
out TimeSpan lockAge,
out object lockId,
out SessionStateActions actionFlags) {
string key = CreateSessionStateCacheKey(id);
// Set default return values
locked = false;
lockId = null;
lockAge = TimeSpan.Zero;
actionFlags = 0;
// Not technically necessary for InProc, but we do it to be consistent
// with SQL provider
SessionIDManager.CheckIdLength(id, true /* throwOnFail */);
InProcSessionState state = (InProcSessionState)HttpRuntime.Cache.InternalCache.Get(key);
if (state != null) {
bool lockedByOther; // True if the state is locked by another session
int initialFlags;
initialFlags = (int)state._flags;
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.
Debug.Trace("SessionStateClientSet", "Removing the Uninit flag for item; key = " + key);
if (initialFlags == Interlocked.CompareExchange(
ref state._flags,
initialFlags & (~((int)SessionStateItemFlags.Uninitialized)),
initialFlags)) {
actionFlags = SessionStateActions.InitializeItem;
}
}
if (exclusive) {
lockedByOther = true;
// If unlocked, use a spinlock to test and lock the state.
if (!state._locked) {
state._spinLock.AcquireWriterLock();
try {
if (!state._locked) {
lockedByOther = false;
state._locked = true;
state._utcLockDate = DateTime.UtcNow;
state._lockCookie++;
}
lockId = state._lockCookie;
}
finally {
state._spinLock.ReleaseWriterLock();
}
}
else {
// It's already locked by another request. Return the lockCookie to caller.
lockId = state._lockCookie;
}
}
else {
state._spinLock.AcquireReaderLock();
try {
lockedByOther = state._locked;
lockId = state._lockCookie;
}
finally {
state._spinLock.ReleaseReaderLock();
}
}
if (lockedByOther) {
// Item found, but locked
locked = true;
lockAge = DateTime.UtcNow - state._utcLockDate;
return null;
}
else {
return SessionStateUtility.CreateLegitStoreData(context, state._sessionItems,
state._staticObjects, state._timeout);
}
}
// Not found
return null;
}
public override SessionStateStoreData GetItem(HttpContext context,
String id,
out bool locked,
out TimeSpan lockAge,
out object lockId,
out SessionStateActions actionFlags) {
return DoGet(context, id, false, out locked, out lockAge, out lockId, out actionFlags);
}
public override SessionStateStoreData GetItemExclusive(HttpContext context,
String id,
out bool locked,
out TimeSpan lockAge,
out object lockId,
out SessionStateActions actionFlags) {
return DoGet(context, id, true, out locked, out lockAge, out lockId, out actionFlags);
}
// Unlock an item locked by GetExclusive
// 'lockId' is the lock context returned by previous call to GetExclusive
public override void ReleaseItemExclusive(HttpContext context,
String id,
object lockId) {
Debug.Assert(lockId != null, "lockId != null");
string key = CreateSessionStateCacheKey(id);
int lockCookie = (int)lockId;
SessionIDManager.CheckIdLength(id, true /* throwOnFail */);
InProcSessionState state = (InProcSessionState)HttpRuntime.Cache.InternalCache.Get(key);
/* If the state isn't there, we probably took too long to run. */
if (state == null)
return;
if (state._locked) {
state._spinLock.AcquireWriterLock();
try {
if (state._locked && lockCookie == state._lockCookie) {
state._locked = false;
}
}
finally {
state._spinLock.ReleaseWriterLock();
}
}
}
public override void SetAndReleaseItemExclusive(HttpContext context,
String id,
SessionStateStoreData item,
object lockId,
bool newItem) {
string key = CreateSessionStateCacheKey(id);
bool doInsert = true;
CacheStoreProvider cacheInternal = HttpRuntime.Cache.InternalCache;
int lockCookieForInsert = NewLockCookie;
ISessionStateItemCollection items = null;
HttpStaticObjectsCollection staticObjects = null;
Debug.Assert(item.Items != null, "item.Items != null");
Debug.Assert(item.StaticObjects != null, "item.StaticObjects != null");
Debug.Assert(item.Timeout <= SessionStateModule.MAX_CACHE_BASED_TIMEOUT_MINUTES, "item.Timeout <= SessionStateModule.MAX_CACHE_BASED_TIMEOUT_MINUTES");
SessionIDManager.CheckIdLength(id, true /* throwOnFail */);
if (item.Items.Count > 0) {
items = item.Items;
}
if (!item.StaticObjects.NeverAccessed) {
staticObjects = item.StaticObjects;
}
if (!newItem) {
Debug.Assert(lockId != null, "lockId != null");
InProcSessionState stateCurrent = (InProcSessionState) cacheInternal.Get(key);
int lockCookie = (int)lockId;
/* If the state isn't there, we probably took too long to run. */
if (stateCurrent == null)
return;
Debug.Trace("SessionStateClientSet", "state is inStorage; key = " + key);
Debug.Assert((stateCurrent._flags & (int)SessionStateItemFlags.Uninitialized) == 0, "Should never set an unitialized item; key = " + key);
stateCurrent._spinLock.AcquireWriterLock();
try {
/* Only set the state if we are the owner */
if (!stateCurrent._locked || stateCurrent._lockCookie != lockCookie) {
Debug.Trace("SessionStateClientSet", "Leave because we're not the owner; key = " + key);
return;
}
/* We can change the state in place if the timeout hasn't changed */
if (stateCurrent._timeout == item.Timeout) {
stateCurrent.Copy(
items,
staticObjects,
item.Timeout,
false,
DateTime.MinValue,
lockCookie,
stateCurrent._flags);
// Don't need to insert into the Cache because an in-place copy is good enough.
doInsert = false;
Debug.Trace("SessionStateClientSet", "Changing state inplace; key = " + key);
}
else {
/* We are going to insert a new item to replace the current one in Cache
because the expiry time has changed.
Pleas note that an insert will cause the Session_End to be incorrectly raised.
Please note that the item itself should not expire between now and
where we do UtcInsert below because cacheInternal.Get above have just
updated its expiry time.
*/
stateCurrent._flags |= (int)SessionStateItemFlags.IgnoreCacheItemRemoved;
/* By setting _lockCookie to 0, we prevent an overwriting by ReleaseExclusive
when we drop the lock.
The scenario can happen if another request is polling and trying to prempt
the lock we have on the item.
*/
lockCookieForInsert = lockCookie;
stateCurrent._lockCookie = 0;
}
}
finally {
stateCurrent._spinLock.ReleaseWriterLock();
}
}
if (doInsert) {
Debug.Trace("SessionStateClientSet", "Inserting state into Cache; key = " + key);
InProcSessionState state = new InProcSessionState(
items,
staticObjects,
item.Timeout,
false,
DateTime.MinValue,
lockCookieForInsert,
0);
try {
}
finally {
// protected from ThreadAbortEx
cacheInternal.Insert(key, state, new CacheInsertOptions() {
SlidingExpiration = new TimeSpan(0, state._timeout, 0),
Priority = CacheItemPriority.NotRemovable,
OnRemovedCallback = _callback
});
PerfCounters.IncrementCounter(AppPerfCounter.SESSIONS_TOTAL);
PerfCounters.IncrementCounter(AppPerfCounter.SESSIONS_ACTIVE);
TraceSessionStats();
}
}
}
public override void CreateUninitializedItem(HttpContext context, String id, int timeout) {
string key = CreateSessionStateCacheKey(id);
Debug.Assert(timeout <= SessionStateModule.MAX_CACHE_BASED_TIMEOUT_MINUTES, "item.Timeout <= SessionStateModule.MAX_CACHE_BASED_TIMEOUT_MINUTES");
SessionIDManager.CheckIdLength(id, true /* throwOnFail */);
Debug.Trace("SessionStateClientSet", "Inserting an uninitialized item into Cache; key = " + key);
InProcSessionState state = new InProcSessionState(
null,
null,
timeout,
false,
DateTime.MinValue,
NewLockCookie,
(int)SessionStateItemFlags.Uninitialized);
// DevDivBugs 146875
// We do not want to overwrite an item with an uninitialized item if it is
// already in the cache
try {
}
finally {
// protected from ThreadAbortEx
object existingEntry = HttpRuntime.Cache.InternalCache.Add(key, state, new CacheInsertOptions() {
SlidingExpiration = new TimeSpan(0, timeout, 0),
Priority = CacheItemPriority.NotRemovable,
OnRemovedCallback = _callback
});
if (existingEntry == null) {
PerfCounters.IncrementCounter(AppPerfCounter.SESSIONS_TOTAL);
PerfCounters.IncrementCounter(AppPerfCounter.SESSIONS_ACTIVE);
}
}
}
// Remove an item. Note that the item is originally obtained by GetExclusive
// Same note as Set on lockId
public override void RemoveItem(HttpContext context,
String id,
object lockId,
SessionStateStoreData item) {
Debug.Assert(lockId != null, "lockId != null");
string key = CreateSessionStateCacheKey(id);
CacheStoreProvider cacheInternal = HttpRuntime.Cache.InternalCache;
int lockCookie = (int)lockId;
SessionIDManager.CheckIdLength(id, true /* throwOnFail */);
InProcSessionState state = (InProcSessionState) cacheInternal.Get(key);
/* If the item isn't there, we probably took too long to run. */
if (state == null)
return;
state._spinLock.AcquireWriterLock();
try {
/* Only remove the item if we are the owner */
if (!state._locked || state._lockCookie != lockCookie)
return;
/* prevent overwriting when we drop the lock */
state._lockCookie = 0;
}
finally {
state._spinLock.ReleaseWriterLock();
}
cacheInternal.Remove(key);
TraceSessionStats();
}
// Reset the expire time of an item based on its timeout value
public override void ResetItemTimeout(HttpContext context, String id)
{
string key = CreateSessionStateCacheKey(id);
SessionIDManager.CheckIdLength(id, true /* throwOnFail */);
HttpRuntime.Cache.InternalCache.Get(key);
}
// Create a new SessionStateStoreData.
public override SessionStateStoreData CreateNewStoreData(HttpContext context, int timeout)
{
return SessionStateUtility.CreateLegitStoreData(context, null, null, timeout);
}
// Called during EndRequest event
public override void EndRequest(HttpContext context)
{
}
[System.Diagnostics.Conditional("DBG")]
internal static void TraceSessionStats() {
#if DBG
Debug.Trace("SessionState",
"sessionsTotal=" + PerfCounters.GetCounter(AppPerfCounter.SESSIONS_TOTAL) +
", sessionsActive=" + PerfCounters.GetCounter(AppPerfCounter.SESSIONS_ACTIVE) +
", sessionsAbandoned=" + PerfCounters.GetCounter(AppPerfCounter.SESSIONS_ABANDONED) +
", sessionsTimedout=" + PerfCounters.GetCounter(AppPerfCounter.SESSIONS_TIMED_OUT)
);
#endif
}
}
internal sealed class InProcSessionState {
internal ISessionStateItemCollection _sessionItems;
internal HttpStaticObjectsCollection _staticObjects;
internal int _timeout; // USed to set slidingExpiration in CacheEntry
internal bool _locked; // If it's locked by another thread
internal DateTime _utcLockDate;
internal int _lockCookie;
#pragma warning disable 0649
internal ReadWriteSpinLock _spinLock;
#pragma warning restore 0649
internal int _flags;
internal InProcSessionState(
ISessionStateItemCollection sessionItems,
HttpStaticObjectsCollection staticObjects,
int timeout,
bool locked,
DateTime utcLockDate,
int lockCookie,
int flags) {
Copy(sessionItems, staticObjects, timeout, locked, utcLockDate, lockCookie, flags);
}
internal void Copy(
ISessionStateItemCollection sessionItems,
HttpStaticObjectsCollection staticObjects,
int timeout,
bool locked,
DateTime utcLockDate,
int lockCookie,
int flags) {
this._sessionItems = sessionItems;
this._staticObjects = staticObjects;
this._timeout = timeout;
this._locked = locked;
this._utcLockDate = utcLockDate;
this._lockCookie = lockCookie;
this._flags = flags;
}
}
}
|