View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2013 Mort Bay Consulting Pty. Ltd.
4   //  ------------------------------------------------------------------------
5   //  All rights reserved. This program and the accompanying materials
6   //  are made available under the terms of the Eclipse Public License v1.0
7   //  and Apache License v2.0 which accompanies this distribution.
8   //
9   //      The Eclipse Public License is available at
10  //      http://www.eclipse.org/legal/epl-v10.html
11  //
12  //      The Apache License v2.0 is available at
13  //      http://www.opensource.org/licenses/apache2.0.php
14  //
15  //  You may elect to redistribute this code under either of these licenses.
16  //  ========================================================================
17  //
18  
19  package org.eclipse.jetty.server.session;
20  
21  import java.security.SecureRandom;
22  import java.util.Random;
23  
24  import javax.servlet.http.HttpServletRequest;
25  
26  import org.eclipse.jetty.server.SessionIdManager;
27  import org.eclipse.jetty.util.component.AbstractLifeCycle;
28  import org.eclipse.jetty.util.log.Log;
29  import org.eclipse.jetty.util.log.Logger;
30  
31  public abstract class AbstractSessionIdManager extends AbstractLifeCycle implements SessionIdManager
32  {
33      private static final Logger LOG = Log.getLogger(AbstractSessionIdManager.class);
34  
35      private final static String __NEW_SESSION_ID="org.eclipse.jetty.server.newSessionId";
36  
37      protected Random _random;
38      protected boolean _weakRandom;
39      protected String _workerName;
40      protected long _reseed=100000L;
41  
42      /* ------------------------------------------------------------ */
43      public AbstractSessionIdManager()
44      {
45      }
46  
47      /* ------------------------------------------------------------ */
48      public AbstractSessionIdManager(Random random)
49      {
50          _random=random;
51      }
52  
53  
54      /* ------------------------------------------------------------ */
55      /**
56       * Get the workname. If set, the workername is dot appended to the session
57       * ID and can be used to assist session affinity in a load balancer.
58       *
59       * @return String or null
60       */
61      public String getWorkerName()
62      {
63          return _workerName;
64      }
65  
66      /* ------------------------------------------------------------ */
67      /**
68       * Set the workname. If set, the workername is dot appended to the session
69       * ID and can be used to assist session affinity in a load balancer.
70       *
71       * @param workerName
72       */
73      public void setWorkerName(String workerName)
74      {
75          if (workerName.contains("."))
76              throw new IllegalArgumentException("Name cannot contain '.'");
77          _workerName=workerName;
78      }
79  
80      /* ------------------------------------------------------------ */
81      public Random getRandom()
82      {
83          return _random;
84      }
85  
86      /* ------------------------------------------------------------ */
87      public synchronized void setRandom(Random random)
88      {
89          _random=random;
90          _weakRandom=false;
91      }
92  
93      /* ------------------------------------------------------------ */
94      /**
95       * @return the reseed probability
96       */
97      public long getReseed()
98      {
99          return _reseed;
100     }
101 
102     /* ------------------------------------------------------------ */
103     /** Set the reseed probability.
104      * @param reseed  If non zero then when a random long modulo the reseed value == 1, the {@link SecureRandom} will be reseeded.
105      */
106     public void setReseed(long reseed)
107     {
108         _reseed = reseed;
109     }
110 
111     /* ------------------------------------------------------------ */
112     /**
113      * Create a new session id if necessary.
114      *
115      * @see org.eclipse.jetty.server.SessionIdManager#newSessionId(javax.servlet.http.HttpServletRequest, long)
116      */
117     public String newSessionId(HttpServletRequest request, long created)
118     {
119         synchronized (this)
120         {
121             if (request!=null)
122             {
123                 // A requested session ID can only be used if it is in use already.
124                 String requested_id=request.getRequestedSessionId();
125                 if (requested_id!=null)
126                 {
127                     String cluster_id=getClusterId(requested_id);
128                     if (idInUse(cluster_id))
129                         return cluster_id;
130                 }
131 
132                 // Else reuse any new session ID already defined for this request.
133                 String new_id=(String)request.getAttribute(__NEW_SESSION_ID);
134                 if (new_id!=null&&idInUse(new_id))
135                     return new_id;
136             }
137 
138             // pick a new unique ID!
139             String id = newSessionId(request.hashCode());
140 
141             request.setAttribute(__NEW_SESSION_ID,id);
142             return id;
143         }
144     }
145 
146     /* ------------------------------------------------------------ */
147     public String newSessionId(long seedTerm)
148     {
149         // pick a new unique ID!
150         String id=null;
151         while (id==null||id.length()==0||idInUse(id))
152         {
153             long r0=_weakRandom
154                     ?(hashCode()^Runtime.getRuntime().freeMemory()^_random.nextInt()^((seedTerm)<<32))
155                     :_random.nextLong();
156             if (r0<0)
157                 r0=-r0;
158                     
159             // random chance to reseed
160             if (_reseed>0 && (r0%_reseed)== 1L)
161             {
162                 LOG.debug("Reseeding {}",this);
163                 if (_random instanceof SecureRandom)
164                 {
165                     SecureRandom secure = (SecureRandom)_random;
166                     secure.setSeed(secure.generateSeed(8));
167                 }
168                 else
169                 {
170                     _random.setSeed(_random.nextLong()^System.currentTimeMillis()^seedTerm^Runtime.getRuntime().freeMemory());
171                 }
172             }
173             
174             long r1=_weakRandom
175                 ?(hashCode()^Runtime.getRuntime().freeMemory()^_random.nextInt()^((seedTerm)<<32))
176                 :_random.nextLong();
177             if (r1<0)
178                 r1=-r1;
179             
180             id=Long.toString(r0,36)+Long.toString(r1,36);
181 
182             //add in the id of the node to ensure unique id across cluster
183             //NOTE this is different to the node suffix which denotes which node the request was received on
184             if (_workerName!=null)
185                 id=_workerName + id;
186     
187         }
188         return id;
189     }
190 
191 
192     /* ------------------------------------------------------------ */
193     public abstract void renewSessionId(String oldClusterId, String oldNodeId, HttpServletRequest request);
194 
195 
196     
197     /* ------------------------------------------------------------ */
198     @Override
199     protected void doStart() throws Exception
200     {
201        initRandom();
202     }
203 
204     /* ------------------------------------------------------------ */
205     @Override
206     protected void doStop() throws Exception
207     {
208     }
209 
210     /* ------------------------------------------------------------ */
211     /**
212      * Set up a random number generator for the sessionids.
213      *
214      * By preference, use a SecureRandom but allow to be injected.
215      */
216     public void initRandom ()
217     {
218         if (_random==null)
219         {
220             try
221             {
222                 _random=new SecureRandom();
223             }
224             catch (Exception e)
225             {
226                 LOG.warn("Could not generate SecureRandom for session-id randomness",e);
227                 _random=new Random();
228                 _weakRandom=true;
229             }
230         }
231         else
232             _random.setSeed(_random.nextLong()^System.currentTimeMillis()^hashCode()^Runtime.getRuntime().freeMemory());
233     }
234 
235 
236 }