fixed tests
[mono.git] / mcs / class / System.Web / System.Web.SessionState_2.0 / SessionStateModule.cs
1 //
2 // System.Web.SessionState.SesionStateModule
3 //
4 // Authors:
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)
9 //
10 // Copyright (C) 2002-2006 Novell, Inc (http://www.novell.com)
11 // (C) 2003 Stefan Görling (http://www.gorling.se)
12 //
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:
20 // 
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
23 // 
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.
31 //
32
33 #if NET_2_0
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;
42
43 namespace System.Web.SessionState
44 {       
45         // CAS - no InheritanceDemand here as the class is sealed
46         [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
47         public sealed class SessionStateModule : IHttpModule
48         {
49                 class CallbackState
50                 {
51                         public readonly HttpContext Context;
52                         public readonly AutoResetEvent AutoEvent;
53                         public readonly string SessionId;
54                         public readonly bool IsReadOnly;
55
56                         public CallbackState (HttpContext context, AutoResetEvent e, string sessionId, bool isReadOnly) {
57                                 this.Context = context;
58                                 this.AutoEvent = e;
59                                 this.SessionId = sessionId;
60                                 this.IsReadOnly = isReadOnly;
61                         }
62                 }
63
64                 internal const string HeaderName = "AspFilterSessionId";
65                 internal const string CookielessFlagName = "_SessionIDManager_IsCookieLess";
66
67                 SessionStateSection config;
68
69                 SessionStateStoreProviderBase handler;
70                 ISessionIDManager idManager;
71                 bool supportsExpiration;
72
73                 HttpApplication app;
74
75                 // Store state
76                 bool storeLocked;
77                 TimeSpan storeLockAge;
78                 object storeLockId;
79                 SessionStateActions storeSessionAction;
80
81                 // Session state
82                 SessionStateStoreData storeData;
83                 HttpSessionStateContainer container;
84
85                 // config
86                 TimeSpan executionTimeout;
87                 //int executionTimeoutMS;
88
89                 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
90                 public SessionStateModule () {
91                 }
92
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);
98                         handler.Dispose ();
99                 }
100
101                 [EnvironmentPermission (SecurityAction.Assert, Read = "MONO_XSP_STATIC_SESSION")]
102                 public void Init (HttpApplication app) {
103
104                         config = (SessionStateSection) WebConfigurationManager.GetSection ("system.web/sessionState");
105
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));
112                                 break;
113                         case SessionStateMode.InProc:
114                                 settings = new ProviderSettings (null, typeof (SessionInProcHandler).AssemblyQualifiedName);
115                                 break;
116                         case SessionStateMode.Off:
117                                 return;
118                         case SessionStateMode.SQLServer:
119                         //settings = new ProviderSettings (null, typeof (SessionInProcHandler).AssemblyQualifiedName);
120                         //break;
121                         default:
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);
125                                 break;
126                         }
127
128                         handler = (SessionStateStoreProviderBase) ProvidersHelper.InstantiateProvider (settings, typeof (SessionStateStoreProviderBase));
129
130                         try {
131                                 Type idManagerType;
132                                 try {
133                                         idManagerType = Type.GetType (config.SessionIDManagerType, true);
134                                 }
135                                 catch {
136                                         idManagerType = typeof (SessionIDManager);
137                                 }
138                                 idManager = Activator.CreateInstance (idManagerType) as ISessionIDManager;
139                                 idManager.Initialize ();
140                         }
141                         catch (Exception ex) {
142                                 throw new HttpException ("Failed to initialize session ID manager.", ex);
143                         }
144
145                         supportsExpiration = handler.SetItemExpireCallback (OnSessionExpired);
146                         HttpRuntimeSection runtime = WebConfigurationManager.GetSection ("system.web/httpRuntime") as HttpRuntimeSection;
147                         executionTimeout = runtime.ExecutionTimeout;
148                         //executionTimeoutMS = executionTimeout.Milliseconds;
149
150                         this.app = app;
151
152                         app.BeginRequest += new EventHandler (OnBeginRequest);
153                         app.AcquireRequestState += new EventHandler (OnAcquireRequestState);
154                         app.ReleaseRequestState += new EventHandler (OnReleaseRequestState);
155                         app.EndRequest += new EventHandler (OnEndRequest);
156                 }
157
158                 internal static bool IsCookieLess (HttpContext context, SessionStateSection config) {
159                         if (config.Cookieless == HttpCookieMode.UseCookies)
160                                 return false;
161                         if (config.Cookieless == HttpCookieMode.UseUri)
162                                 return true;
163                         object cookieless = context.Items [CookielessFlagName];
164                         if (cookieless == null)
165                                 return false;
166                         return (bool) cookieless;
167                 }
168
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);
174
175                         if (id == null)
176                                 return;
177
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, ")"));
182                 }
183
184                 void OnAcquireRequestState (object o, EventArgs args) {
185 #if TRACE
186                         Console.WriteLine ("SessionStateModule.OnAcquireRequestState (hash {0})", this.GetHashCode ().ToString ("x"));
187 #endif
188                         HttpApplication application = (HttpApplication) o;
189                         HttpContext context = application.Context;
190
191                         if (!(context.Handler is IRequiresSessionState)) {
192 #if TRACE
193                                 Console.WriteLine ("Handler ({0}) does not require session state", context.Handler);
194 #endif
195                                 return;
196                         }
197                         bool isReadOnly = (context.Handler is IReadOnlySessionState);
198
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);
203
204
205                         handler.InitializeRequest (context);
206
207                         GetStoreData (context, sessionId, isReadOnly);
208
209                         bool isNew = false;
210                         if (storeData == null && !storeLocked) {
211                                 isNew = true;
212                                 sessionId = idManager.CreateSessionID (context);
213 #if TRACE
214                                 Console.WriteLine ("New session ID allocated: {0}", sessionId);
215 #endif
216                                 bool redirected;
217                                 bool cookieAdded;
218                                 idManager.SaveSessionID (context, sessionId, out redirected, out cookieAdded);
219                                 if (redirected) {
220                                         if (supportSessionIDReissue)
221                                                 handler.CreateUninitializedItem (context, sessionId, config.Timeout.Minutes);
222                                         context.Response.End ();
223                                         return;
224                                 }
225                                 else
226                                         storeData = handler.CreateNewStoreData (context, config.Timeout.Minutes);
227                         }
228                         else if (storeData == null && storeLocked) {
229                                 WaitForStoreUnlock (context, sessionId, isReadOnly);
230                         }
231                         else if (storeData != null &&
232                                  !storeLocked &&
233                                  storeSessionAction == SessionStateActions.InitializeItem &&
234                                  IsCookieLess (context, config)) {
235                                 storeData = handler.CreateNewStoreData (context, config.Timeout.Minutes);
236                         }
237
238                         container = CreateContainer (sessionId, storeData, isNew, isReadOnly);
239                         SessionStateUtility.AddHttpSessionStateToContext (app.Context, container);
240                         if (isNew)
241                                 OnSessionStart ();
242                 }
243
244                 void OnReleaseRequestState (object o, EventArgs args) {
245
246 #if TRACE
247                         Console.WriteLine ("SessionStateModule.OnReleaseRequestState (hash {0})", this.GetHashCode ().ToString ("x"));
248 #endif
249
250                         HttpApplication application = (HttpApplication) o;
251                         HttpContext context = application.Context;
252                         if (!(context.Handler is IRequiresSessionState))
253                                 return;
254
255 #if TRACE
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);
259 #endif
260                         try {
261                                 if (!container.IsAbandoned) {
262 #if TRACE
263                                         Console.WriteLine ("\tnot abandoned");
264 #endif
265                                         if (!container.IsReadOnly) {
266 #if TRACE
267                                                 Console.WriteLine ("\tnot read only, storing and releasing");
268 #endif
269                                                 handler.SetAndReleaseItemExclusive (context, container.SessionID, storeData, storeLockId, false);
270                                         }
271                                         else {
272 #if TRACE
273                                                 Console.WriteLine ("\tread only, releasing");
274 #endif
275                                                 handler.ReleaseItemExclusive (context, container.SessionID, storeLockId);
276                                         }
277                                         handler.ResetItemTimeout (context, container.SessionID);
278                                 }
279                                 else {
280                                         handler.ReleaseItemExclusive (context, container.SessionID, storeLockId);
281                                         handler.RemoveItem (context, container.SessionID, storeLockId, storeData);
282                                         if (!supportsExpiration)
283                                                 SessionStateUtility.RaiseSessionEnd (container, this, args);
284                                 }
285                                 SessionStateUtility.RemoveHttpSessionStateFromContext (context);
286                         }
287                         finally {
288                                 container = null;
289                                 storeData = null;
290                         }
291                 }
292
293                 void OnEndRequest (object o, EventArgs args) {
294                         if (handler == null)
295                                 return;
296
297                         HttpApplication application = o as HttpApplication;
298                         if (application == null)
299                                 return;
300                         if (handler != null)
301                                 handler.EndRequest (application.Context);
302                 }
303
304                 void GetStoreData (HttpContext context, string sessionId, bool isReadOnly) {
305                         storeData = (isReadOnly) ?
306                                 handler.GetItem (context,
307                                                                  sessionId,
308                                                                  out storeLocked,
309                                                                  out storeLockAge,
310                                                                  out storeLockId,
311                                                                  out storeSessionAction)
312                                                                  :
313                                 handler.GetItemExclusive (context,
314                                                                           sessionId,
315                                                                           out storeLocked,
316                                                                           out storeLockAge,
317                                                                           out storeLockId,
318                                                                           out storeSessionAction);
319                 }
320
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)) {
326                                 try {
327                                         are.WaitOne (executionTimeout, false);
328                                 }
329                                 catch {
330                                         storeData = null;
331                                 }
332                         }
333                 }
334
335                 void StoreUnlockWaitCallback (object s) {
336                         CallbackState state = (CallbackState) s;
337
338                         GetStoreData (state.Context, state.SessionId, state.IsReadOnly);
339
340                         if (storeData == null && storeLocked && (storeLockAge > executionTimeout)) {
341                                 handler.ReleaseItemExclusive (state.Context, state.SessionId, storeLockId);
342                                 state.AutoEvent.Set ();
343                         }
344                         else if (storeData != null && !storeLocked)
345                                 state.AutoEvent.Set ();
346                 }
347
348                 HttpSessionStateContainer CreateContainer (string sessionId, SessionStateStoreData data, bool isNew, bool isReadOnly) {
349                         return new HttpSessionStateContainer (
350                                 sessionId,
351                                 data.Items,
352                                 data.StaticObjects,
353                                 data.Timeout,
354                                 isNew,
355                                 config.Cookieless,
356                                 config.Mode,
357                                 isReadOnly);
358                 }
359
360                 void OnSessionExpired (string id, SessionStateStoreData item) {
361                         SessionStateUtility.RaiseSessionEnd (
362                                 CreateContainer (id, item, false, true),
363                                 this, EventArgs.Empty);
364                 }
365
366                 void OnSessionStart () {
367                         if (Start != null)
368                                 Start (this, EventArgs.Empty);
369                 }
370
371                 public event EventHandler Start;
372
373                 // This event is public, but only Session_[On]End in global.asax will be invoked if present.
374                 public event EventHandler End;
375         }
376 }
377 #endif