SessionStateModule.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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-2006 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 const string CookieName = "ASPSESSION";
  43. internal const string HeaderName = "AspFilterSessionId";
  44. static object locker = new object ();
  45. #if TARGET_J2EE
  46. #if NET_2_0
  47. static private SessionStateSection config {
  48. get
  49. {
  50. return (SessionStateSection) AppDomain.CurrentDomain.GetData ("SessionStateModule.config");
  51. }
  52. set
  53. {
  54. AppDomain.CurrentDomain.SetData ("SessionStateModule.config", value);
  55. }
  56. }
  57. static private Type handlerType
  58. {
  59. get
  60. {
  61. return (Type) AppDomain.CurrentDomain.GetData ("SessionStateModule.handlerType");
  62. }
  63. set
  64. {
  65. AppDomain.CurrentDomain.SetData ("SessionStateModule.handlerType", value);
  66. }
  67. }
  68. #else
  69. static private SessionConfig config {
  70. get {
  71. return (SessionConfig)AppDomain.CurrentDomain.GetData("SessionStateModule.config");
  72. }
  73. set {
  74. AppDomain.CurrentDomain.SetData("SessionStateModule.config", value);
  75. }
  76. }
  77. static private Type handlerType {
  78. get {
  79. return (Type)AppDomain.CurrentDomain.GetData("SessionStateModule.handlerType");
  80. }
  81. set {
  82. AppDomain.CurrentDomain.SetData("SessionStateModule.handlerType", value);
  83. }
  84. }
  85. #endif
  86. #else
  87. #if NET_2_0
  88. static SessionStateSection config;
  89. #else
  90. static SessionConfig config;
  91. #endif
  92. static Type handlerType;
  93. #endif
  94. ISessionHandler handler;
  95. bool sessionForStaticFiles;
  96. static RandomNumberGenerator rng = RandomNumberGenerator.Create ();
  97. [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
  98. public SessionStateModule ()
  99. {
  100. }
  101. internal RandomNumberGenerator Rng {
  102. get { return rng; }
  103. }
  104. public void Dispose ()
  105. {
  106. if (handler!=null)
  107. handler.Dispose();
  108. }
  109. #if NET_2_0
  110. SessionStateSection GetConfig ()
  111. #else
  112. SessionConfig GetConfig ()
  113. #endif
  114. {
  115. lock (locker) {
  116. if (config != null)
  117. return config;
  118. #if NET_2_0
  119. config = (SessionStateSection) WebConfigurationManager.GetSection ("system.web/sessionState");
  120. #else
  121. config = (SessionConfig) HttpContext.GetAppConfig ("system.web/sessionState");
  122. if (config == null)
  123. config = new SessionConfig (null);
  124. #endif
  125. #if TARGET_J2EE
  126. if (config.Mode == SessionStateMode.SQLServer || config.Mode == SessionStateMode.StateServer)
  127. throw new NotImplementedException("You must use web.xml to specify session state handling");
  128. #else
  129. if (config.Mode == SessionStateMode.StateServer)
  130. handlerType = typeof (SessionStateServerHandler);
  131. if (config.Mode == SessionStateMode.SQLServer)
  132. handlerType = typeof (SessionSQLServerHandler);
  133. #endif
  134. if (config.Mode == SessionStateMode.InProc)
  135. handlerType = typeof (SessionInProcHandler);
  136. return config;
  137. }
  138. }
  139. [EnvironmentPermission (SecurityAction.Assert, Read = "MONO_XSP_STATIC_SESSION")]
  140. public void Init (HttpApplication app)
  141. {
  142. sessionForStaticFiles = (Environment.GetEnvironmentVariable ("MONO_XSP_STATIC_SESSION") != null);
  143. #if NET_2_0
  144. SessionStateSection cfg = GetConfig ();
  145. #else
  146. SessionConfig cfg = GetConfig ();
  147. #endif
  148. if (handlerType == null)
  149. return;
  150. if (cfg.CookieLess)
  151. app.BeginRequest += new EventHandler (OnBeginRequest);
  152. app.AcquireRequestState += new EventHandler (OnAcquireState);
  153. app.ReleaseRequestState += new EventHandler (OnReleaseRequestState);
  154. app.EndRequest += new EventHandler (OnEndRequest);
  155. if (handlerType != null && handler == null) {
  156. handler = (ISessionHandler) Activator.CreateInstance (handlerType);
  157. handler.Init (this, app, cfg); //initialize
  158. }
  159. }
  160. void OnBeginRequest (object o, EventArgs args)
  161. {
  162. HttpApplication application = (HttpApplication) o;
  163. HttpContext context = application.Context;
  164. string base_path = context.Request.BaseVirtualDir;
  165. string id = UrlUtils.GetSessionId (base_path);
  166. if (id == null)
  167. return;
  168. string new_path = UrlUtils.RemoveSessionId (base_path, context.Request.FilePath);
  169. context.Request.SetFilePath (new_path);
  170. context.Request.SetHeader (HeaderName, id);
  171. context.Response.SetAppPathModifier (String.Concat ("(", id, ")"));
  172. }
  173. void OnReleaseRequestState (object o, EventArgs args)
  174. {
  175. if (handler == null)
  176. return;
  177. HttpApplication application = (HttpApplication) o;
  178. HttpContext context = application.Context;
  179. handler.UpdateHandler (context, this);
  180. }
  181. void OnEndRequest (object o, EventArgs args)
  182. {
  183. }
  184. void OnAcquireState (object o, EventArgs args)
  185. {
  186. HttpApplication application = (HttpApplication) o;
  187. HttpContext context = application.Context;
  188. bool required = (context.Handler is IRequiresSessionState);
  189. // This is a hack. Sites that use Session in global.asax event handling code
  190. // are not supposed to get a Session object for static files, but seems that
  191. // IIS handles those files before getting there and thus they are served without
  192. // error.
  193. // As a workaround, setting MONO_XSP_STATIC_SESSION variable make this work
  194. // on mono, but you lose performance when serving static files.
  195. if (sessionForStaticFiles && context.Handler is StaticFileHandler)
  196. required = true;
  197. // hack end
  198. bool read_only = (context.Handler is IReadOnlySessionState);
  199. bool isNew = false;
  200. HttpSessionState session = null;
  201. if (handler != null)
  202. session = handler.UpdateContext (context, this, required, read_only, ref isNew);
  203. if (session != null) {
  204. if (isNew)
  205. session.SetNewSession (true);
  206. if (read_only)
  207. session = session.Clone ();
  208. context.SetSession (session);
  209. HttpRequest request = context.Request;
  210. HttpResponse response = context.Response;
  211. string id = context.Session.SessionID;
  212. if (isNew && config.CookieLess) {
  213. request.SetHeader (HeaderName, id);
  214. response.Redirect (UrlUtils.InsertSessionId (id, request.FilePath));
  215. } else if (isNew) {
  216. HttpCookie cookie = new HttpCookie (CookieName, id);
  217. cookie.Path = request.ApplicationPath;
  218. context.Response.AppendCookie (cookie);
  219. }
  220. if (isNew)
  221. OnSessionStart ();
  222. }
  223. }
  224. void OnSessionStart ()
  225. {
  226. if (Start != null)
  227. Start (this, EventArgs.Empty);
  228. }
  229. internal void OnSessionRemoved (string key, object value, CacheItemRemovedReason reason)
  230. {
  231. #if NET_2_0
  232. SessionStateSection cfg = GetConfig ();
  233. #else
  234. SessionConfig cfg = GetConfig ();
  235. #endif
  236. // Only invoked for InProc (see msdn2 docs on SessionStateModule.End)
  237. if (cfg.Mode == SessionStateMode.InProc)
  238. HttpApplicationFactory.InvokeSessionEnd (value);
  239. }
  240. public event EventHandler Start;
  241. // This event is public, but only Session_[On]End in global.asax will be invoked if present.
  242. public event EventHandler End;
  243. }
  244. }