SessionStateModule.cs 12 KB

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