SessionStateModule.cs 13 KB

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