SessionStateModule.cs 12 KB

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