SessionStateModule.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. try {
  124. Type idManagerType;
  125. try {
  126. idManagerType = Type.GetType (config.SessionIDManagerType, true);
  127. }
  128. catch {
  129. idManagerType = typeof (SessionIDManager);
  130. }
  131. idManager = Activator.CreateInstance (idManagerType) as ISessionIDManager;
  132. idManager.Initialize ();
  133. }
  134. catch (Exception ex) {
  135. throw new HttpException ("Failed to initialize session ID manager.", ex);
  136. }
  137. supportsExpiration = handler.SetItemExpireCallback (OnSessionExpired);
  138. HttpRuntimeSection runtime = WebConfigurationManager.GetSection ("system.web/httpRuntime") as HttpRuntimeSection;
  139. executionTimeout = runtime.ExecutionTimeout;
  140. //executionTimeoutMS = executionTimeout.Milliseconds;
  141. this.app = app;
  142. app.BeginRequest += new EventHandler (OnBeginRequest);
  143. app.AcquireRequestState += new EventHandler (OnAcquireRequestState);
  144. app.ReleaseRequestState += new EventHandler (OnReleaseRequestState);
  145. app.EndRequest += new EventHandler (OnEndRequest);
  146. }
  147. internal static bool IsCookieLess (HttpContext context, SessionStateSection config) {
  148. if (config.Cookieless == HttpCookieMode.UseCookies)
  149. return false;
  150. if (config.Cookieless == HttpCookieMode.UseUri)
  151. return true;
  152. object cookieless = context.Items [CookielessFlagName];
  153. if (cookieless == null)
  154. return false;
  155. return (bool) cookieless;
  156. }
  157. void OnBeginRequest (object o, EventArgs args) {
  158. HttpApplication application = (HttpApplication) o;
  159. HttpContext context = application.Context;
  160. string base_path = context.Request.BaseVirtualDir;
  161. string id = UrlUtils.GetSessionId (base_path);
  162. if (id == null)
  163. return;
  164. string new_path = UrlUtils.RemoveSessionId (base_path, context.Request.FilePath);
  165. context.Request.SetFilePath (new_path);
  166. context.Request.SetHeader (HeaderName, id);
  167. context.Response.SetAppPathModifier (String.Concat ("(", id, ")"));
  168. }
  169. void OnAcquireRequestState (object o, EventArgs args) {
  170. #if TRACE
  171. Console.WriteLine ("SessionStateModule.OnAcquireRequestState (hash {0})", this.GetHashCode ().ToString ("x"));
  172. #endif
  173. HttpApplication application = (HttpApplication) o;
  174. HttpContext context = application.Context;
  175. if (!(context.Handler is IRequiresSessionState)) {
  176. #if TRACE
  177. Console.WriteLine ("Handler ({0}) does not require session state", context.Handler);
  178. #endif
  179. return;
  180. }
  181. bool isReadOnly = (context.Handler is IReadOnlySessionState);
  182. bool supportSessionIDReissue;
  183. if (idManager.InitializeRequest (context, false, out supportSessionIDReissue))
  184. return; // Redirected, will come back here in a while
  185. string sessionId = idManager.GetSessionID (context);
  186. handler.InitializeRequest (context);
  187. GetStoreData (context, sessionId, isReadOnly);
  188. bool isNew = false;
  189. if (storeData == null && !storeLocked) {
  190. isNew = true;
  191. sessionId = idManager.CreateSessionID (context);
  192. #if TRACE
  193. Console.WriteLine ("New session ID allocated: {0}", sessionId);
  194. #endif
  195. bool redirected;
  196. bool cookieAdded;
  197. idManager.SaveSessionID (context, sessionId, out redirected, out cookieAdded);
  198. if (redirected) {
  199. if (supportSessionIDReissue)
  200. handler.CreateUninitializedItem (context, sessionId, config.Timeout.Minutes);
  201. context.Response.End ();
  202. return;
  203. }
  204. else
  205. storeData = handler.CreateNewStoreData (context, config.Timeout.Minutes);
  206. }
  207. else if (storeData == null && storeLocked) {
  208. WaitForStoreUnlock (context, sessionId, isReadOnly);
  209. }
  210. else if (storeData != null &&
  211. !storeLocked &&
  212. storeSessionAction == SessionStateActions.InitializeItem &&
  213. IsCookieLess (context, config)) {
  214. storeData = handler.CreateNewStoreData (context, config.Timeout.Minutes);
  215. }
  216. container = CreateContainer (sessionId, storeData, isNew, isReadOnly);
  217. SessionStateUtility.AddHttpSessionStateToContext (app.Context, container);
  218. if (isNew)
  219. OnSessionStart ();
  220. }
  221. void OnReleaseRequestState (object o, EventArgs args) {
  222. #if TRACE
  223. Console.WriteLine ("SessionStateModule.OnReleaseRequestState (hash {0})", this.GetHashCode ().ToString ("x"));
  224. #endif
  225. HttpApplication application = (HttpApplication) o;
  226. HttpContext context = application.Context;
  227. if (!(context.Handler is IRequiresSessionState))
  228. return;
  229. #if TRACE
  230. Console.WriteLine ("\tsessionId == {0}", container.SessionID);
  231. Console.WriteLine ("\trequest path == {0}", context.Request.FilePath);
  232. Console.WriteLine ("\tHandler ({0}) requires session state", context.Handler);
  233. #endif
  234. try {
  235. if (!container.IsAbandoned) {
  236. #if TRACE
  237. Console.WriteLine ("\tnot abandoned");
  238. #endif
  239. if (!container.IsReadOnly) {
  240. #if TRACE
  241. Console.WriteLine ("\tnot read only, storing and releasing");
  242. #endif
  243. handler.SetAndReleaseItemExclusive (context, container.SessionID, storeData, storeLockId, false);
  244. }
  245. else {
  246. #if TRACE
  247. Console.WriteLine ("\tread only, releasing");
  248. #endif
  249. handler.ReleaseItemExclusive (context, container.SessionID, storeLockId);
  250. }
  251. handler.ResetItemTimeout (context, container.SessionID);
  252. }
  253. else {
  254. handler.ReleaseItemExclusive (context, container.SessionID, storeLockId);
  255. handler.RemoveItem (context, container.SessionID, storeLockId, storeData);
  256. if (supportsExpiration)
  257. // Make sure the expiration handler is not called after we will have raised
  258. // the session end event.
  259. handler.SetItemExpireCallback (null);
  260. SessionStateUtility.RaiseSessionEnd (container, this, args);
  261. }
  262. SessionStateUtility.RemoveHttpSessionStateFromContext (context);
  263. }
  264. finally {
  265. container = null;
  266. storeData = null;
  267. }
  268. }
  269. void OnEndRequest (object o, EventArgs args) {
  270. if (handler == null)
  271. return;
  272. if (container != null)
  273. OnReleaseRequestState (o, args);
  274. HttpApplication application = o as HttpApplication;
  275. if (application == null)
  276. return;
  277. if (handler != null)
  278. handler.EndRequest (application.Context);
  279. }
  280. void GetStoreData (HttpContext context, string sessionId, bool isReadOnly) {
  281. storeData = (isReadOnly) ?
  282. handler.GetItem (context,
  283. sessionId,
  284. out storeLocked,
  285. out storeLockAge,
  286. out storeLockId,
  287. out storeSessionAction)
  288. :
  289. handler.GetItemExclusive (context,
  290. sessionId,
  291. out storeLocked,
  292. out storeLockAge,
  293. out storeLockId,
  294. out storeSessionAction);
  295. }
  296. void WaitForStoreUnlock (HttpContext context, string sessionId, bool isReadonly) {
  297. AutoResetEvent are = new AutoResetEvent (false);
  298. TimerCallback tc = new TimerCallback (StoreUnlockWaitCallback);
  299. CallbackState cs = new CallbackState (context, are, sessionId, isReadonly);
  300. using (Timer timer = new Timer (tc, cs, 500, 500)) {
  301. try {
  302. are.WaitOne (executionTimeout, false);
  303. }
  304. catch {
  305. storeData = null;
  306. }
  307. }
  308. }
  309. void StoreUnlockWaitCallback (object s) {
  310. CallbackState state = (CallbackState) s;
  311. GetStoreData (state.Context, state.SessionId, state.IsReadOnly);
  312. if (storeData == null && storeLocked && (storeLockAge > executionTimeout)) {
  313. handler.ReleaseItemExclusive (state.Context, state.SessionId, storeLockId);
  314. state.AutoEvent.Set ();
  315. }
  316. else if (storeData != null && !storeLocked)
  317. state.AutoEvent.Set ();
  318. }
  319. HttpSessionStateContainer CreateContainer (string sessionId, SessionStateStoreData data, bool isNew, bool isReadOnly) {
  320. if (data == null)
  321. return new HttpSessionStateContainer (
  322. sessionId, null, null, 0, isNew,
  323. config.Cookieless, config.Mode, isReadOnly);
  324. return new HttpSessionStateContainer (
  325. sessionId,
  326. data.Items,
  327. data.StaticObjects,
  328. data.Timeout,
  329. isNew,
  330. config.Cookieless,
  331. config.Mode,
  332. isReadOnly);
  333. }
  334. void OnSessionExpired (string id, SessionStateStoreData item) {
  335. SessionStateUtility.RaiseSessionEnd (
  336. CreateContainer (id, item, false, true),
  337. this, EventArgs.Empty);
  338. }
  339. void OnSessionStart () {
  340. if (Start != null)
  341. Start (this, EventArgs.Empty);
  342. }
  343. public event EventHandler Start;
  344. // This event is public, but only Session_[On]End in global.asax will be invoked if present.
  345. public event EventHandler End;
  346. }
  347. }
  348. #endif