SessionStateModule.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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. using System.Collections.Specialized;
  33. using System.ComponentModel;
  34. using System.Web.Configuration;
  35. using System.Web.Caching;
  36. using System.Web.Util;
  37. using System.Security.Permissions;
  38. using System.Threading;
  39. using System.Configuration;
  40. using System.Diagnostics;
  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. static readonly object startEvent = new object ();
  63. static readonly object endEvent = new object ();
  64. SessionStateSection config;
  65. SessionStateStoreProviderBase handler;
  66. ISessionIDManager idManager;
  67. bool supportsExpiration;
  68. HttpApplication app;
  69. // Store state
  70. bool storeLocked;
  71. TimeSpan storeLockAge;
  72. object storeLockId;
  73. SessionStateActions storeSessionAction;
  74. bool storeIsNew;
  75. // Session state
  76. SessionStateStoreData storeData;
  77. HttpSessionStateContainer container;
  78. // config
  79. TimeSpan executionTimeout;
  80. //int executionTimeoutMS;
  81. EventHandlerList events = new EventHandlerList ();
  82. public event EventHandler Start {
  83. add { events.AddHandler (startEvent, value); }
  84. remove { events.RemoveHandler (startEvent, value); }
  85. }
  86. // This event is public, but only Session_[On]End in global.asax will be invoked if present.
  87. public event EventHandler End {
  88. add { events.AddHandler (endEvent, value); }
  89. remove { events.RemoveHandler (endEvent, value); }
  90. }
  91. [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
  92. public SessionStateModule () {
  93. }
  94. public void Dispose () {
  95. app.BeginRequest -= new EventHandler (OnBeginRequest);
  96. app.AcquireRequestState -= new EventHandler (OnAcquireRequestState);
  97. app.ReleaseRequestState -= new EventHandler (OnReleaseRequestState);
  98. app.EndRequest -= new EventHandler (OnEndRequest);
  99. handler.Dispose ();
  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. 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. case SessionStateMode.InProc:
  115. settings = new ProviderSettings (null, typeof (SessionInProcHandler).AssemblyQualifiedName);
  116. break;
  117. case SessionStateMode.SQLServer:
  118. settings = new ProviderSettings (null, typeof (SessionSQLServerHandler).AssemblyQualifiedName);
  119. break;
  120. case SessionStateMode.StateServer:
  121. settings = new ProviderSettings (null, typeof (SessionStateServerHandler).AssemblyQualifiedName);
  122. break;
  123. default:
  124. throw new NotImplementedException (String.Format ("The mode '{0}' is not implemented.", config.Mode));
  125. }
  126. handler = (SessionStateStoreProviderBase) ProvidersHelper.InstantiateProvider (settings, typeof (SessionStateStoreProviderBase));
  127. if (String.IsNullOrEmpty(config.SessionIDManagerType)) {
  128. idManager = new SessionIDManager ();
  129. } else {
  130. Type idManagerType = HttpApplication.LoadType (config.SessionIDManagerType, true);
  131. idManager = (ISessionIDManager)Activator.CreateInstance (idManagerType);
  132. }
  133. try {
  134. idManager.Initialize ();
  135. } catch (Exception ex) {
  136. throw new HttpException ("Failed to initialize session ID manager.", ex);
  137. }
  138. supportsExpiration = handler.SetItemExpireCallback (OnSessionExpired);
  139. HttpRuntimeSection runtime = HttpRuntime.Section;
  140. executionTimeout = runtime.ExecutionTimeout;
  141. //executionTimeoutMS = executionTimeout.Milliseconds;
  142. this.app = app;
  143. app.BeginRequest += new EventHandler (OnBeginRequest);
  144. app.AcquireRequestState += new EventHandler (OnAcquireRequestState);
  145. app.ReleaseRequestState += new EventHandler (OnReleaseRequestState);
  146. app.EndRequest += new EventHandler (OnEndRequest);
  147. }
  148. internal static bool IsCookieLess (HttpContext context, SessionStateSection config) {
  149. if (config.Cookieless == HttpCookieMode.UseCookies)
  150. return false;
  151. if (config.Cookieless == HttpCookieMode.UseUri)
  152. return true;
  153. object cookieless = context.Items [CookielessFlagName];
  154. if (cookieless == null)
  155. return false;
  156. return (bool) cookieless;
  157. }
  158. void OnBeginRequest (object o, EventArgs args)
  159. {
  160. HttpApplication application = (HttpApplication) o;
  161. HttpContext context = application.Context;
  162. string file_path = context.Request.FilePath;
  163. string base_path = VirtualPathUtility.GetDirectory (file_path);
  164. string id = UrlUtils.GetSessionId (base_path);
  165. if (id == null)
  166. return;
  167. string new_path = UrlUtils.RemoveSessionId (base_path, file_path);
  168. context.Request.SetFilePath (new_path);
  169. context.Request.SetHeader (HeaderName, id);
  170. context.Response.SetAppPathModifier (id);
  171. }
  172. void OnAcquireRequestState (object o, EventArgs args) {
  173. Trace.WriteLine ("SessionStateModule.OnAcquireRequestState (hash " + this.GetHashCode ().ToString ("x") + ")");
  174. HttpApplication application = (HttpApplication) o;
  175. HttpContext context = application.Context;
  176. if (!(context.Handler is IRequiresSessionState)) {
  177. Trace.WriteLine ("Handler (" + context.Handler + ") does not require session state");
  178. return;
  179. }
  180. bool isReadOnly = (context.Handler is IReadOnlySessionState);
  181. bool supportSessionIDReissue;
  182. if (idManager.InitializeRequest (context, false, out supportSessionIDReissue))
  183. return; // Redirected, will come back here in a while
  184. string sessionId = idManager.GetSessionID (context);
  185. handler.InitializeRequest (context);
  186. storeData = GetStoreData (context, sessionId, isReadOnly);
  187. storeIsNew = false;
  188. if (storeData == null && !storeLocked) {
  189. storeIsNew = true;
  190. sessionId = idManager.CreateSessionID (context);
  191. Trace.WriteLine ("New session ID allocated: " + sessionId);
  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, storeIsNew, isReadOnly);
  214. SessionStateUtility.AddHttpSessionStateToContext (app.Context, container);
  215. if (storeIsNew) {
  216. OnSessionStart ();
  217. HttpSessionState hss = app.Session;
  218. if (hss != null)
  219. storeData.Timeout = hss.Timeout;
  220. }
  221. // Whenever a container is abandoned, we temporarily disable the expire call back.
  222. // So in this case we are quite sure we have a brand new container, so we make sure it works again.
  223. supportsExpiration = handler.SetItemExpireCallback (OnSessionExpired);
  224. }
  225. void OnReleaseRequestState (object o, EventArgs args) {
  226. Trace.WriteLine ("SessionStateModule.OnReleaseRequestState (hash " + this.GetHashCode ().ToString ("x") + ")");
  227. HttpApplication application = (HttpApplication) o;
  228. HttpContext context = application.Context;
  229. if (!(context.Handler is IRequiresSessionState))
  230. return;
  231. Trace.WriteLine ("\tsessionId == " + container.SessionID);
  232. Trace.WriteLine ("\trequest path == " + context.Request.FilePath);
  233. Trace.WriteLine ("\tHandler (" + context.Handler + ") requires session state");
  234. try {
  235. if (!container.IsAbandoned) {
  236. Trace.WriteLine ("\tnot abandoned");
  237. if (!container.IsReadOnly) {
  238. Trace.WriteLine ("\tnot read only, storing and releasing");
  239. handler.SetAndReleaseItemExclusive (context, container.SessionID, storeData, storeLockId, storeIsNew);
  240. }
  241. else {
  242. Trace.WriteLine ("\tread only, releasing");
  243. handler.ReleaseItemExclusive (context, container.SessionID, storeLockId);
  244. }
  245. handler.ResetItemTimeout (context, container.SessionID);
  246. }
  247. else {
  248. handler.ReleaseItemExclusive (context, container.SessionID, storeLockId);
  249. handler.RemoveItem (context, container.SessionID, storeLockId, storeData);
  250. if (supportsExpiration)
  251. // Make sure the expiration handler is not called after we will have raised
  252. // the session end event.
  253. handler.SetItemExpireCallback (null);
  254. SessionStateUtility.RaiseSessionEnd (container, this, args);
  255. }
  256. SessionStateUtility.RemoveHttpSessionStateFromContext (context);
  257. }
  258. finally {
  259. container = null;
  260. storeData = null;
  261. }
  262. }
  263. void OnEndRequest (object o, EventArgs args) {
  264. if (handler == null)
  265. return;
  266. if (container != null)
  267. OnReleaseRequestState (o, args);
  268. HttpApplication application = o as HttpApplication;
  269. if (application == null)
  270. return;
  271. if (handler != null)
  272. handler.EndRequest (application.Context);
  273. }
  274. SessionStateStoreData GetStoreData (HttpContext context, string sessionId, bool isReadOnly) {
  275. SessionStateStoreData item;
  276. item = (isReadOnly) ?
  277. handler.GetItem (context,
  278. sessionId,
  279. out storeLocked,
  280. out storeLockAge,
  281. out storeLockId,
  282. out storeSessionAction)
  283. :
  284. handler.GetItemExclusive (context,
  285. sessionId,
  286. out storeLocked,
  287. out storeLockAge,
  288. out storeLockId,
  289. out storeSessionAction);
  290. if (storeLockId == null)
  291. storeLockId = 0;
  292. return item;
  293. }
  294. void WaitForStoreUnlock (HttpContext context, string sessionId, bool isReadonly) {
  295. AutoResetEvent are = new AutoResetEvent (false);
  296. TimerCallback tc = new TimerCallback (StoreUnlockWaitCallback);
  297. CallbackState cs = new CallbackState (context, are, sessionId, isReadonly);
  298. using (Timer timer = new Timer (tc, cs, 500, 500)) {
  299. try {
  300. are.WaitOne (executionTimeout, false);
  301. }
  302. catch {
  303. storeData = null;
  304. }
  305. }
  306. }
  307. void StoreUnlockWaitCallback (object s) {
  308. CallbackState state = (CallbackState) s;
  309. SessionStateStoreData item = GetStoreData (state.Context, state.SessionId, state.IsReadOnly);
  310. if (item == null && storeLocked && (storeLockAge > executionTimeout)) {
  311. handler.ReleaseItemExclusive (state.Context, state.SessionId, storeLockId);
  312. storeData = null; // Create new state
  313. state.AutoEvent.Set ();
  314. }
  315. else if (item != null && !storeLocked) {
  316. storeData = item;
  317. state.AutoEvent.Set ();
  318. }
  319. }
  320. HttpSessionStateContainer CreateContainer (string sessionId, SessionStateStoreData data, bool isNew, bool isReadOnly) {
  321. if (data == null)
  322. return new HttpSessionStateContainer (
  323. sessionId, null, null, 0, isNew,
  324. config.Cookieless, config.Mode, isReadOnly);
  325. return new HttpSessionStateContainer (
  326. sessionId,
  327. data.Items,
  328. data.StaticObjects,
  329. data.Timeout,
  330. isNew,
  331. config.Cookieless,
  332. config.Mode,
  333. isReadOnly);
  334. }
  335. void OnSessionExpired (string id, SessionStateStoreData item) {
  336. SessionStateUtility.RaiseSessionEnd (
  337. CreateContainer (id, item, false, true),
  338. this, EventArgs.Empty);
  339. }
  340. void OnSessionStart () {
  341. EventHandler eh = events [startEvent] as EventHandler;
  342. if (eh != null)
  343. eh (this, EventArgs.Empty);
  344. }
  345. }
  346. }