internal void InitStateStoreItem(bool addToContext)
 {
     this.ChangeImpersonation(this._rqContext, false);
     try
     {
         if (this._rqItem == null)
         {
             this._rqItem = this._store.CreateNewStoreData(this._rqContext, s_timeout);
         }
         this._rqSessionItems = this._rqItem.Items;
         if (this._rqSessionItems == null)
         {
             throw new HttpException(System.Web.SR.GetString("Null_value_for_SessionStateItemCollection"));
         }
         this._rqStaticObjects      = this._rqItem.StaticObjects;
         this._rqSessionItems.Dirty = false;
         this._rqSessionState       = new HttpSessionStateContainer(this, this._rqId, this._rqSessionItems, this._rqStaticObjects, this._rqItem.Timeout, this._rqIsNewSession, s_configCookieless, s_configMode, this._rqReadonly);
         if (addToContext)
         {
             SessionStateUtility.AddHttpSessionStateToContext(this._rqContext, this._rqSessionState);
         }
     }
     finally
     {
         this.RestoreImpersonation();
     }
 }
Beispiel #2
0
        public override void SetAndReleaseItemExclusive(HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem)
        {
            System.Web.UnsafeNativeMethods.SessionNDMakeRequestResults results;
            byte[] buffer;
            int    num;
            int    num2;

            try
            {
                SessionStateUtility.SerializeStoreData(item, 0, out buffer, out num, s_configCompressionEnabled);
            }
            catch
            {
                if (!newItem)
                {
                    this.ReleaseItemExclusive(context, id, lockId);
                }
                throw;
            }
            if (lockId == null)
            {
                num2 = 0;
            }
            else
            {
                num2 = (int)lockId;
            }
            this.MakeRequest(System.Web.UnsafeNativeMethods.StateProtocolVerb.PUT, id, System.Web.UnsafeNativeMethods.StateProtocolExclusive.NONE, 0, item.Timeout, num2, buffer, num, s_networkTimeout, out results);
        }
Beispiel #3
0
        SessionStateStoreData Deserialize(HttpContext context, string serializedItems, int timeout)
        {
            MemoryStream ms = null;
            Stream       input;
            BinaryReader reader = null;

#if NET_4_0
            GZipStream gzip = null;
#endif
            try {
                ms = new MemoryStream(Convert.FromBase64String(serializedItems));
                var sessionItems = new SessionStateItemCollection();

                if (ms.Length > 0)
                {
#if NET_4_0
                    if (sessionConfig.CompressionEnabled)
                    {
                        input = gzip = new GZipStream(ms, CompressionMode.Decompress, true);
                    }
                    else
#endif
                    input = ms;

                    reader       = new BinaryReader(input);
                    sessionItems = SessionStateItemCollection.Deserialize(reader);
#if NET_4_0
                    if (gzip != null)
                    {
                        gzip.Close();
                    }
#endif
                    reader.Close();
                }

                return(new SessionStateStoreData(sessionItems, SessionStateUtility.GetSessionStaticObjects(context), timeout));
            } finally {
#if NET_4_0
                if (reader != null)
                {
                    reader.Dispose();
                }
                if (gzip != null)
                {
                    gzip.Dispose();
                }
#else
                if (reader != null)
                {
                    ((IDisposable)reader).Dispose();
                }
#endif
                if (ms != null)
                {
                    ms.Dispose();
                }
            }
        }
Beispiel #4
0
        public override void CreateUninitializedItem(HttpContext context, string id, int timeout)
        {
            System.Web.UnsafeNativeMethods.SessionNDMakeRequestResults results;
            byte[] buffer;
            int    num;

            SessionStateUtility.SerializeStoreData(this.CreateNewStoreData(context, timeout), 0, out buffer, out num, s_configCompressionEnabled);
            this.MakeRequest(System.Web.UnsafeNativeMethods.StateProtocolVerb.PUT, id, System.Web.UnsafeNativeMethods.StateProtocolExclusive.NONE, 1, timeout, 0, buffer, num, s_networkTimeout, out results);
        }
