2 // System.Web.SessionState.SesionStateModule
5 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
6 // Stefan Görling (stefan@gorling.se)
7 // Jackson Harper (jackson@ximian.com)
8 // Marek Habersack (grendello@gmail.com)
10 // Copyright (C) 2002-2006 Novell, Inc (http://www.novell.com)
11 // (C) 2003 Stefan Görling (http://www.gorling.se)
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 using System.Collections.Specialized;
35 using System.Web.Configuration;
36 using System.Web.Caching;
37 using System.Web.Util;
38 using System.Security.Cryptography;
39 using System.Security.Permissions;
40 using System.Threading;
41 using System.Configuration;
43 namespace System.Web.SessionState
45 // CAS - no InheritanceDemand here as the class is sealed
46 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
47 public sealed class SessionStateModule : IHttpModule
51 public readonly HttpContext Context;
52 public readonly AutoResetEvent AutoEvent;
53 public readonly string SessionId;
54 public readonly bool IsReadOnly;
56 public CallbackState (HttpContext context, AutoResetEvent e, string sessionId, bool isReadOnly) {
57 this.Context = context;
59 this.SessionId = sessionId;
60 this.IsReadOnly = isReadOnly;
64 internal const string HeaderName = "AspFilterSessionId";
65 internal const string CookielessFlagName = "_SessionIDManager_IsCookieLess";
67 SessionStateSection config;
69 SessionStateStoreProviderBase handler;
70 ISessionIDManager idManager;
71 bool supportsExpiration;
77 TimeSpan storeLockAge;
79 SessionStateActions storeSessionAction;
82 SessionStateStoreData storeData;
83 HttpSessionStateContainer container;
86 TimeSpan executionTimeout;
87 //int executionTimeoutMS;
89 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
90 public SessionStateModule () {
93 public void Dispose () {
94 app.BeginRequest -= new EventHandler (OnBeginRequest);
95 app.AcquireRequestState -= new EventHandler (OnAcquireRequestState);
96 app.ReleaseRequestState -= new EventHandler (OnReleaseRequestState);
97 app.EndRequest -= new EventHandler (OnEndRequest);
101 [EnvironmentPermission (SecurityAction.Assert, Read = "MONO_XSP_STATIC_SESSION")]
102 public void Init (HttpApplication app) {
104 config = (SessionStateSection) WebConfigurationManager.GetSection ("system.web/sessionState");
106 ProviderSettings settings;
107 switch (config.Mode) {
108 case SessionStateMode.Custom:
109 settings = config.Providers [config.CustomProvider];
110 if (settings == null)
111 throw new HttpException (String.Format ("Cannot find '{0}' provider.", config.CustomProvider));
113 case SessionStateMode.InProc:
114 settings = new ProviderSettings (null, typeof (SessionInProcHandler).AssemblyQualifiedName);
116 case SessionStateMode.Off:
118 case SessionStateMode.SQLServer:
119 //settings = new ProviderSettings (null, typeof (SessionInProcHandler).AssemblyQualifiedName);
122 throw new NotImplementedException (String.Format ("The mode '{0}' is not implemented.", config.Mode));
123 case SessionStateMode.StateServer:
124 settings = new ProviderSettings (null, typeof (SessionStateServerHandler).AssemblyQualifiedName);
128 handler = (SessionStateStoreProviderBase) ProvidersHelper.InstantiateProvider (settings, typeof (SessionStateStoreProviderBase));
133 idManagerType = Type.GetType (config.SessionIDManagerType, true);
136 idManagerType = typeof (SessionIDManager);
138 idManager = Activator.CreateInstance (idManagerType) as ISessionIDManager;
139 idManager.Initialize ();
141 catch (Exception ex) {
142 throw new HttpException ("Failed to initialize session ID manager.", ex);
145 supportsExpiration = handler.SetItemExpireCallback (OnSessionExpired);
146 HttpRuntimeSection runtime = WebConfigurationManager.GetSection ("system.web/httpRuntime") as HttpRuntimeSection;
147 executionTimeout = runtime.ExecutionTimeout;
148 //executionTimeoutMS = executionTimeout.Milliseconds;
152 app.BeginRequest += new EventHandler (OnBeginRequest);
153 app.AcquireRequestState += new EventHandler (OnAcquireRequestState);
154 app.ReleaseRequestState += new EventHandler (OnReleaseRequestState);
155 app.EndRequest += new EventHandler (OnEndRequest);
158 internal static bool IsCookieLess (HttpContext context, SessionStateSection config) {
159 if (config.Cookieless == HttpCookieMode.UseCookies)
161 if (config.Cookieless == HttpCookieMode.UseUri)
163 object cookieless = context.Items [CookielessFlagName];
164 if (cookieless == null)
166 return (bool) cookieless;
169 void OnBeginRequest (object o, EventArgs args) {
170 HttpApplication application = (HttpApplication) o;
171 HttpContext context = application.Context;
172 string base_path = context.Request.BaseVirtualDir;
173 string id = UrlUtils.GetSessionId (base_path);
178 string new_path = UrlUtils.RemoveSessionId (base_path, context.Request.FilePath);
179 context.Request.SetFilePath (new_path);
180 context.Request.SetHeader (HeaderName, id);
181 context.Response.SetAppPathModifier (String.Concat ("(", id, ")"));
184 void OnAcquireRequestState (object o, EventArgs args) {
186 Console.WriteLine ("SessionStateModule.OnAcquireRequestState (hash {0})", this.GetHashCode ().ToString ("x"));
188 HttpApplication application = (HttpApplication) o;
189 HttpContext context = application.Context;
191 if (!(context.Handler is IRequiresSessionState)) {
193 Console.WriteLine ("Handler ({0}) does not require session state", context.Handler);
197 bool isReadOnly = (context.Handler is IReadOnlySessionState);
199 bool supportSessionIDReissue;
200 if (idManager.InitializeRequest (context, false, out supportSessionIDReissue))
201 return; // Redirected, will come back here in a while
202 string sessionId = idManager.GetSessionID (context);
205 handler.InitializeRequest (context);
207 GetStoreData (context, sessionId, isReadOnly);
210 if (storeData == null && !storeLocked) {
212 sessionId = idManager.CreateSessionID (context);
214 Console.WriteLine ("New session ID allocated: {0}", sessionId);
218 idManager.SaveSessionID (context, sessionId, out redirected, out cookieAdded);
220 if (supportSessionIDReissue)
221 handler.CreateUninitializedItem (context, sessionId, config.Timeout.Minutes);
222 context.Response.End ();
226 storeData = handler.CreateNewStoreData (context, config.Timeout.Minutes);
228 else if (storeData == null && storeLocked) {
229 WaitForStoreUnlock (context, sessionId, isReadOnly);
231 else if (storeData != null &&
233 storeSessionAction == SessionStateActions.InitializeItem &&
234 IsCookieLess (context, config)) {
235 storeData = handler.CreateNewStoreData (context, config.Timeout.Minutes);
238 container = CreateContainer (sessionId, storeData, isNew, isReadOnly);
239 SessionStateUtility.AddHttpSessionStateToContext (app.Context, container);
244 void OnReleaseRequestState (object o, EventArgs args) {
247 Console.WriteLine ("SessionStateModule.OnReleaseRequestState (hash {0})", this.GetHashCode ().ToString ("x"));
250 HttpApplication application = (HttpApplication) o;
251 HttpContext context = application.Context;
252 if (!(context.Handler is IRequiresSessionState))
256 Console.WriteLine ("\tsessionId == {0}", container.SessionID);
257 Console.WriteLine ("\trequest path == {0}", context.Request.FilePath);
258 Console.WriteLine ("\tHandler ({0}) requires session state", context.Handler);
261 if (!container.IsAbandoned) {
263 Console.WriteLine ("\tnot abandoned");
265 if (!container.IsReadOnly) {
267 Console.WriteLine ("\tnot read only, storing and releasing");
269 handler.SetAndReleaseItemExclusive (context, container.SessionID, storeData, storeLockId, false);
273 Console.WriteLine ("\tread only, releasing");
275 handler.ReleaseItemExclusive (context, container.SessionID, storeLockId);
277 handler.ResetItemTimeout (context, container.SessionID);
280 handler.ReleaseItemExclusive (context, container.SessionID, storeLockId);
281 handler.RemoveItem (context, container.SessionID, storeLockId, storeData);
282 if (!supportsExpiration)
283 SessionStateUtility.RaiseSessionEnd (container, this, args);
285 SessionStateUtility.RemoveHttpSessionStateFromContext (context);
293 void OnEndRequest (object o, EventArgs args) {
297 HttpApplication application = o as HttpApplication;
298 if (application == null)
301 handler.EndRequest (application.Context);
304 void GetStoreData (HttpContext context, string sessionId, bool isReadOnly) {
305 storeData = (isReadOnly) ?
306 handler.GetItem (context,
311 out storeSessionAction)
313 handler.GetItemExclusive (context,
318 out storeSessionAction);
321 void WaitForStoreUnlock (HttpContext context, string sessionId, bool isReadonly) {
322 AutoResetEvent are = new AutoResetEvent (false);
323 TimerCallback tc = new TimerCallback (StoreUnlockWaitCallback);
324 CallbackState cs = new CallbackState (context, are, sessionId, isReadonly);
325 using (Timer timer = new Timer (tc, cs, 500, 500)) {
327 are.WaitOne (executionTimeout, false);
335 void StoreUnlockWaitCallback (object s) {
336 CallbackState state = (CallbackState) s;
338 GetStoreData (state.Context, state.SessionId, state.IsReadOnly);
340 if (storeData == null && storeLocked && (storeLockAge > executionTimeout)) {
341 handler.ReleaseItemExclusive (state.Context, state.SessionId, storeLockId);
342 state.AutoEvent.Set ();
344 else if (storeData != null && !storeLocked)
345 state.AutoEvent.Set ();
348 HttpSessionStateContainer CreateContainer (string sessionId, SessionStateStoreData data, bool isNew, bool isReadOnly) {
349 return new HttpSessionStateContainer (
360 void OnSessionExpired (string id, SessionStateStoreData item) {
361 SessionStateUtility.RaiseSessionEnd (
362 CreateContainer (id, item, false, true),
363 this, EventArgs.Empty);
366 void OnSessionStart () {
368 Start (this, EventArgs.Empty);
371 public event EventHandler Start;
373 // This event is public, but only Session_[On]End in global.asax will be invoked if present.
374 public event EventHandler End;