1 /*
   2  * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package sun.security.ssl;
  27 
  28 import java.util.ArrayList;
  29 import java.util.Collections;
  30 import java.util.Enumeration;
  31 import java.util.Locale;
  32 import javax.net.ssl.SSLSession;
  33 import javax.net.ssl.SSLSessionContext;
  34 
  35 import sun.security.action.GetIntegerAction;
  36 import sun.security.util.Cache;
  37 
  38 
  39 final class SSLSessionContextImpl implements SSLSessionContext {
  40     private final static int DEFAULT_MAX_CACHE_SIZE = 20480;
  41 
  42     private final Cache<SessionId, SSLSessionImpl> sessionCache;
  43                                         // session cache, session id as key
  44     private final Cache<String, SSLSessionImpl> sessionHostPortCache;
  45                                         // session cache, "host:port" as key
  46     private int cacheLimit;             // the max cache size
  47     private int timeout;                // timeout in seconds
  48 
  49     // package private
  50     SSLSessionContextImpl() {
  51         cacheLimit = getDefaultCacheLimit();    // default cache size
  52         timeout = 86400;                        // default, 24 hours
  53 
  54         // use soft reference
  55         sessionCache = Cache.newSoftMemoryCache(cacheLimit, timeout);
  56         sessionHostPortCache = Cache.newSoftMemoryCache(cacheLimit, timeout);
  57     }
  58 
  59     /**
  60      * Returns the <code>SSLSession</code> bound to the specified session id.
  61      */
  62     @Override
  63     public SSLSession getSession(byte[] sessionId) {
  64         if (sessionId == null) {
  65             throw new NullPointerException("session id cannot be null");
  66         }
  67 
  68         SSLSessionImpl sess = sessionCache.get(new SessionId(sessionId));
  69         if (!isTimedout(sess)) {
  70             return sess;
  71         }
  72 
  73         return null;
  74     }
  75 
  76     /**
  77      * Returns an enumeration of the active SSL sessions.
  78      */
  79     @Override
  80     public Enumeration<byte[]> getIds() {
  81         SessionCacheVisitor scVisitor = new SessionCacheVisitor();
  82         sessionCache.accept(scVisitor);
  83 
  84         return scVisitor.getSessionIds();
  85     }
  86 
  87     /**
  88      * Sets the timeout limit for cached <code>SSLSession</code> objects
  89      *
  90      * Note that after reset the timeout, the cached session before
  91      * should be timed within the shorter one of the old timeout and the
  92      * new timeout.
  93      */
  94     @Override
  95     public void setSessionTimeout(int seconds)
  96                  throws IllegalArgumentException {
  97         if (seconds < 0) {
  98             throw new IllegalArgumentException();
  99         }
 100 
 101         if (timeout != seconds) {
 102             sessionCache.setTimeout(seconds);
 103             sessionHostPortCache.setTimeout(seconds);
 104             timeout = seconds;
 105         }
 106     }
 107 
 108     /**
 109      * Gets the timeout limit for cached <code>SSLSession</code> objects
 110      */
 111     @Override
 112     public int getSessionTimeout() {
 113         return timeout;
 114     }
 115 
 116     /**
 117      * Sets the size of the cache used for storing
 118      * <code>SSLSession</code> objects.
 119      */
 120     @Override
 121     public void setSessionCacheSize(int size)
 122                  throws IllegalArgumentException {
 123         if (size < 0)
 124             throw new IllegalArgumentException();
 125 
 126         if (cacheLimit != size) {
 127             sessionCache.setCapacity(size);
 128             sessionHostPortCache.setCapacity(size);
 129             cacheLimit = size;
 130         }
 131     }
 132 
 133     /**
 134      * Gets the size of the cache used for storing
 135      * <code>SSLSession</code> objects.
 136      */
 137     @Override
 138     public int getSessionCacheSize() {
 139         return cacheLimit;
 140     }
 141 
 142     // package-private method, used ONLY by ServerHandshaker
 143     SSLSessionImpl get(byte[] id) {
 144         return (SSLSessionImpl)getSession(id);
 145     }
 146 
 147     // package-private method, used ONLY by ClientHandshaker
 148     SSLSessionImpl get(String hostname, int port) {
 149         /*
 150          * If no session caching info is available, we won't
 151          * get one, so exit before doing a lookup.
 152          */
 153         if (hostname == null && port == -1) {
 154             return null;
 155         }
 156 
 157         SSLSessionImpl sess = sessionHostPortCache.get(getKey(hostname, port));
 158         if (!isTimedout(sess)) {
 159             return sess;
 160         }
 161 
 162         return null;
 163     }
 164 
 165     private static String getKey(String hostname, int port) {
 166         return (hostname + ":" +
 167             String.valueOf(port)).toLowerCase(Locale.ENGLISH);
 168     }
 169 
 170     // cache a SSLSession
 171     //
 172     // In SunJSSE implementation, a session is created while getting a
 173     // client hello or a server hello message, and cached while the
 174     // handshaking finished.
 175     // Here we time the session from the time it cached instead of the
 176     // time it created, which is a little longer than the expected. So
 177     // please do check isTimedout() while getting entry from the cache.
 178     void put(SSLSessionImpl s) {
 179         sessionCache.put(s.getSessionId(), s);
 180 
 181         // If no hostname/port info is available, don't add this one.
 182         if ((s.getPeerHost() != null) && (s.getPeerPort() != -1)) {
 183             sessionHostPortCache.put(
 184                 getKey(s.getPeerHost(), s.getPeerPort()), s);
 185         }
 186 
 187         s.setContext(this);
 188     }
 189 
 190     // package-private method, remove a cached SSLSession
 191     void remove(SessionId key) {
 192         SSLSessionImpl s = sessionCache.get(key);
 193         if (s != null) {
 194             sessionCache.remove(key);
 195             sessionHostPortCache.remove(
 196                     getKey(s.getPeerHost(), s.getPeerPort()));
 197         }
 198     }
 199 
 200     private static int getDefaultCacheLimit() {
 201         try {
 202             int defaultCacheLimit = GetIntegerAction.privilegedGetProperty(
 203                     "javax.net.ssl.sessionCacheSize", DEFAULT_MAX_CACHE_SIZE);
 204 
 205             if (defaultCacheLimit >= 0) {
 206                 return defaultCacheLimit;
 207             } else if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
 208                 SSLLogger.warning(
 209                     "invalid System Property javax.net.ssl.sessionCacheSize, " +
 210                     "use the default session cache size (" +
 211                     DEFAULT_MAX_CACHE_SIZE + ") instead");
 212             }
 213         } catch (Exception e) {
 214             // unlikely, log it for safe
 215             if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
 216                 SSLLogger.warning(
 217                     "the System Property javax.net.ssl.sessionCacheSize is " +
 218                     "not available, use the default value (" +
 219                     DEFAULT_MAX_CACHE_SIZE + ") instead");
 220             }
 221         }
 222 
 223         return DEFAULT_MAX_CACHE_SIZE;
 224     }
 225 
 226     private boolean isTimedout(SSLSession sess) {
 227         if (timeout == 0) {
 228             return false;
 229         }
 230 
 231         if ((sess != null) && ((sess.getCreationTime() + timeout * 1000L)
 232                                         <= (System.currentTimeMillis()))) {
 233             sess.invalidate();
 234             return true;
 235         }
 236 
 237         return false;
 238     }
 239 
 240     private final class SessionCacheVisitor
 241             implements Cache.CacheVisitor<SessionId, SSLSessionImpl> {
 242         ArrayList<byte[]> ids = null;
 243 
 244         // public void visit(java.util.Map<K,V> map) {}
 245         @Override
 246         public void visit(java.util.Map<SessionId, SSLSessionImpl> map) {
 247             ids = new ArrayList<>(map.size());
 248 
 249             for (SessionId key : map.keySet()) {
 250                 SSLSessionImpl value = map.get(key);
 251                 if (!isTimedout(value)) {
 252                     ids.add(key.getId());
 253                 }
 254             }
 255         }
 256 
 257         Enumeration<byte[]> getSessionIds() {
 258             return  ids != null ? Collections.enumeration(ids) :
 259                                   Collections.emptyEnumeration();
 260         }
 261     }
 262 }