Beispiel #5
0
        void OnReleaseRequestState(object o, EventArgs args)
        {
            Trace.WriteLine("SessionStateModule.OnReleaseRequestState (hash " + this.GetHashCode().ToString("x") + ")");

            HttpApplication application = (HttpApplication)o;
            HttpContext     context     = application.Context;

            if (!(context.Handler is IRequiresSessionState))
            {
                return;
            }

            Trace.WriteLine("\tsessionId == " + container.SessionID);
            Trace.WriteLine("\trequest path == " + context.Request.FilePath);
            Trace.WriteLine("\tHandler (" + context.Handler + ") requires session state");
            try
            {
                if (!container.IsAbandoned)
                {
                    Trace.WriteLine("\tnot abandoned");
                    if (!container.IsReadOnly)
                    {
                        Trace.WriteLine("\tnot read only, storing and releasing");
                        handler.SetAndReleaseItemExclusive(context, container.SessionID, storeData, storeLockId, storeIsNew);
                    }
                    else
                    {
                        Trace.WriteLine("\tread only, releasing");
                        handler.ReleaseItemExclusive(context, container.SessionID, storeLockId);
                    }
                    handler.ResetItemTimeout(context, container.SessionID);
                }
                else
                {
                    handler.ReleaseItemExclusive(context, container.SessionID, storeLockId);
                    handler.RemoveItem(context, container.SessionID, storeLockId, storeData);
                    if (supportsExpiration)
#if TARGET_J2EE
                    {; }
                    else
#else
                    {// Make sure the expiration handler is not called after we will have raised
                     // the session end event.
                        handler.SetItemExpireCallback(null);
                    }
#endif
                    { SessionStateUtility.RaiseSessionEnd(container, this, args); }
                }
                SessionStateUtility.RemoveHttpSessionStateFromContext(context);
            }
            finally
            {
                container = null;
                storeData = null;
            }
        }
        private void CompleteAcquireState()
        {
            bool flag = false;

            try
            {
                if (this._rqItem != null)
                {
                    this._rqSessionStateNotFound = false;
                    if ((this._rqActionFlags & SessionStateActions.InitializeItem) != SessionStateActions.None)
                    {
                        this._rqIsNewSession = true;
                    }
                    else
                    {
                        this._rqIsNewSession = false;
                    }
                }
                else
                {
                    this._rqIsNewSession         = true;
                    this._rqSessionStateNotFound = true;
                    if (s_allowDelayedStateStoreItemCreation)
                    {
                        flag = true;
                    }
                    if ((!this._rqIdNew && s_configRegenerateExpiredSessionId) && (this._rqSupportSessionIdReissue && this.CreateSessionId()))
                    {
                        this.CreateUninitializedSessionState();
                        return;
                    }
                }
                if (flag)
                {
                    SessionStateUtility.AddDelayedHttpSessionStateToContext(this._rqContext, this);
                    this._rqSessionState = s_delayedSessionState;
                }
                else
                {
                    this.InitStateStoreItem(true);
                }
                if (this._rqIsNewSession)
                {
                    this.OnStart(EventArgs.Empty);
                }
            }
            finally
            {
                if (EtwTrace.IsTraceEnabled(4, 8))
                {
                    EtwTrace.Trace(EtwTraceType.ETW_TYPE_SESSION_DATA_END, this._rqContext.WorkerRequest);
                }
            }
        }
Beispiel #7
0
 static internal SessionStateStoreData DeserializeStoreData(HttpContext context, Stream stream, bool compressionEnabled)
 {
     if (compressionEnabled)
     {
         // apply the compression decorator on top of the stream
         // the data should not be bigger than 4GB - compression doesn't work for more than that
         using (DeflateStream zipStream = new DeflateStream(stream, CompressionMode.Decompress, true)) {
             return(SessionStateUtility.Deserialize(context, zipStream));
         }
     }
     return(SessionStateUtility.Deserialize(context, stream));
 }
