1   //========================================================================
2   //Copyright 2006 Mort Bay Consulting Pty. Ltd.
3   //------------------------------------------------------------------------
4   //Licensed under the Apache License, Version 2.0 (the "License");
5   //you may not use this file except in compliance with the License.
6   //You may obtain a copy of the License at 
7   //http://www.apache.org/licenses/LICENSE-2.0
8   //Unless required by applicable law or agreed to in writing, software
9   //distributed under the License is distributed on an "AS IS" BASIS,
10  //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11  //See the License for the specific language governing permissions and
12  //limitations under the License.
13  //========================================================================
14  
15  package org.mortbay.jetty.servlet;
16  
17  import java.security.NoSuchAlgorithmException;
18  import java.security.SecureRandom;
19  import java.util.Random;
20  
21  import javax.servlet.http.HttpServletRequest;
22  import javax.servlet.http.HttpSession;
23  
24  import org.mortbay.component.AbstractLifeCycle;
25  import org.mortbay.jetty.SessionIdManager;
26  import org.mortbay.jetty.servlet.AbstractSessionManager.Session;
27  import org.mortbay.log.Log;
28  import org.mortbay.util.MultiMap;
29  
30  /* ------------------------------------------------------------ */
31  /**
32   * HashSessionIdManager. An in-memory implementation of the session ID manager.
33   */
34  public class HashSessionIdManager extends AbstractLifeCycle implements SessionIdManager
35  {
36      private final static String __NEW_SESSION_ID="org.mortbay.jetty.newSessionId";  
37      protected final static String SESSION_ID_RANDOM_ALGORITHM = "SHA1PRNG";
38      protected final static String SESSION_ID_RANDOM_ALGORITHM_ALT = "IBMSecureRandom";
39  
40      MultiMap<String> _sessions;
41      protected Random _random;
42      private boolean _weakRandom;
43      private String _workerName;
44  
45      /* ------------------------------------------------------------ */
46      public HashSessionIdManager()
47      {
48      }
49  
50      /* ------------------------------------------------------------ */
51      public HashSessionIdManager(Random random)
52      {
53          _random=random;
54        
55      }
56  
57      /* ------------------------------------------------------------ */
58      /**
59       * Get the workname. If set, the workername is dot appended to the session
60       * ID and can be used to assist session affinity in a load balancer.
61       * 
62       * @return String or null
63       */
64      public String getWorkerName()
65      {
66          return _workerName;
67      }
68  
69      /* ------------------------------------------------------------ */
70      /**
71       * Set the workname. If set, the workername is dot appended to the session
72       * ID and can be used to assist session affinity in a load balancer.
73       * 
74       * @param workerName
75       */
76      public void setWorkerName(String workerName)
77      {
78          _workerName=workerName;
79      }
80  
81      /* ------------------------------------------------------------ */
82      /** Get the session ID with any worker ID.
83       * 
84       * @param request
85       * @return sessionId plus any worker ID.
86       */
87      public String getNodeId(String clusterId,HttpServletRequest request) 
88      {
89          String worker=request==null?null:(String)request.getAttribute("org.mortbay.http.ajp.JVMRoute");
90          if (worker!=null) 
91              return clusterId+'.'+worker; 
92          
93          if (_workerName!=null) 
94              return clusterId+'.'+_workerName;
95         
96          return clusterId;
97      }
98  
99      /* ------------------------------------------------------------ */
100     /** Get the session ID without any worker ID.
101      * 
102      * @param request
103      * @return sessionId without any worker ID.
104      */
105     public String getClusterId(String nodeId) 
106     {
107         int dot=nodeId.lastIndexOf('.');
108         return (dot>0)?nodeId.substring(0,dot):nodeId;
109     }
110     
111     /* ------------------------------------------------------------ */
112     protected void doStart()
113     {
114         if (_random==null)
115         {      
116             try 
117             {
118                 _random=SecureRandom.getInstance(SESSION_ID_RANDOM_ALGORITHM);
119             }
120             catch (NoSuchAlgorithmException e)
121             {
122                 try
123                 {
124                     _random=SecureRandom.getInstance(SESSION_ID_RANDOM_ALGORITHM_ALT);
125                     _weakRandom=false;
126                 }
127                 catch (NoSuchAlgorithmException e_alt)
128                 {
129                     Log.warn("Could not generate SecureRandom for session-id randomness",e);
130                     _random=new Random();
131                     _weakRandom=true;
132                 }
133             }
134         }
135         _random.setSeed(_random.nextLong()^System.currentTimeMillis()^hashCode()^Runtime.getRuntime().freeMemory());
136         _sessions=new MultiMap<String>(true);
137     }
138 
139     /* ------------------------------------------------------------ */
140     protected void doStop()
141     {
142         if (_sessions!=null)
143             _sessions.clear(); // Maybe invalidate?
144         _sessions=null;
145     }
146 
147     /* ------------------------------------------------------------ */
148     /*
149      * @see org.mortbay.jetty.SessionManager.MetaManager#idInUse(java.lang.String)
150      */
151     public boolean idInUse(String id)
152     {
153         return _sessions.containsKey(id);
154     }
155 
156     /* ------------------------------------------------------------ */
157     /*
158      * @see org.mortbay.jetty.SessionManager.MetaManager#addSession(javax.servlet.http.HttpSession)
159      */
160     public void addSession(HttpSession session)
161     {
162         _sessions.add(getClusterId(session.getId()),session);
163     }
164 
165     /* ------------------------------------------------------------ */
166     /*
167      * @see org.mortbay.jetty.SessionManager.MetaManager#addSession(javax.servlet.http.HttpSession)
168      */
169     public void removeSession(HttpSession session)
170     {
171         _sessions.removeValue(getClusterId(session.getId()),session);
172     }
173 
174     /* ------------------------------------------------------------ */
175     /*
176      * @see org.mortbay.jetty.SessionManager.MetaManager#invalidateAll(java.lang.String)
177      */
178     public void invalidateAll(String id)
179     {
180 	// Do not use interators as this method tends to be called recursively 
181 	// by the invalidate calls.
182 	while (_sessions.containsKey(id))
183 	{
184 	    Session session=(Session)_sessions.getValue(id,0);
185 	    if (session.isValid())
186 		session.invalidate();
187 	    else
188 		_sessions.removeValue(id,session);
189 	}
190     }
191 
192     /* ------------------------------------------------------------ */
193     /*
194      * new Session ID. If the request has a requestedSessionID which is unique,
195      * that is used. The session ID is created as a unique random long XORed with
196      * connection specific information, base 36.
197      * @param request 
198      * @param created 
199      * @return Session ID.
200      */
201     public String newSessionId(HttpServletRequest request, long created)
202     {
203         synchronized (this)
204         {
205             // A requested session ID can only be used if it is in use already.
206             String requested_id=request.getRequestedSessionId();
207 
208             if (requested_id!=null)
209             {
210                 String cluster_id=getClusterId(requested_id);
211                 if (idInUse(cluster_id))
212                     return cluster_id;
213             }
214 
215             // Else reuse any new session ID already defined for this request.
216             String new_id=(String)request.getAttribute(__NEW_SESSION_ID);
217             if (new_id!=null&&idInUse(new_id))
218                 return new_id;
219 
220             // pick a new unique ID!
221             String id=null;
222             while (id==null||id.length()==0||idInUse(id))
223             {
224                 long r=_weakRandom
225                 ?(hashCode()^Runtime.getRuntime().freeMemory()^_random.nextInt()^(((long)request.hashCode())<<32))
226                 :_random.nextLong();
227                 r^=created;
228                 if (request!=null && request.getRemoteAddr()!=null)
229                     r^=request.getRemoteAddr().hashCode();
230                 if (r<0)
231                     r=-r;
232                 id=Long.toString(r,36);
233             }
234 
235             request.setAttribute(__NEW_SESSION_ID,id);
236             return id;
237         }
238     }
239 
240     /* ------------------------------------------------------------ */
241     public Random getRandom()
242     {
243         return _random;
244     }
245 
246     /* ------------------------------------------------------------ */
247     public void setRandom(Random random)
248     {
249         _random=random;
250         _weakRandom=false;
251     }
252 
253 }