SSLSessionContextImpl.java 8.1 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */


package sun.security.ssl;

import java.io.*;
import java.net.*;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.NoSuchElementException;
import java.util.Vector;

import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSessionContext;
import javax.net.ssl.SSLSessionBindingListener;
import javax.net.ssl.SSLSessionBindingEvent;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;

44
import sun.security.util.Cache;
D
duke 已提交
45 46


47 48 49 50 51 52
final class SSLSessionContextImpl implements SSLSessionContext {
    private Cache sessionCache;         // session cache, session id as key
    private Cache sessionHostPortCache; // session cache, "host:port" as key
    private int cacheLimit;             // the max cache size
    private int timeout;                // timeout in seconds

D
duke 已提交
53 54
    private static final Debug debug = Debug.getInstance("ssl");

55 56 57 58 59 60 61 62
    // package private
    SSLSessionContextImpl() {
        cacheLimit = getDefaultCacheLimit();    // default cache size
        timeout = 86400;                        // default, 24 hours

        // use soft reference
        sessionCache = Cache.newSoftMemoryCache(cacheLimit, timeout);
        sessionHostPortCache = Cache.newSoftMemoryCache(cacheLimit, timeout);
D
duke 已提交
63 64 65
    }

    /**
66
     * Returns the <code>SSLSession</code> bound to the specified session id.
D
duke 已提交
67
     */
68 69 70 71 72 73 74 75 76 77 78 79
    public SSLSession getSession(byte[] sessionId) {
        if (sessionId == null) {
            throw new NullPointerException("session id cannot be null");
        }

        SSLSessionImpl sess =
                (SSLSessionImpl)sessionCache.get(new SessionId(sessionId));
        if (!isTimedout(sess)) {
            return sess;
        }

        return null;
D
duke 已提交
80 81 82 83 84 85
    }

    /**
     * Returns an enumeration of the active SSL sessions.
     */
    public Enumeration<byte[]> getIds() {
86 87
        SessionCacheVisitor scVisitor = new SessionCacheVisitor();
        sessionCache.accept(scVisitor);
D
duke 已提交
88

89
        return scVisitor.getSessionIds();
D
duke 已提交
90 91
    }

92 93 94 95 96 97 98
    /**
     * Sets the timeout limit for cached <code>SSLSession</code> objects
     *
     * Note that after reset the timeout, the cached session before
     * should be timed within the shorter one of the old timeout and the
     * new timeout.
     */
D
duke 已提交
99 100
    public void setSessionTimeout(int seconds)
                 throws IllegalArgumentException {
101
        if (seconds < 0) {
D
duke 已提交
102
            throw new IllegalArgumentException();
103 104 105 106 107 108 109
        }

        if (timeout != seconds) {
            sessionCache.setTimeout(seconds);
            sessionHostPortCache.setTimeout(seconds);
            timeout = seconds;
        }
D
duke 已提交
110 111
    }

112 113 114
    /**
     * Gets the timeout limit for cached <code>SSLSession</code> objects
     */
D
duke 已提交
115
    public int getSessionTimeout() {
116
        return timeout;
D
duke 已提交
117 118
    }

119 120 121 122
    /**
     * Sets the size of the cache used for storing
     * <code>SSLSession</code> objects.
     */
D
duke 已提交
123 124 125 126 127
    public void setSessionCacheSize(int size)
                 throws IllegalArgumentException {
        if (size < 0)
            throw new IllegalArgumentException();

128 129 130 131 132
        if (cacheLimit != size) {
            sessionCache.setCapacity(size);
            sessionHostPortCache.setCapacity(size);
            cacheLimit = size;
        }
D
duke 已提交
133 134
    }

135 136 137 138
    /**
     * Gets the size of the cache used for storing
     * <code>SSLSession</code> objects.
     */
D
duke 已提交
139 140 141 142
    public int getSessionCacheSize() {
        return cacheLimit;
    }

143 144