Beispiel #8
0
        internal static SessionStateStoreData Deserialize(HttpContext context, Stream stream)
        {
            int timeout;
            SessionStateItemCollection sessionItems;
            bool hasItems;
            bool hasStaticObjects;
            HttpStaticObjectsCollection staticObjects;
            Byte eof;

            Debug.Assert(context != null);

            try {
                BinaryReader reader = new BinaryReader(stream);
                timeout          = reader.ReadInt32();
                hasItems         = reader.ReadBoolean();
                hasStaticObjects = reader.ReadBoolean();

                if (hasItems)
                {
                    sessionItems = SessionStateItemCollection.Deserialize(reader);
                }
                else
                {
                    sessionItems = new SessionStateItemCollection();
                }

                if (hasStaticObjects)
                {
                    staticObjects = HttpStaticObjectsCollection.Deserialize(reader);
                }
                else
                {
                    staticObjects = SessionStateUtility.GetSessionStaticObjects(context);
                }

                eof = reader.ReadByte();
                if (eof != 0xff)
                {
                    throw new HttpException(SR.GetString(SR.Invalid_session_state));
                }
            }
            catch (EndOfStreamException) {
                throw new HttpException(SR.GetString(SR.Invalid_session_state));
            }

            return(new SessionStateStoreData(sessionItems, staticObjects, timeout));
        }
Beispiel #9
0
        public override void CreateUninitializedItem(HttpContext context, String id, int timeout)
        {
            UnsafeNativeMethods.SessionNDMakeRequestResults results;
            byte[] buf;
            int    length;

            Debug.Trace("OutOfProcSessionStateStore", "Calling CreateUninitializedItem, id=" + id + " timeout=" + timeout);

            // Create an empty item
            SessionStateUtility.SerializeStoreData(CreateNewStoreData(context, timeout), 0, out buf, out length, s_configCompressionEnabled);

            // Save it to the store
            MakeRequest(UnsafeNativeMethods.StateProtocolVerb.PUT, id,
                        UnsafeNativeMethods.StateProtocolExclusive.NONE,
                        (int)SessionStateItemFlags.Uninitialized, timeout, 0,
                        buf, length, s_networkTimeout, out results);
        }
