SessionStateModule.cs 13 KB

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