SessionStateModule.cs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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.Caching;
  32. using System.Web.Util;
  33. using System.Security.Cryptography;
  34. using System.Security.Permissions;
  35. namespace System.Web.SessionState
  36. {
  37. // CAS - no InheritanceDemand here as the class is sealed
  38. [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  39. public sealed class SessionStateModule : IHttpModule
  40. {
  41. internal static readonly string CookieName = "ASPSESSION";
  42. internal static readonly string HeaderName = "AspFilterSessionId";
  43. static object locker = new object ();
  44. #if TARGET_J2EE
  45. static private SessionConfig config {
  46. get {
  47. return (SessionConfig)AppDomain.CurrentDomain.GetData("SessionStateModule.config");
  48. }
  49. set {
  50. AppDomain.CurrentDomain.SetData("SessionStateModule.config", value);
  51. }
  52. }
  53. static private Type handlerType {
  54. get {
  55. return (Type)AppDomain.CurrentDomain.GetData("SessionStateModule.handlerType");
  56. }
  57. set {
  58. AppDomain.CurrentDomain.SetData("SessionStateModule.handlerType", value);
  59. }
  60. }
  61. #else
  62. static SessionConfig config;
  63. static Type handlerType;
  64. #endif
  65. ISessionHandler handler;
  66. bool sessionForStaticFiles;
  67. static RandomNumberGenerator rng = RandomNumberGenerator.Create ();
  68. [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
  69. public SessionStateModule ()
  70. {
  71. }
  72. internal RandomNumberGenerator Rng {
  73. get { return rng; }
  74. }
  75. public void Dispose ()
  76. {
  77. if (handler!=null)
  78. handler.Dispose();
  79. }
  80. SessionConfig GetConfig ()
  81. {
  82. lock (locker) {
  83. if (config != null)
  84. return config;
  85. config = (SessionConfig) HttpContext.GetAppConfig ("system.web/sessionState");
  86. if (config == null)
  87. config = new SessionConfig (null);
  88. #if TARGET_J2EE
  89. if (config.Mode == SessionStateMode.SQLServer || config.Mode == SessionStateMode.StateServer)
  90. throw new NotImplementedException("You must use web.xml to specify session state handling");
  91. #else
  92. if (config.Mode == SessionStateMode.StateServer)
  93. handlerType = typeof (SessionStateServerHandler);
  94. if (config.Mode == SessionStateMode.SQLServer)
  95. handlerType = typeof (SessionSQLServerHandler);
  96. #endif
  97. if (config.Mode == SessionStateMode.InProc)
  98. handlerType = typeof (SessionInProcHandler);
  99. return config;
  100. }
  101. }
  102. [EnvironmentPermission (SecurityAction.Assert, Read = "MONO_XSP_STATIC_SESSION")]
  103. public void Init (HttpApplication app)
  104. {
  105. sessionForStaticFiles = (Environment.GetEnvironmentVariable ("MONO_XSP_STATIC_SESSION") != null);
  106. SessionConfig cfg = GetConfig ();
  107. if (handlerType == null)
  108. return;
  109. if (config.CookieLess)
  110. app.BeginRequest += new EventHandler (OnBeginRequest);
  111. app.AcquireRequestState += new EventHandler (OnAcquireState);
  112. app.ReleaseRequestState += new EventHandler (OnReleaseRequestState);
  113. app.EndRequest += new EventHandler (OnEndRequest);
  114. if (handlerType != null && handler == null) {
  115. handler = (ISessionHandler) Activator.CreateInstance (handlerType);
  116. handler.Init (this, app, config); //initialize
  117. }
  118. }
  119. void OnBeginRequest (object o, EventArgs args)
  120. {
  121. HttpApplication application = (HttpApplication) o;
  122. HttpContext context = application.Context;
  123. string base_path = context.Request.BaseVirtualDir;
  124. string id = UrlUtils.GetSessionId (base_path);
  125. if (id == null)
  126. return;
  127. context.Request.SetCurrentExePath (UrlUtils.RemoveSessionId (base_path,
  128. context.Request.FilePath));
  129. context.Request.SetHeader (HeaderName, id);
  130. context.Response.SetAppPathModifier (String.Format ("({0})", id));
  131. }
  132. void OnReleaseRequestState (object o, EventArgs args)
  133. {
  134. if (handler == null)
  135. return;
  136. HttpApplication application = (HttpApplication) o;
  137. HttpContext context = application.Context;
  138. handler.UpdateHandler (context, this);
  139. }
  140. void OnEndRequest (object o, EventArgs args)
  141. {
  142. }
  143. void OnAcquireState (object o, EventArgs args)
  144. {
  145. HttpApplication application = (HttpApplication) o;
  146. HttpContext context = application.Context;
  147. bool required = (context.Handler is IRequiresSessionState);
  148. // This is a hack. Sites that use Session in global.asax event handling code
  149. // are not supposed to get a Session object for static files, but seems that
  150. // IIS handles those files before getting there and thus they are served without
  151. // error.
  152. // As a workaround, setting MONO_XSP_STATIC_SESSION variable make this work
  153. // on mono, but you lose performance when serving static files.
  154. if (sessionForStaticFiles && context.Handler is StaticFileHandler)
  155. required = true;
  156. // hack end
  157. bool read_only = (context.Handler is IReadOnlySessionState);
  158. bool isNew = false;
  159. HttpSessionState session = null;
  160. if (handler != null)
  161. session = handler.UpdateContext (context, this, required, read_only, ref isNew);
  162. if (session != null) {
  163. if (isNew)
  164. session.SetNewSession (true);
  165. if (read_only)
  166. session = session.Clone ();
  167. context.SetSession (session);
  168. if (isNew && config.CookieLess) {
  169. string id = context.Session.SessionID;
  170. context.Request.SetHeader (HeaderName, id);
  171. context.Response.Redirect (UrlUtils.InsertSessionId (id,
  172. context.Request.FilePath));
  173. } else if (isNew) {
  174. string id = context.Session.SessionID;
  175. HttpCookie cookie = new HttpCookie (CookieName, id);
  176. cookie.Path = UrlUtils.GetDirectory (context.Request.ApplicationPath);
  177. context.Response.AppendCookie (cookie);
  178. }
  179. if (isNew)
  180. OnSessionStart ();
  181. }
  182. }
  183. void OnSessionStart ()
  184. {
  185. if (Start != null)
  186. Start (this, EventArgs.Empty);
  187. }
  188. internal void OnSessionRemoved (string key, object value, CacheItemRemovedReason reason)
  189. {
  190. // Only invoked for InProc (see msdn2 docs on SessionStateModule.End)
  191. if (GetConfig ().Mode == SessionStateMode.InProc)
  192. HttpApplicationFactory.InvokeSessionEnd (value);
  193. }
  194. public event EventHandler Start;
  195. // This event is public, but only Session_[On]End in global.asax will be invoked if present.
  196. public event EventHandler End;
  197. }
  198. }