Beispiel #10
0
        internal static SessionStateStoreData CreateLegitStoreData(HttpContext context,
                                                                   ISessionStateItemCollection sessionItems,
                                                                   HttpStaticObjectsCollection staticObjects,
                                                                   int timeout)
        {
            if (sessionItems == null)
            {
                sessionItems = new SessionStateItemCollection();
            }

            if (staticObjects == null && context != null)
            {
                staticObjects = SessionStateUtility.GetSessionStaticObjects(context);
            }

            return(new SessionStateStoreData(sessionItems, staticObjects, timeout));
        }
        /*
         * 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));
            }
        }
Beispiel #12
0
        public override void SetAndReleaseItemExclusive(HttpContext context,
                                                        String id,
                                                        SessionStateStoreData item,
                                                        object lockId,
                                                        bool newItem)
        {
            UnsafeNativeMethods.SessionNDMakeRequestResults results;
            byte[] buf;
            int    length;
            int    lockCookie;

            Debug.Assert(item.Items != null, "item.Items != null");
            Debug.Assert(item.StaticObjects != null, "item.StaticObjects != null");

            Debug.Trace("OutOfProcSessionStateStore", "Calling Set, id=" + id + " sessionItems=" + item.Items + " timeout=" + item.Timeout);

            try {
                SessionStateUtility.SerializeStoreData(item, 0, out buf, out length, s_configCompressionEnabled);
            }
            catch {
                if (!newItem)
                {
                    ((SessionStateStoreProviderBase)this).ReleaseItemExclusive(context, id, lockId);
                }
                throw;
            }

            // Save it to the store

            if (lockId == null)
            {
                lockCookie = 0;
            }
            else
            {
                lockCookie = (int)lockId;
            }

            MakeRequest(UnsafeNativeMethods.StateProtocolVerb.PUT, id,
                        UnsafeNativeMethods.StateProtocolExclusive.NONE, 0, item.Timeout, lockCookie,
                        buf, length, s_networkTimeout, out results);
        }
Beispiel #13
0
 static internal void SerializeStoreData(SessionStateStoreData item, int initialStreamSize, out byte[] buf, out int length, bool compressionEnabled)
 {
     using (MemoryStream s = new MemoryStream(initialStreamSize)) {
         SessionStateUtility.Serialize(item, s);
         if (compressionEnabled)
         {
             byte[] serializedBuffer = s.GetBuffer();
             int    serializedLength = (int)s.Length;
             // truncate the MemoryStream so we can write the compressed data in it
             s.SetLength(0);
             // compress the serialized bytes
             using (DeflateStream zipStream = new DeflateStream(s, CompressionMode.Compress, true)) {
                 zipStream.Write(serializedBuffer, 0, serializedLength);
             }
             // if the session state tables have ANSI_PADDING disabled, last )s are trimmed.
             // This shouldn't happen, but to be sure, we are padding with an extra byte
             s.WriteByte((byte)0xff);
         }
         buf    = s.GetBuffer();
         length = (int)s.Length;
     }
 }
        public void OnCacheItemRemoved(string key, object value, CacheItemRemovedReason reason)
        {
            PerfCounters.DecrementCounter(AppPerfCounter.SESSIONS_ACTIVE);
            InProcSessionState state = (InProcSessionState)value;

            if (((state._flags & 2) == 0) && ((state._flags & 1) == 0))
            {
                switch (reason)
                {
                case CacheItemRemovedReason.Removed:
                    PerfCounters.IncrementCounter(AppPerfCounter.SESSIONS_ABANDONED);
                    break;

                case CacheItemRemovedReason.Expired:
                    PerfCounters.IncrementCounter(AppPerfCounter.SESSIONS_TIMED_OUT);
                    break;
                }
                if (this._expireCallback != null)
                {
                    string id = key.Substring(CACHEKEYPREFIXLENGTH);
                    this._expireCallback(id, SessionStateUtility.CreateLegitStoreData(null, state._sessionItems, state._staticObjects, state._timeout));
                }
            }
        }
Beispiel #15
0
        public override SessionStateStoreData CreateNewStoreData(HttpContext context, int timeout)
        {
            Debug.Assert(timeout <= SessionStateModule.MAX_CACHE_BASED_TIMEOUT_MINUTES, "item.Timeout <= SessionStateModule.MAX_CACHE_BASED_TIMEOUT_MINUTES");

            return(SessionStateUtility.CreateLegitStoreData(context, null, null, timeout));
        }
Beispiel #16
0
        internal SessionStateStoreData DoGet(HttpContext context,
                                             String id,
                                             UnsafeNativeMethods.StateProtocolExclusive exclusiveAccess,
                                             out bool locked,
                                             out TimeSpan lockAge,
                                             out object lockId,
                                             out SessionStateActions actionFlags)
        {
            SessionStateStoreData item   = null;
            UnmanagedMemoryStream stream = null;
            int contentLength;

            UnsafeNativeMethods.SessionNDMakeRequestResults results;

            // Set default return values
            locked          = false;
            lockId          = null;
            lockAge         = TimeSpan.Zero;
            actionFlags     = 0;
            results.content = IntPtr.Zero;

            try {
                MakeRequest(UnsafeNativeMethods.StateProtocolVerb.GET,
                            id, exclusiveAccess, 0, 0, 0,
                            null, 0, s_networkTimeout, out results);

                switch (results.httpStatus)
                {
                case 200:
                    /* item found, deserialize it */
                    contentLength = results.contentLength;
                    if (contentLength > 0)
                    {
                        try {
                            unsafe {
                                stream = new UnmanagedMemoryStream((byte *)results.content, contentLength);
                            }
                            item = SessionStateUtility.DeserializeStoreData(context, stream, s_configCompressionEnabled);
                        }
                        finally {
                            if (stream != null)
                            {
                                stream.Close();
                            }
                        }

                        lockId      = results.lockCookie;
                        actionFlags = (SessionStateActions)results.actionFlags;
                    }

                    break;

                case 423:
                    /* state locked, return lock information */

                    if (0 <= results.lockAge)
                    {
                        if (results.lockAge < Sec.ONE_YEAR)
                        {
                            lockAge = new TimeSpan(0, 0, results.lockAge);
                        }
                        else
                        {
                            lockAge = TimeSpan.Zero;
                        }
                    }
                    else
                    {
                        DateTime now = DateTime.Now;
                        if (0 < results.lockDate && results.lockDate < now.Ticks)
                        {
                            lockAge = now - new DateTime(results.lockDate);
                        }
                        else
                        {
                            lockAge = TimeSpan.Zero;
                        }
                    }

                    locked = true;
                    lockId = results.lockCookie;

                    Debug.Assert((results.actionFlags & (int)SessionStateActions.InitializeItem) == 0,
                                 "(results.actionFlags & (int)SessionStateActions.InitializeItem) == 0; uninitialized item cannot be locked");
                    break;
                }
            }
            finally {
                if (results.content != IntPtr.Zero)
                {
                    UnsafeNativeMethods.SessionNDFreeBody(new HandleRef(this, results.content));
                }
            }

            return(item);
        }
        private void OnReleaseState(object source, EventArgs eventArgs)
        {
            bool flag = false;

            this._releaseCalled = true;
            HttpApplication application = (HttpApplication)source;
            HttpContext     context     = application.Context;

            this.ChangeImpersonation(context, false);
            try
            {
                if (this._rqSessionState != null)
                {
                    bool delayed = this._rqSessionState == s_delayedSessionState;
                    SessionStateUtility.RemoveHttpSessionStateFromContext(this._rqContext, delayed);
                    if (((!this._rqSessionStateNotFound || (this._sessionStartEventHandler != null)) || (!delayed && this._rqSessionItems.Dirty)) || ((!delayed && (this._rqStaticObjects != null)) && !this._rqStaticObjects.NeverAccessed))
                    {
                        if (this._rqSessionState.IsAbandoned)
                        {
                            if (this._rqSessionStateNotFound)
                            {
                                if (this._supportSessionExpiry)
                                {
                                    if (delayed)
                                    {
                                        this.InitStateStoreItem(false);
                                    }
                                    this._onEndTarget.RaiseSessionOnEnd(this.ReleaseStateGetSessionID(), this._rqItem);
                                }
                            }
                            else
                            {
                                this._store.RemoveItem(this._rqContext, this.ReleaseStateGetSessionID(), this._rqLockId, this._rqItem);
                            }
                        }
                        else if (!this._rqReadonly || ((this._rqReadonly && this._rqIsNewSession) && ((this._sessionStartEventHandler != null) && !this.SessionIDManagerUseCookieless)))
                        {
                            if ((context.Error == null) && (((this._rqSessionStateNotFound || this._rqSessionItems.Dirty) || ((this._rqStaticObjects != null) && !this._rqStaticObjects.NeverAccessed)) || (this._rqItem.Timeout != this._rqSessionState.Timeout)))
                            {
                                if (delayed)
                                {
                                    this.InitStateStoreItem(false);
                                }
                                if (this._rqItem.Timeout != this._rqSessionState.Timeout)
                                {
                                    this._rqItem.Timeout = this._rqSessionState.Timeout;
                                }
                                s_sessionEverSet = true;
                                flag             = true;
                                this._store.SetAndReleaseItemExclusive(this._rqContext, this.ReleaseStateGetSessionID(), this._rqItem, this._rqLockId, this._rqSessionStateNotFound);
                            }
                            else if (!this._rqSessionStateNotFound)
                            {
                                this._store.ReleaseItemExclusive(this._rqContext, this.ReleaseStateGetSessionID(), this._rqLockId);
                            }
                        }
                    }
                }
                if ((this._rqAddedCookie && !flag) && context.Response.IsBuffered())
                {
                    this._idManager.RemoveSessionID(this._rqContext);
                }
            }
            finally
            {
                this.RestoreImpersonation();
            }
            bool requiresSessionState = context.RequiresSessionState;

            if ((HttpRuntime.UseIntegratedPipeline && (context.NotificationContext.CurrentNotification == RequestNotification.ReleaseRequestState)) && (s_canSkipEndRequestCall || !requiresSessionState))
            {
                context.DisableNotifications(RequestNotification.EndRequest, 0);
                this._acquireCalled = false;
                this._releaseCalled = false;
                this.ResetPerRequestFields();
            }
        }
        private SessionStateStoreData DoGet(HttpContext context, string id, bool exclusive, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actionFlags)
        {
            bool   flag;
            string key = this.CreateSessionStateCacheKey(id);

            locked      = false;
            lockId      = null;
            lockAge     = TimeSpan.Zero;
            actionFlags = SessionStateActions.None;
            SessionIDManager.CheckIdLength(id, true);
            InProcSessionState state = (InProcSessionState)HttpRuntime.CacheInternal.Get(key);

            if (state == null)
            {
                return(null);
            }
            int comparand = state._flags;

            if (((comparand & 1) != 0) && (comparand == Interlocked.CompareExchange(ref state._flags, comparand & -2, comparand)))
            {
                actionFlags = SessionStateActions.InitializeItem;
            }
            if (exclusive)
            {
                flag = true;
                if (!state._locked)
                {
                    state._spinLock.AcquireWriterLock();
                    try
                    {
                        if (!state._locked)
                        {
                            flag               = false;
                            state._locked      = true;
                            state._utcLockDate = DateTime.UtcNow;
                            state._lockCookie++;
                        }
                        lockId = state._lockCookie;
                        goto Label_00FE;
                    }
                    finally
                    {
                        state._spinLock.ReleaseWriterLock();
                    }
                }
                lockId = state._lockCookie;
            }
            else
            {
                state._spinLock.AcquireReaderLock();
                try
                {
                    flag   = state._locked;
                    lockId = state._lockCookie;
                }
                finally
                {
                    state._spinLock.ReleaseReaderLock();
                }
            }
Label_00FE:
            if (flag)
            {
                locked  = true;
                lockAge = (TimeSpan)(DateTime.UtcNow - state._utcLockDate);
                return(null);
            }
            return(SessionStateUtility.CreateLegitStoreData(context, state._sessionItems, state._staticObjects, state._timeout));
        }
