SessionStateModule.cs 14 KB

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