SessionStateModule.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. //
  9. // Copyright (C) 2002,2003,2004,2005 Novell, Inc (http://www.novell.com)
  10. // (C) 2003 Stefan Görling (http://www.gorling.se)
  11. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. using System.Web.Configuration;
  32. using System.Web.Caching;
  33. using System.Web.Util;
  34. using System.Security.Cryptography;
  35. using System.Security.Permissions;
  36. namespace System.Web.SessionState
  37. {
  38. // CAS - no InheritanceDemand here as the class is sealed
  39. [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  40. public sealed class SessionStateModule : IHttpModule
  41. {
  42. internal static readonly string CookieName = "ASPSESSION";
  43. internal static readonly string HeaderName = "AspFilterSessionId";
  44. static object locker = new object ();
  45. #if TARGET_J2EE
  46. static private SessionConfig config {
  47. get {
  48. return (SessionConfig)AppDomain.CurrentDomain.GetData("SessionStateModule.config");
  49. }
  50. set {
  51. AppDomain.CurrentDomain.SetData("SessionStateModule.config", value);
  52. }
  53. }
  54. static private Type handlerType {
  55. get {
  56. return (Type)AppDomain.CurrentDomain.GetData("SessionStateModule.handlerType");
  57. }
  58. set {
  59. AppDomain.CurrentDomain.SetData("SessionStateModule.handlerType", value);
  60. }
  61. }
  62. #else
  63. #if CONFIGURATION_2_0
  64. static SessionStateSection config;
  65. #else
  66. static SessionConfig config;
  67. #endif
  68. static Type handlerType;
  69. #endif
  70. ISessionHandler handler;
  71. bool sessionForStaticFiles;
  72. static RandomNumberGenerator rng = RandomNumberGenerator.Create ();
  73. [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
  74. public SessionStateModule ()
  75. {
  76. }
  77. internal RandomNumberGenerator Rng {
  78. get { return rng; }
  79. }
  80. public void Dispose ()
  81. {
  82. if (handler!=null)
  83. handler.Dispose();
  84. }
  85. #if CONFIGURATION_2_0
  86. SessionStateSection GetConfig ()
  87. #else
  88. SessionConfig GetConfig ()
  89. #endif
  90. {
  91. lock (locker) {
  92. if (config != null)
  93. return config;
  94. #if CONFIGURATION_2_0
  95. config = (SessionStateSection) WebConfigurationManager.GetSection ("system.web/sessionState");
  96. #else
  97. config = (SessionConfig) HttpContext.GetAppConfig ("system.web/sessionState");
  98. if (config == null)
  99. config = new SessionConfig (null);
  100. #endif
  101. #if TARGET_J2EE
  102. if (config.Mode == SessionStateMode.SQLServer || config.Mode == SessionStateMode.StateServer)
  103. throw new NotImplementedException("You must use web.xml to specify session state handling");
  104. #else
  105. if (config.Mode == SessionStateMode.StateServer)
  106. handlerType = typeof (SessionStateServerHandler);
  107. if (config.Mode == SessionStateMode.SQLServer)
  108. handlerType = typeof (SessionSQLServerHandler);
  109. #endif
  110. if (config.Mode == SessionStateMode.InProc)
  111. handlerType = typeof (SessionInProcHandler);
  112. return config;
  113. }
  114. }
  115. [EnvironmentPermission (SecurityAction.Assert, Read = "MONO_XSP_STATIC_SESSION")]
  116. public void Init (HttpApplication app)
  117. {
  118. sessionForStaticFiles = (Environment.GetEnvironmentVariable ("MONO_XSP_STATIC_SESSION") != null);
  119. #if CONFIGURATION_2_0
  120. SessionStateSection cfg = GetConfig ();
  121. #else
  122. SessionConfig cfg = GetConfig ();
  123. #endif
  124. if (handlerType == null)
  125. return;
  126. if (cfg.CookieLess)
  127. app.BeginRequest += new EventHandler (OnBeginRequest);
  128. app.AcquireRequestState += new EventHandler (OnAcquireState);
  129. app.ReleaseRequestState += new EventHandler (OnReleaseRequestState);
  130. app.EndRequest += new EventHandler (OnEndRequest);
  131. if (handlerType != null && handler == null) {
  132. handler = (ISessionHandler) Activator.CreateInstance (handlerType);
  133. handler.Init (this, app, cfg); //initialize
  134. }
  135. }
  136. void OnBeginRequest (object o, EventArgs args)
  137. {
  138. HttpApplication application = (HttpApplication) o;
  139. HttpContext context = application.Context;
  140. string base_path = context.Request.BaseVirtualDir;
  141. string id = UrlUtils.GetSessionId (base_path);
  142. if (id == null)
  143. return;
  144. string new_path = UrlUtils.RemoveSessionId (base_path, context.Request.FilePath);
  145. context.Request.SetFilePath (new_path);
  146. context.Request.SetHeader (HeaderName, id);
  147. context.Response.SetAppPathModifier (String.Concat ("(", id, ")"));
  148. }
  149. void OnReleaseRequestState (object o, EventArgs args)
  150. {
  151. if (handler == null)
  152. return;
  153. HttpApplication application = (HttpApplication) o;
  154. HttpContext context = application.Context;
  155. handler.UpdateHandler (context, this);
  156. }
  157. void OnEndRequest (object o, EventArgs args)
  158. {
  159. }
  160. void OnAcquireState (object o, EventArgs args)
  161. {
  162. HttpApplication application = (HttpApplication) o;
  163. HttpContext context = application.Context;
  164. bool required = (context.Handler is IRequiresSessionState);
  165. // This is a hack. Sites that use Session in global.asax event handling code
  166. // are not supposed to get a Session object for static files, but seems that
  167. // IIS handles those files before getting there and thus they are served without
  168. // error.
  169. // As a workaround, setting MONO_XSP_STATIC_SESSION variable make this work
  170. // on mono, but you lose performance when serving static files.
  171. if (sessionForStaticFiles && context.Handler is StaticFileHandler)
  172. required = true;
  173. // hack end
  174. bool read_only = (context.Handler is IReadOnlySessionState);
  175. bool isNew = false;
  176. HttpSessionState session = null;
  177. if (handler != null)
  178. session = handler.UpdateContext (context, this, required, read_only, ref isNew);
  179. if (session != null) {
  180. if (isNew)
  181. session.SetNewSession (true);
  182. if (read_only)
  183. session = session.Clone ();
  184. context.SetSession (session);
  185. HttpRequest request = context.Request;
  186. HttpResponse response = context.Response;
  187. string id = context.Session.SessionID;
  188. if (isNew && config.CookieLess) {
  189. request.SetHeader (HeaderName, id);
  190. response.Redirect (UrlUtils.InsertSessionId (id, request.FilePath));
  191. } else if (isNew) {
  192. HttpCookie cookie = new HttpCookie (CookieName, id);
  193. cookie.Path = request.ApplicationPath;
  194. context.Response.AppendCookie (cookie);
  195. }
  196. if (isNew)
  197. OnSessionStart ();
  198. }
  199. }
  200. void OnSessionStart ()
  201. {
  202. if (Start != null)
  203. Start (this, EventArgs.Empty);
  204. }
  205. internal void OnSessionRemoved (string key, object value, CacheItemRemovedReason reason)
  206. {
  207. #if CONFIGURATION_2_0
  208. SessionStateSection cfg = GetConfig ();
  209. #else
  210. SessionConfig cfg = GetConfig ();
  211. #endif
  212. // Only invoked for InProc (see msdn2 docs on SessionStateModule.End)
  213. if (cfg.Mode == SessionStateMode.InProc)
  214. HttpApplicationFactory.InvokeSessionEnd (value);
  215. }
  216. public event EventHandler Start;
  217. // This event is public, but only Session_[On]End in global.asax will be invoked if present.
  218. public event EventHandler End;
  219. }
  220. }