Beispiel #19
0
        internal unsafe SessionStateStoreData DoGet(HttpContext context, string id, System.Web.UnsafeNativeMethods.StateProtocolExclusive exclusiveAccess, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actionFlags)
        {
            SessionStateStoreData data   = null;
            UnmanagedMemoryStream stream = null;

            System.Web.UnsafeNativeMethods.SessionNDMakeRequestResults results;
            locked          = false;
            lockId          = null;
            lockAge         = TimeSpan.Zero;
            actionFlags     = SessionStateActions.None;
            results.content = IntPtr.Zero;
            try
            {
                this.MakeRequest(System.Web.UnsafeNativeMethods.StateProtocolVerb.GET, id, exclusiveAccess, 0, 0, 0, null, 0, s_networkTimeout, out results);
                int httpStatus = results.httpStatus;
                if (httpStatus != 200)
                {
                    if (httpStatus != 0x1a7)
                    {
                        return(data);
                    }
                }
                else
                {
                    int contentLength = results.contentLength;
                    if (contentLength > 0)
                    {
                        try
                        {
                            stream = new UnmanagedMemoryStream((byte *)results.content, (long)contentLength);
                            data   = SessionStateUtility.DeserializeStoreData(context, stream, s_configCompressionEnabled);
                        }
                        finally
                        {
                            if (stream != null)
                            {
                                stream.Close();
                            }
                        }
                        lockId      = results.lockCookie;
                        actionFlags = (SessionStateActions)results.actionFlags;
                    }
                    return(data);
                }
                if (0 <= results.lockAge)
                {
                    if (results.lockAge < 0x1e13380)
                    {
                        lockAge = new TimeSpan(0, 0, results.lockAge);
                    }
                    else
                    {
                        lockAge = TimeSpan.Zero;
                    }
                }
                else
                {
                    DateTime now = DateTime.Now;
                    if ((0L < results.lockDate) && (results.lockDate < now.Ticks))
                    {
                        lockAge = (TimeSpan)(now - new DateTime(results.lockDate));
                    }
                    else
                    {
                        lockAge = TimeSpan.Zero;
                    }
                }
                locked = true;
                lockId = results.lockCookie;
            }
            finally
            {
                if (results.content != IntPtr.Zero)
                {
                    System.Web.UnsafeNativeMethods.SessionNDFreeBody(new HandleRef(this, results.content));
                }
            }
            return(data);
        }
