Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/sun/security/pkcs11/SessionManager.java
38919 views
/*1* Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.security.pkcs11;2627import java.util.*;2829import java.security.ProviderException;3031import sun.security.util.Debug;3233import sun.security.pkcs11.wrapper.*;34import static sun.security.pkcs11.wrapper.PKCS11Constants.*;3536import java.util.concurrent.ConcurrentLinkedDeque;37import java.util.concurrent.atomic.AtomicInteger;3839/**40* Session manager. There is one session manager object per PKCS#1141* provider. It allows code to checkout a session, release it42* back to the pool, or force it to be closed.43*44* The session manager pools sessions to minimize the number of45* C_OpenSession() and C_CloseSession() that have to be made. It46* maintains two pools: one for "object" sessions and one for47* "operation" sessions.48*49* The reason for this separation is how PKCS#11 deals with session objects.50* It defines that when a session is closed, all objects created within51* that session are destroyed. In other words, we may never close a session52* while a Key created it in is still in use. We would like to keep the53* number of such sessions low. Note that we occasionally want to explicitly54* close a session, see P11Signature.55*56* NOTE that sessions obtained from this class SHOULD be returned using57* either releaseSession() or closeSession() using a finally block when58* not needed anymore. Otherwise, they will be left for cleanup via the59* PhantomReference mechanism when GC kicks in, but it's best not to rely60* on that since GC may not run timely enough since the native PKCS11 library61* is also consuming memory.62*63* Note that sessions are automatically closed when they are not used for a64* period of time, see Session.65*66* @author Andreas Sterbenz67* @since 1.568*/69final class SessionManager {7071private final static int DEFAULT_MAX_SESSIONS = 32;7273private final static Debug debug = Debug.getInstance("pkcs11");7475// token instance76private final Token token;7778// maximum number of sessions to open with this token79private final int maxSessions;8081// total number of active sessions82private AtomicInteger activeSessions = new AtomicInteger();8384// pool of available object sessions85private final Pool objSessions;8687// pool of available operation sessions88private final Pool opSessions;8990// maximum number of active sessions during this invocation, for debugging91private int maxActiveSessions;92private Object maxActiveSessionsLock;9394// flags to use in the C_OpenSession() call95private final long openSessionFlags;9697SessionManager(Token token) {98long n;99if (token.isWriteProtected()) {100openSessionFlags = CKF_SERIAL_SESSION;101n = token.tokenInfo.ulMaxSessionCount;102} else {103openSessionFlags = CKF_SERIAL_SESSION | CKF_RW_SESSION;104n = token.tokenInfo.ulMaxRwSessionCount;105}106if (n == CK_EFFECTIVELY_INFINITE) {107n = Integer.MAX_VALUE;108} else if ((n == CK_UNAVAILABLE_INFORMATION) || (n < 0)) {109// choose an arbitrary concrete value110n = DEFAULT_MAX_SESSIONS;111}112maxSessions = (int)Math.min(n, Integer.MAX_VALUE);113this.token = token;114this.objSessions = new Pool(this);115this.opSessions = new Pool(this);116if (debug != null) {117maxActiveSessionsLock = new Object();118}119}120121// returns whether only a fairly low number of sessions are122// supported by this token.123boolean lowMaxSessions() {124return (maxSessions <= DEFAULT_MAX_SESSIONS);125}126127Session getObjSession() throws PKCS11Exception {128Session session = objSessions.poll();129if (session != null) {130return ensureValid(session);131}132session = opSessions.poll();133if (session != null) {134return ensureValid(session);135}136session = openSession();137return ensureValid(session);138}139140Session getOpSession() throws PKCS11Exception {141Session session = opSessions.poll();142if (session != null) {143return ensureValid(session);144}145// create a new session rather than re-using an obj session146// that avoids potential expensive cancels() for Signatures & RSACipher147if (maxSessions == Integer.MAX_VALUE ||148activeSessions.get() < maxSessions) {149session = openSession();150return ensureValid(session);151}152session = objSessions.poll();153if (session != null) {154return ensureValid(session);155}156throw new ProviderException("Could not obtain session");157}158159private Session ensureValid(Session session) {160session.id();161return session;162}163164Session killSession(Session session) {165if ((session == null) || (token.isValid() == false)) {166return null;167}168if (debug != null) {169String location = new Exception().getStackTrace()[2].toString();170System.out.println("Killing session (" + location + ") active: "171+ activeSessions.get());172}173closeSession(session);174return null;175}176177Session releaseSession(Session session) {178if ((session == null) || (token.isValid() == false)) {179return null;180}181182if (session.hasObjects()) {183objSessions.release(session);184} else {185opSessions.release(session);186}187return null;188}189190void demoteObjSession(Session session) {191if (token.isValid() == false) {192return;193}194if (debug != null) {195System.out.println("Demoting session, active: " +196activeSessions.get());197}198boolean present = objSessions.remove(session);199if (present == false) {200// session is currently in use201// will be added to correct pool on release, nothing to do now202return;203}204opSessions.release(session);205}206207private Session openSession() throws PKCS11Exception {208if ((maxSessions != Integer.MAX_VALUE) &&209(activeSessions.get() >= maxSessions)) {210throw new ProviderException("No more sessions available");211}212213long id = token.p11.C_OpenSession214(token.provider.slotID, openSessionFlags, null, null);215Session session = new Session(token, id);216activeSessions.incrementAndGet();217if (debug != null) {218synchronized(maxActiveSessionsLock) {219if (activeSessions.get() > maxActiveSessions) {220maxActiveSessions = activeSessions.get();221if (maxActiveSessions % 10 == 0) {222System.out.println("Open sessions: " + maxActiveSessions);223}224}225}226}227return session;228}229230private void closeSession(Session session) {231session.close();232activeSessions.decrementAndGet();233}234235public static final class Pool {236237private final SessionManager mgr;238239private final ConcurrentLinkedDeque<Session> pool;240241Pool(SessionManager mgr) {242this.mgr = mgr;243pool = new ConcurrentLinkedDeque<Session>();244}245246boolean remove(Session session) {247return pool.remove(session);248}249250Session poll() {251return pool.pollLast();252}253254void release(Session session) {255pool.offer(session);256if (session.hasObjects()) {257return;258}259260int n = pool.size();261if (n < 5) {262return;263}264265Session oldestSession;266long time = System.currentTimeMillis();267int i = 0;268// Check if the session head is too old and continue through queue269// until only one is left.270do {271oldestSession = pool.peek();272if (oldestSession == null || oldestSession.isLive(time) ||273!pool.remove(oldestSession)) {274break;275}276277i++;278mgr.closeSession(oldestSession);279} while ((n - i) > 1);280281if (debug != null) {282System.out.println("Closing " + i + " idle sessions, active: "283+ mgr.activeSessions);284}285}286287}288289}290291292