SessionStateModule.cs 7.4 KB

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