Beispiel #20
0
        void OnAcquireRequestState(object o, EventArgs args)
        {
            Trace.WriteLine("SessionStateModule.OnAcquireRequestState (hash " + this.GetHashCode().ToString("x") + ")");
            HttpApplication application = (HttpApplication)o;
            HttpContext     context     = application.Context;

            if (!(context.Handler is IRequiresSessionState))
            {
                Trace.WriteLine("Handler (" + context.Handler + ") does not require session state");
                return;
            }
            bool isReadOnly = (context.Handler is IReadOnlySessionState);

            bool supportSessionIDReissue;

            if (idManager.InitializeRequest(context, false, out supportSessionIDReissue))
            {
                return;                 // Redirected, will come back here in a while
            }
            string sessionId = idManager.GetSessionID(context);

            handler.InitializeRequest(context);

            storeData = GetStoreData(context, sessionId, isReadOnly);

            storeIsNew = false;
            if (storeData == null && !storeLocked)
            {
                storeIsNew = true;
                sessionId  = idManager.CreateSessionID(context);
                Trace.WriteLine("New session ID allocated: " + sessionId);
                bool redirected;
                bool cookieAdded;
                idManager.SaveSessionID(context, sessionId, out redirected, out cookieAdded);
                if (redirected)
                {
                    if (supportSessionIDReissue)
                    {
                        handler.CreateUninitializedItem(context, sessionId, (int)config.Timeout.TotalMinutes);
                    }
                    context.Response.End();
                    return;
                }
                else
                {
                    storeData = handler.CreateNewStoreData(context, (int)config.Timeout.TotalMinutes);
                }
            }
            else if (storeData == null && storeLocked)
            {
                WaitForStoreUnlock(context, sessionId, isReadOnly);
            }
            else if (storeData != null &&
                     !storeLocked &&
                     storeSessionAction == SessionStateActions.InitializeItem &&
                     IsCookieLess(context, config))
            {
                storeData = handler.CreateNewStoreData(context, (int)config.Timeout.TotalMinutes);
            }

            container = CreateContainer(sessionId, storeData, storeIsNew, isReadOnly);
            SessionStateUtility.AddHttpSessionStateToContext(app.Context, container);
            if (storeIsNew)
            {
                OnSessionStart();
                HttpSessionState hss = app.Session;

                if (hss != null)
                {
                    storeData.Timeout = hss.Timeout;
                }
            }

            // Whenever a container is abandoned, we temporarily disable the expire call back.
            // So in this case we are quite sure we have a brand new container, so we make sure it works again.
            supportsExpiration = handler.SetItemExpireCallback(OnSessionExpired);
        }
        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.CacheInternal.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);
        }
Beispiel #22
0
 public override SessionStateStoreData CreateNewStoreData(HttpContext context, int timeout)
 {
     return(new SessionStateStoreData(new SessionStateItemCollection(), SessionStateUtility.GetSessionStaticObjects(context), timeout));
 }
Beispiel #23
0
 void OnSessionExpired(string id, SessionStateStoreData item)
 {
     SessionStateUtility.RaiseSessionEnd(
         CreateContainer(id, item, false, true),
         this, EventArgs.Empty);
 }
 // Create a new SessionStateStoreData.
 public override SessionStateStoreData CreateNewStoreData(HttpContext context, int timeout)
 {
     return(SessionStateUtility.CreateLegitStoreData(context, null, null, timeout));
 }