SessionStateModule.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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. {
  170. HttpApplication application = (HttpApplication) o;
  171. HttpContext context = application.Context;
  172. string file_path = context.Request.FilePath;
  173. string base_path = VirtualPathUtility.GetDirectory (file_path);
  174. string id = UrlUtils.GetSessionId (base_path);
  175. if (id == null)
  176. return;
  177. string new_path = UrlUtils.RemoveSessionId (base_path, file_path);
  178. context.Request.SetFilePath (new_path);
  179. context.Request.SetHeader (HeaderName, id);
  180. context.Response.SetAppPathModifier (id);
  181. }
  182. void OnAcquireRequestState (object o, EventArgs args) {
  183. Trace.WriteLine ("SessionStateModule.OnAcquireRequestState (hash " + this.GetHashCode ().ToString ("x") + ")");
  184. HttpApplication application = (HttpApplication) o;
  185. HttpContext context = application.Context;
  186. if (!(context.Handler is IRequiresSessionState)) {
  187. Trace.WriteLine ("Handler (" + context.Handler + ") does not require session state");
  188. return;
  189. }
  190. bool isReadOnly = (context.Handler is IReadOnlySessionState);
  191. bool supportSessionIDReissue;
  192. if (idManager.InitializeRequest (context, false, out supportSessionIDReissue))
  193. return; // Redirected, will come back here in a while
  194. string sessionId = idManager.GetSessionID (context);
  195. handler.InitializeRequest (context);
  196. GetStoreData (context, sessionId, isReadOnly);
  197. bool isNew = false;
  198. if (storeData == null && !storeLocked) {
  199. isNew = true;
  200. sessionId = idManager.CreateSessionID (context);
  201. Trace.WriteLine ("New session ID allocated: " + sessionId);
  202. bool redirected;
  203. bool cookieAdded;
  204. idManager.SaveSessionID (context, sessionId, out redirected, out cookieAdded);
  205. if (redirected) {
  206. if (supportSessionIDReissue)
  207. handler.CreateUninitializedItem (context, sessionId, (int)config.Timeout.TotalMinutes);
  208. context.Response.End ();
  209. return;
  210. }
  211. else
  212. storeData = handler.CreateNewStoreData (context, (int)config.Timeout.TotalMinutes);
  213. }
  214. else if (storeData == null && storeLocked) {
  215. WaitForStoreUnlock (context, sessionId, isReadOnly);
  216. }
  217. else if (storeData != null &&
  218. !storeLocked &&
  219. storeSessionAction == SessionStateActions.InitializeItem &&
  220. IsCookieLess (context, config)) {
  221. storeData = handler.CreateNewStoreData (context, (int)config.Timeout.TotalMinutes);
  222. }
  223. container = CreateContainer (sessionId, storeData, isNew, isReadOnly);
  224. SessionStateUtility.AddHttpSessionStateToContext (app.Context, container);
  225. if (isNew) {
  226. OnSessionStart ();
  227. HttpSessionState hss = app.Session;
  228. if (hss != null)
  229. storeData.Timeout = hss.Timeout;
  230. }
  231. }
  232. void OnReleaseRequestState (object o, EventArgs args) {
  233. Trace.WriteLine ("SessionStateModule.OnReleaseRequestState (hash " + this.GetHashCode ().ToString ("x") + ")");
  234. HttpApplication application = (HttpApplication) o;
  235. HttpContext context = application.Context;
  236. if (!(context.Handler is IRequiresSessionState))
  237. return;
  238. Trace.WriteLine ("\tsessionId == " + container.SessionID);
  239. Trace.WriteLine ("\trequest path == " + context.Request.FilePath);
  240. Trace.WriteLine ("\tHandler (" + context.Handler + ") requires session state");
  241. try {
  242. if (!container.IsAbandoned) {
  243. Trace.WriteLine ("\tnot abandoned");
  244. if (!container.IsReadOnly) {
  245. Trace.WriteLine ("\tnot read only, storing and releasing");
  246. handler.SetAndReleaseItemExclusive (context, container.SessionID, storeData, storeLockId, false);
  247. }
  248. else {
  249. Trace.WriteLine ("\tread only, releasing");
  250. handler.ReleaseItemExclusive (context, container.SessionID, storeLockId);
  251. }
  252. handler.ResetItemTimeout (context, container.SessionID);
  253. }
  254. else {
  255. handler.ReleaseItemExclusive (context, container.SessionID, storeLockId);
  256. handler.RemoveItem (context, container.SessionID, storeLockId, storeData);
  257. if (supportsExpiration)
  258. #if TARGET_J2EE
  259. ;
  260. else
  261. #else
  262. // Make sure the expiration handler is not called after we will have raised
  263. // the session end event.
  264. handler.SetItemExpireCallback (null);
  265. #endif
  266. SessionStateUtility.RaiseSessionEnd (container, this, args);
  267. }
  268. SessionStateUtility.RemoveHttpSessionStateFromContext (context);
  269. }
  270. finally {
  271. container = null;
  272. storeData = null;
  273. }
  274. }
  275. void OnEndRequest (object o, EventArgs args) {
  276. if (handler == null)
  277. return;
  278. if (container != null)
  279. OnReleaseRequestState (o, args);
  280. HttpApplication application = o as HttpApplication;
  281. if (application == null)
  282. return;
  283. if (handler != null)
  284. handler.EndRequest (application.Context);
  285. }
  286. void GetStoreData (HttpContext context, string sessionId, bool isReadOnly) {
  287. storeData = (isReadOnly) ?
  288. handler.GetItem (context,
  289. sessionId,
  290. out storeLocked,
  291. out storeLockAge,
  292. out storeLockId,
  293. out storeSessionAction)
  294. :
  295. handler.GetItemExclusive (context,
  296. sessionId,
  297. out storeLocked,
  298. out storeLockAge,
  299. out storeLockId,
  300. out storeSessionAction);
  301. }
  302. void WaitForStoreUnlock (HttpContext context, string sessionId, bool isReadonly) {
  303. AutoResetEvent are = new AutoResetEvent (false);
  304. TimerCallback tc = new TimerCallback (StoreUnlockWaitCallback);
  305. CallbackState cs = new CallbackState (context, are, sessionId, isReadonly);
  306. using (Timer timer = new Timer (tc, cs, 500, 500)) {
  307. try {
  308. are.WaitOne (executionTimeout, false);
  309. }
  310. catch {
  311. storeData = null;
  312. }
  313. }
  314. }
  315. void StoreUnlockWaitCallback (object s) {
  316. CallbackState state = (CallbackState) s;
  317. GetStoreData (state.Context, state.SessionId, state.IsReadOnly);
  318. if (storeData == null && storeLocked && (storeLockAge > executionTimeout)) {
  319. handler.ReleaseItemExclusive (state.Context, state.SessionId, storeLockId);
  320. state.AutoEvent.Set ();
  321. }
  322. else if (storeData != null && !storeLocked)
  323. state.AutoEvent.Set ();
  324. }
  325. HttpSessionStateContainer CreateContainer (string sessionId, SessionStateStoreData data, bool isNew, bool isReadOnly) {
  326. if (data == null)
  327. return new HttpSessionStateContainer (
  328. sessionId, null, null, 0, isNew,
  329. config.Cookieless, config.Mode, isReadOnly);
  330. return new HttpSessionStateContainer (
  331. sessionId,
  332. data.Items,
  333. data.StaticObjects,
  334. data.Timeout,
  335. isNew,
  336. config.Cookieless,
  337. config.Mode,
  338. isReadOnly);
  339. }
  340. void OnSessionExpired (string id, SessionStateStoreData item) {
  341. SessionStateUtility.RaiseSessionEnd (
  342. CreateContainer (id, item, false, true),
  343. this, EventArgs.Empty);
  344. }
  345. void OnSessionStart () {
  346. EventHandler eh = events [startEvent] as EventHandler;
  347. if (eh != null)
  348. eh (this, EventArgs.Empty);
  349. }
  350. }
  351. }
  352. #endif