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