SessionStateModule.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. //
  2. // System.Web.SessionState.SesionStateModule
  3. //
  4. // Authors:
  5. // Gonzalo Paniagua Javier ([email protected])
  6. // Stefan Görling ([email protected])
  7. // Jackson Harper ([email protected])
  8. // Marek Habersack ([email protected])
  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. #if NET_2_0
  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.Cryptography;
  39. using System.Security.Permissions;
  40. using System.Threading;
  41. using System.Configuration;
  42. using System.Diagnostics;
  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. public CallbackState (HttpContext context, AutoResetEvent e, string sessionId, bool isReadOnly) {
  56. this.Context = context;
  57. this.AutoEvent = e;
  58. this.SessionId = sessionId;
  59. this.IsReadOnly = isReadOnly;
  60. }
  61. }
  62. internal const string HeaderName = "AspFilterSessionId";
  63. internal const string CookielessFlagName = "_SessionIDManager_IsCookieLess";
  64. static readonly object startEvent = new object ();
  65. static readonly object endEvent = new object ();
  66. SessionStateSection config;
  67. SessionStateStoreProviderBase handler;
  68. ISessionIDManager idManager;
  69. bool supportsExpiration;
  70. HttpApplication app;
  71. // Store state
  72. bool storeLocked;
  73. TimeSpan storeLockAge;
  74. object storeLockId;
  75. SessionStateActions storeSessionAction;
  76. // Session state
  77. SessionStateStoreData storeData;
  78. HttpSessionStateContainer container;
  79. // config
  80. TimeSpan executionTimeout;
  81. //int executionTimeoutMS;
  82. EventHandlerList events = new EventHandlerList ();
  83. public event EventHandler Start {
  84. add { events.AddHandler (startEvent, value); }
  85. remove { events.RemoveHandler (startEvent, value); }
  86. }
  87. // This event is public, but only Session_[On]End in global.asax will be invoked if present.
  88. public event EventHandler End {
  89. add { events.AddHandler (endEvent, value); }
  90. remove { events.RemoveHandler (endEvent, value); }
  91. }
  92. [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
  93. public SessionStateModule () {
  94. }
  95. public void Dispose () {
  96. app.BeginRequest -= new EventHandler (OnBeginRequest);
  97. app.AcquireRequestState -= new EventHandler (OnAcquireRequestState);
  98. app.ReleaseRequestState -= new EventHandler (OnReleaseRequestState);
  99. app.EndRequest -= new EventHandler (OnEndRequest);
  100. handler.Dispose ();
  101. }
  102. [EnvironmentPermission (SecurityAction.Assert, Read = "MONO_XSP_STATIC_SESSION")]
  103. public void Init (HttpApplication app) {
  104. config = (SessionStateSection) WebConfigurationManager.GetSection ("system.web/sessionState");
  105. ProviderSettings settings;
  106. switch (config.Mode) {
  107. case SessionStateMode.Custom:
  108. settings = config.Providers [config.CustomProvider];
  109. if (settings == null)
  110. throw new HttpException (String.Format ("Cannot find '{0}' provider.", config.CustomProvider));
  111. break;
  112. case SessionStateMode.Off:
  113. return;
  114. #if TARGET_J2EE
  115. default:
  116. config = new SessionStateSection ();
  117. config.Mode = SessionStateMode.Custom;
  118. config.CustomProvider = "ServletSessionStateStore";
  119. config.SessionIDManagerType = "Mainsoft.Web.SessionState.ServletSessionIDManager";
  120. config.Providers.Add (new ProviderSettings ("ServletSessionStateStore", "Mainsoft.Web.SessionState.ServletSessionStateStoreProvider"));
  121. goto case SessionStateMode.Custom;
  122. #else
  123. case SessionStateMode.InProc:
  124. settings = new ProviderSettings (null, typeof (SessionInProcHandler).AssemblyQualifiedName);
  125. break;
  126. case SessionStateMode.SQLServer:
  127. //settings = new ProviderSettings (null, typeof (SessionInProcHandler).AssemblyQualifiedName);
  128. //break;
  129. default:
  130. throw new NotImplementedException (String.Format ("The mode '{0}' is not implemented.", config.Mode));
  131. case SessionStateMode.StateServer:
  132. settings = new ProviderSettings (null, typeof (SessionStateServerHandler).AssemblyQualifiedName);
  133. break;
  134. #endif
  135. }
  136. handler = (SessionStateStoreProviderBase) ProvidersHelper.InstantiateProvider (settings, typeof (SessionStateStoreProviderBase));
  137. if (String.IsNullOrEmpty(config.SessionIDManagerType)) {
  138. idManager = new SessionIDManager ();
  139. } else {
  140. Type idManagerType = HttpApplication.LoadType (config.SessionIDManagerType, true);
  141. idManager = (ISessionIDManager)Activator.CreateInstance (idManagerType);
  142. }
  143. try {
  144. idManager.Initialize ();
  145. } catch (Exception ex) {
  146. throw new HttpException ("Failed to initialize session ID manager.", ex);
  147. }
  148. supportsExpiration = handler.SetItemExpireCallback (OnSessionExpired);
  149. HttpRuntimeSection runtime = WebConfigurationManager.GetSection ("system.web/httpRuntime") as HttpRuntimeSection;
  150. executionTimeout = runtime.ExecutionTimeout;
  151. //executionTimeoutMS = executionTimeout.Milliseconds;
  152. this.app = app;
  153. app.BeginRequest += new EventHandler (OnBeginRequest);
  154. app.AcquireRequestState += new EventHandler (OnAcquireRequestState);
  155. app.ReleaseRequestState += new EventHandler (OnReleaseRequestState);
  156. app.EndRequest += new EventHandler (OnEndRequest);
  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. void OnBeginRequest (object o, EventArgs args) {
  169. HttpApplication application = (HttpApplication) o;
  170. HttpContext context = application.Context;
  171. string base_path = context.Request.BaseVirtualDir;
  172. string id = UrlUtils.GetSessionId (base_path);
  173. if (id == null)
  174. return;
  175. string new_path = UrlUtils.RemoveSessionId (base_path, context.Request.FilePath);
  176. context.Request.SetFilePath (new_path);
  177. context.Request.SetHeader (HeaderName, id);
  178. context.Response.SetAppPathModifier (id);
  179. }
  180. void OnAcquireRequestState (object o, EventArgs args) {
  181. Trace.WriteLine ("SessionStateModule.OnAcquireRequestState (hash " + this.GetHashCode ().ToString ("x") + ")");
  182. HttpApplication application = (HttpApplication) o;
  183. HttpContext context = application.Context;
  184. if (!(context.Handler is IRequiresSessionState)) {
  185. Trace.WriteLine ("Handler (" + context.Handler + ") does not require session state");
  186. return;
  187. }
  188. bool isReadOnly = (context.Handler is IReadOnlySessionState);
  189. bool supportSessionIDReissue;
  190. if (idManager.InitializeRequest (context, false, out supportSessionIDReissue))
  191. return; // Redirected, will come back here in a while
  192. string sessionId = idManager.GetSessionID (context);
  193. handler.InitializeRequest (context);
  194. GetStoreData (context, sessionId, isReadOnly);
  195. bool isNew = false;
  196. if (storeData == null && !storeLocked) {
  197. isNew = true;
  198. sessionId = idManager.CreateSessionID (context);
  199. Trace.WriteLine ("New session ID allocated: " + sessionId);
  200. bool redirected;
  201. bool cookieAdded;
  202. idManager.SaveSessionID (context, sessionId, out redirected, out cookieAdded);
  203. if (redirected) {
  204. if (supportSessionIDReissue)
  205. handler.CreateUninitializedItem (context, sessionId, (int)config.Timeout.TotalMinutes);
  206. context.Response.End ();
  207. return;
  208. }
  209. else
  210. storeData = handler.CreateNewStoreData (context, (int)config.Timeout.TotalMinutes);
  211. }
  212. else if (storeData == null && storeLocked) {
  213. WaitForStoreUnlock (context, sessionId, isReadOnly);
  214. }
  215. else if (storeData != null &&
  216. !storeLocked &&
  217. storeSessionAction == SessionStateActions.InitializeItem &&
  218. IsCookieLess (context, config)) {
  219. storeData = handler.CreateNewStoreData (context, (int)config.Timeout.TotalMinutes);
  220. }
  221. container = CreateContainer (sessionId, storeData, isNew, isReadOnly);
  222. SessionStateUtility.AddHttpSessionStateToContext (app.Context, container);
  223. if (isNew) {
  224. OnSessionStart ();
  225. HttpSessionState hss = app.Session;
  226. if (hss != null)
  227. storeData.Timeout = hss.Timeout;
  228. }
  229. }
  230. void OnReleaseRequestState (object o, EventArgs args) {
  231. Trace.WriteLine ("SessionStateModule.OnReleaseRequestState (hash " + this.GetHashCode ().ToString ("x") + ")");
  232. HttpApplication application = (HttpApplication) o;
  233. HttpContext context = application.Context;
  234. if (!(context.Handler is IRequiresSessionState))
  235. return;
  236. Trace.WriteLine ("\tsessionId == " + container.SessionID);
  237. Trace.WriteLine ("\trequest path == " + context.Request.FilePath);
  238. Trace.WriteLine ("\tHandler (" + context.Handler + ") requires session state");
  239. try {
  240. if (!container.IsAbandoned) {
  241. Trace.WriteLine ("\tnot abandoned");
  242. if (!container.IsReadOnly) {
  243. Trace.WriteLine ("\tnot read only, storing and releasing");
  244. handler.SetAndReleaseItemExclusive (context, container.SessionID, storeData, storeLockId, false);
  245. }
  246. else {
  247. Trace.WriteLine ("\tread only, releasing");
  248. handler.ReleaseItemExclusive (context, container.SessionID, storeLockId);
  249. }
  250. handler.ResetItemTimeout (context, container.SessionID);
  251. }
  252. else {
  253. handler.ReleaseItemExclusive (context, container.SessionID, storeLockId);
  254. handler.RemoveItem (context, container.SessionID, storeLockId, storeData);
  255. if (supportsExpiration)
  256. #if TARGET_J2EE
  257. ;
  258. else
  259. #else
  260. // Make sure the expiration handler is not called after we will have raised
  261. // the session end event.
  262. handler.SetItemExpireCallback (null);
  263. #endif
  264. SessionStateUtility.RaiseSessionEnd (container, this, args);
  265. }
  266. SessionStateUtility.RemoveHttpSessionStateFromContext (context);
  267. }
  268. finally {
  269. container = null;
  270. storeData = null;
  271. }
  272. }
  273. void OnEndRequest (object o, EventArgs args) {
  274. if (handler == null)
  275. return;
  276. if (container != null)
  277. OnReleaseRequestState (o, args);
  278. HttpApplication application = o as HttpApplication;
  279. if (application == null)
  280. return;
  281. if (handler != null)
  282. handler.EndRequest (application.Context);
  283. }
  284. void GetStoreData (HttpContext context, string sessionId, bool isReadOnly) {
  285. storeData = (isReadOnly) ?
  286. handler.GetItem (context,
  287. sessionId,
  288. out storeLocked,
  289. out storeLockAge,
  290. out storeLockId,
  291. out storeSessionAction)
  292. :
  293. handler.GetItemExclusive (context,
  294. sessionId,
  295. out storeLocked,
  296. out storeLockAge,
  297. out storeLockId,
  298. out storeSessionAction);
  299. }
  300. void WaitForStoreUnlock (HttpContext context, string sessionId, bool isReadonly) {
  301. AutoResetEvent are = new AutoResetEvent (false);
  302. TimerCallback tc = new TimerCallback (StoreUnlockWaitCallback);
  303. CallbackState cs = new CallbackState (context, are, sessionId, isReadonly);
  304. using (Timer timer = new Timer (tc, cs, 500, 500)) {
  305. try {
  306. are.WaitOne (executionTimeout, false);
  307. }
  308. catch {
  309. storeData = null;
  310. }
  311. }
  312. }
  313. void StoreUnlockWaitCallback (object s) {
  314. CallbackState state = (CallbackState) s;
  315. GetStoreData (state.Context, state.SessionId, state.IsReadOnly);
  316. if (storeData == null && storeLocked && (storeLockAge > executionTimeout)) {
  317. handler.ReleaseItemExclusive (state.Context, state.SessionId, storeLockId);
  318. state.AutoEvent.Set ();
  319. }
  320. else if (storeData != null && !storeLocked)
  321. state.AutoEvent.Set ();
  322. }
  323. HttpSessionStateContainer CreateContainer (string sessionId, SessionStateStoreData data, bool isNew, bool isReadOnly) {
  324. if (data == null)
  325. return new HttpSessionStateContainer (
  326. sessionId, null, null, 0, isNew,
  327. config.Cookieless, config.Mode, isReadOnly);
  328. return new HttpSessionStateContainer (
  329. sessionId,
  330. data.Items,
  331. data.StaticObjects,
  332. data.Timeout,
  333. isNew,
  334. config.Cookieless,
  335. config.Mode,
  336. isReadOnly);
  337. }
  338. void OnSessionExpired (string id, SessionStateStoreData item) {
  339. SessionStateUtility.RaiseSessionEnd (
  340. CreateContainer (id, item, false, true),
  341. this, EventArgs.Empty);
  342. }
  343. void OnSessionStart () {
  344. EventHandler eh = events [startEvent] as EventHandler;
  345. if (eh != null)
  346. eh (this, EventArgs.Empty);
  347. }
  348. }
  349. }
  350. #endif