    // package-private method, used ONLY by ServerHandshaker
D
duke 已提交
145
    SSLSessionImpl get(byte[] id) {
146
        return (SSLSessionImpl)getSession(id);
D
duke 已提交
147 148
    }

149
    // package-private method, used ONLY by ClientHandshaker
D
duke 已提交
150 151 152 153 154 155 156 157
    SSLSessionImpl get(String hostname, int port) {
        /*
         * If no session caching info is available, we won't
         * get one, so exit before doing a lookup.
         */
        if (hostname == null && port == -1) {
            return null;
        }
158 159 160 161 162 163 164 165

        SSLSessionImpl sess =
            (SSLSessionImpl)sessionHostPortCache.get(getKey(hostname, port));
        if (!isTimedout(sess)) {
            return sess;
        }

        return null;
D
duke 已提交
166 167 168
    }

    private String getKey(String hostname, int port) {
169
        return (hostname + ":" + String.valueOf(port)).toLowerCase();
D
duke 已提交
170 171
    }

172 173 174 175 176 177 178 179
    // cache a SSLSession
    //
    // In SunJSSE implementation, a session is created while getting a
    // client hello or a server hello message, and cached while the
    // handshaking finished.
    // Here we time the session from the time it cached instead of the
    // time it created, which is a little longer than the expected. So
    // please do check isTimedout() while getting entry from the cache.
D
duke 已提交
180 181 182
    void put(SSLSessionImpl s) {
        sessionCache.put(s.getSessionId(), s);

183
        // If no hostname/port info is available, don't add this one.
D
duke 已提交
184 185 186 187
        if ((s.getPeerHost() != null) && (s.getPeerPort() != -1)) {
            sessionHostPortCache.put(
                getKey(s.getPeerHost(), s.getPeerPort()), s);
        }
188

D
duke 已提交
189 190 191
        s.setContext(this);
    }

192 193 194 195 196 197 198
    // package-private method, remove a cached SSLSession
    void remove(SessionId key) {
        SSLSessionImpl s = (SSLSessionImpl)sessionCache.get(key);
        if (s != null) {
            sessionCache.remove(key);
            sessionHostPortCache.remove(
                        getKey(s.getPeerHost(), s.getPeerPort()));
D
duke 已提交
199 200 201
        }
    }

202
    private int getDefaultCacheLimit() {
D
duke 已提交
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
        int cacheLimit = 0;
        try {
        String s = java.security.AccessController.doPrivileged(
                new java.security.PrivilegedAction<String>() {
                public String run() {
                    return System.getProperty(
                        "javax.net.ssl.sessionCacheSize");
                }
            });
            cacheLimit = (s != null) ? Integer.valueOf(s).intValue() : 0;
        } catch (Exception e) {
        }

        return (cacheLimit > 0) ? cacheLimit : 0;
    }

    boolean isTimedout(SSLSession sess) {
220
        if (timeout == 0) {
D
duke 已提交
221
            return false;
222 223 224 225 226
        }

        if ((sess != null) && ((sess.getCreationTime() + timeout * 1000L)
                                        <= (System.currentTimeMillis()))) {
            sess.invalidate();
D
duke 已提交
227
            return true;
228 229
        }

D
duke 已提交
230 231
        return false;
    }
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254

    final class SessionCacheVisitor
            implements sun.security.util.Cache.CacheVisitor {
        Vector<byte[]> ids = null;

        // public void visit(java.util.Map<Object, Object> map) {}
        public void visit(java.util.Map<Object, Object> map) {
            ids = new Vector<byte[]>(map.size());

            for (Object key : map.keySet()) {
                SSLSessionImpl value = (SSLSessionImpl)map.get(key);
                if (!isTimedout(value)) {
                    ids.addElement(((SessionId)key).getId());
                }
            }
        }

        public Enumeration<byte[]> getSessionIds() {
            return  ids != null ? ids.elements() :
                                  new Vector<byte[]>().elements();
        }
    }

D
duke 已提交
255
}