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.
33 using System.Collections.Specialized;
34 using System.ComponentModel;
35 using System.Web.Configuration;
36 using System.Web.Caching;
37 using System.Web.Util;
38 using System.Security.Permissions;
39 using System.Threading;
40 using System.Configuration;
41 using System.Diagnostics;
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 static readonly object startEvent = new object ();
68 static readonly object endEvent = new object ();
70 SessionStateSection config;
72 SessionStateStoreProviderBase handler;
73 ISessionIDManager idManager;
74 bool supportsExpiration;
80 TimeSpan storeLockAge;
82 SessionStateActions storeSessionAction;
86 SessionStateStoreData storeData;
87 HttpSessionStateContainer container;
90 TimeSpan executionTimeout;
91 //int executionTimeoutMS;
93 EventHandlerList events = new EventHandlerList ();
95 public event EventHandler Start {
96 add { events.AddHandler (startEvent, value); }
97 remove { events.RemoveHandler (startEvent, value); }
100 // This event is public, but only Session_[On]End in global.asax will be invoked if present.
101 public event EventHandler End {
102 add { events.AddHandler (endEvent, value); }
103 remove { events.RemoveHandler (endEvent, value); }
106 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
107 public SessionStateModule () {
110 public void Dispose () {
111 app.BeginRequest -= new EventHandler (OnBeginRequest);
112 app.AcquireRequestState -= new EventHandler (OnAcquireRequestState);
113 app.ReleaseRequestState -= new EventHandler (OnReleaseRequestState);
114 app.EndRequest -= new EventHandler (OnEndRequest);
118 [EnvironmentPermission (SecurityAction.Assert, Read = "MONO_XSP_STATIC_SESSION")]
119 public void Init (HttpApplication app)
121 config = (SessionStateSection) WebConfigurationManager.GetSection ("system.web/sessionState");
123 ProviderSettings settings;
124 switch (config.Mode) {
125 case SessionStateMode.Custom:
126 settings = config.Providers [config.CustomProvider];
127 if (settings == null)
128 throw new HttpException (String.Format ("Cannot find '{0}' provider.", config.CustomProvider));
130 case SessionStateMode.Off:
132 case SessionStateMode.InProc:
133 settings = new ProviderSettings (null, typeof (SessionInProcHandler).AssemblyQualifiedName);
136 case SessionStateMode.SQLServer:
137 settings = new ProviderSettings (null, typeof (SessionSQLServerHandler).AssemblyQualifiedName);
140 case SessionStateMode.StateServer:
141 settings = new ProviderSettings (null, typeof (SessionStateServerHandler).AssemblyQualifiedName);
145 throw new NotImplementedException (String.Format ("The mode '{0}' is not implemented.", config.Mode));
149 handler = (SessionStateStoreProviderBase) ProvidersHelper.InstantiateProvider (settings, typeof (SessionStateStoreProviderBase));
151 if (String.IsNullOrEmpty(config.SessionIDManagerType)) {
152 idManager = new SessionIDManager ();
154 Type idManagerType = HttpApplication.LoadType (config.SessionIDManagerType, true);
155 idManager = (ISessionIDManager)Activator.CreateInstance (idManagerType);
159 idManager.Initialize ();
160 } catch (Exception ex) {
161 throw new HttpException ("Failed to initialize session ID manager.", ex);
164 supportsExpiration = handler.SetItemExpireCallback (OnSessionExpired);
165 HttpRuntimeSection runtime = HttpRuntime.Section;
166 executionTimeout = runtime.ExecutionTimeout;
167 //executionTimeoutMS = executionTimeout.Milliseconds;
171 app.BeginRequest += new EventHandler (OnBeginRequest);
172 app.AcquireRequestState += new EventHandler (OnAcquireRequestState);
173 app.ReleaseRequestState += new EventHandler (OnReleaseRequestState);
174 app.EndRequest += new EventHandler (OnEndRequest);
177 internal static bool IsCookieLess (HttpContext context, SessionStateSection config) {
178 if (config.Cookieless == HttpCookieMode.UseCookies)
180 if (config.Cookieless == HttpCookieMode.UseUri)
182 object cookieless = context.Items [CookielessFlagName];
183 if (cookieless == null)
185 return (bool) cookieless;
188 void OnBeginRequest (object o, EventArgs args)
190 HttpApplication application = (HttpApplication) o;
191 HttpContext context = application.Context;
192 string file_path = context.Request.FilePath;
193 string base_path = VirtualPathUtility.GetDirectory (file_path);
194 string id = UrlUtils.GetSessionId (base_path);
199 string new_path = UrlUtils.RemoveSessionId (base_path, file_path);
200 context.Request.SetFilePath (new_path);
201 context.Request.SetHeader (HeaderName, id);
202 context.Response.SetAppPathModifier (id);
205 void OnAcquireRequestState (object o, EventArgs args) {
206 Trace.WriteLine ("SessionStateModule.OnAcquireRequestState (hash " + this.GetHashCode ().ToString ("x") + ")");
207 HttpApplication application = (HttpApplication) o;
208 HttpContext context = application.Context;
210 if (!(context.Handler is IRequiresSessionState)) {
211 Trace.WriteLine ("Handler (" + context.Handler + ") does not require session state");
214 bool isReadOnly = (context.Handler is IReadOnlySessionState);
216 bool supportSessionIDReissue;
217 if (idManager.InitializeRequest (context, false, out supportSessionIDReissue))
218 return; // Redirected, will come back here in a while
219 string sessionId = idManager.GetSessionID (context);
221 handler.InitializeRequest (context);
223 storeData = GetStoreData (context, sessionId, isReadOnly);
226 if (storeData == null && !storeLocked) {
228 sessionId = idManager.CreateSessionID (context);
229 Trace.WriteLine ("New session ID allocated: " + sessionId);
232 idManager.SaveSessionID (context, sessionId, out redirected, out cookieAdded);
234 if (supportSessionIDReissue)
235 handler.CreateUninitializedItem (context, sessionId, (int)config.Timeout.TotalMinutes);
236 context.Response.End ();
240 storeData = handler.CreateNewStoreData (context, (int)config.Timeout.TotalMinutes);
242 else if (storeData == null && storeLocked) {
243 WaitForStoreUnlock (context, sessionId, isReadOnly);
245 else if (storeData != null &&
247 storeSessionAction == SessionStateActions.InitializeItem &&
248 IsCookieLess (context, config)) {
249 storeData = handler.CreateNewStoreData (context, (int)config.Timeout.TotalMinutes);
252 container = CreateContainer (sessionId, storeData, storeIsNew, isReadOnly);
253 SessionStateUtility.AddHttpSessionStateToContext (app.Context, container);
256 HttpSessionState hss = app.Session;
259 storeData.Timeout = hss.Timeout;
262 // Whenever a container is abandoned, we temporarily disable the expire call back.
263 // So in this case we are quite sure we have a brand new container, so we make sure it works again.
264 supportsExpiration = handler.SetItemExpireCallback (OnSessionExpired);
267 void OnReleaseRequestState (object o, EventArgs args) {
269 Trace.WriteLine ("SessionStateModule.OnReleaseRequestState (hash " + this.GetHashCode ().ToString ("x") + ")");
271 HttpApplication application = (HttpApplication) o;
272 HttpContext context = application.Context;
273 if (!(context.Handler is IRequiresSessionState))
276 Trace.WriteLine ("\tsessionId == " + container.SessionID);
277 Trace.WriteLine ("\trequest path == " + context.Request.FilePath);
278 Trace.WriteLine ("\tHandler (" + context.Handler + ") requires session state");
280 if (!container.IsAbandoned) {
281 Trace.WriteLine ("\tnot abandoned");
282 if (!container.IsReadOnly) {
283 Trace.WriteLine ("\tnot read only, storing and releasing");
284 handler.SetAndReleaseItemExclusive (context, container.SessionID, storeData, storeLockId, storeIsNew);
287 Trace.WriteLine ("\tread only, releasing");
288 handler.ReleaseItemExclusive (context, container.SessionID, storeLockId);
290 handler.ResetItemTimeout (context, container.SessionID);
293 handler.ReleaseItemExclusive (context, container.SessionID, storeLockId);
294 handler.RemoveItem (context, container.SessionID, storeLockId, storeData);
295 if (supportsExpiration)
296 // Make sure the expiration handler is not called after we will have raised
297 // the session end event.
298 handler.SetItemExpireCallback (null);
299 SessionStateUtility.RaiseSessionEnd (container, this, args);
301 SessionStateUtility.RemoveHttpSessionStateFromContext (context);
309 void OnEndRequest (object o, EventArgs args) {
313 if (container != null)
314 OnReleaseRequestState (o, args);
316 HttpApplication application = o as HttpApplication;
317 if (application == null)
320 handler.EndRequest (application.Context);
323 SessionStateStoreData GetStoreData (HttpContext context, string sessionId, bool isReadOnly) {
324 SessionStateStoreData item;
325 item = (isReadOnly) ?
326 handler.GetItem (context,
331 out storeSessionAction)
333 handler.GetItemExclusive (context,
338 out storeSessionAction);
339 if (storeLockId == null)
345 void WaitForStoreUnlock (HttpContext context, string sessionId, bool isReadonly) {
346 AutoResetEvent are = new AutoResetEvent (false);
347 TimerCallback tc = new TimerCallback (StoreUnlockWaitCallback);
348 CallbackState cs = new CallbackState (context, are, sessionId, isReadonly);
349 using (Timer timer = new Timer (tc, cs, 500, 500)) {
351 are.WaitOne (executionTimeout, false);
359 void StoreUnlockWaitCallback (object s) {
360 CallbackState state = (CallbackState) s;
362 SessionStateStoreData item = GetStoreData (state.Context, state.SessionId, state.IsReadOnly);
364 if (item == null && storeLocked && (storeLockAge > executionTimeout)) {
365 handler.ReleaseItemExclusive (state.Context, state.SessionId, storeLockId);
366 storeData = null; // Create new state
367 state.AutoEvent.Set ();
369 else if (item != null && !storeLocked) {
371 state.AutoEvent.Set ();
375 HttpSessionStateContainer CreateContainer (string sessionId, SessionStateStoreData data, bool isNew, bool isReadOnly) {
377 return new HttpSessionStateContainer (
378 sessionId, null, null, 0, isNew,
379 config.Cookieless, config.Mode, isReadOnly);
381 return new HttpSessionStateContainer (
392 void OnSessionExpired (string id, SessionStateStoreData item) {
393 SessionStateUtility.RaiseSessionEnd (
394 CreateContainer (id, item, false, true),
395 this, EventArgs.Empty);
398 void OnSessionStart () {
399 EventHandler eh = events [startEvent] as EventHandler;
401 eh (this, EventArgs.Empty);