8221882: Use fiber-friendly java.util.concurrent.locks in JSSE

Reviewed-by: alanb, dfuchs
This commit is contained in:
Xue-Lei Andrew Fan 2019-04-05 11:28:23 -07:00
parent 6d617481d4
commit 8263b618ba
22 changed files with 1672 additions and 1020 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -26,8 +26,9 @@
package javax.net.ssl;
import java.security.*;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.util.Objects;
import sun.security.jca.GetInstance;
/**
@ -58,6 +59,20 @@ public class SSLContext {
private final String protocol;
private static volatile SSLContext defaultContext;
private static final VarHandle VH_DEFAULT_CONTEXT;
static {
try {
VH_DEFAULT_CONTEXT = MethodHandles.lookup()
.findStaticVarHandle(
SSLContext.class, "defaultContext", SSLContext.class);
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
/**
* Creates an SSLContext object.
*
@ -72,8 +87,6 @@ public class SSLContext {
this.protocol = protocol;
}
private static SSLContext defaultContext;
/**
* Returns the default SSL context.
*
@ -91,12 +104,16 @@ public class SSLContext {
* {@link SSLContext#getInstance SSLContext.getInstance()} call fails
* @since 1.6
*/
public static synchronized SSLContext getDefault()
throws NoSuchAlgorithmException {
if (defaultContext == null) {
defaultContext = SSLContext.getInstance("Default");
public static SSLContext getDefault() throws NoSuchAlgorithmException {
SSLContext temporaryContext = defaultContext;
if (temporaryContext == null) {
temporaryContext = SSLContext.getInstance("Default");
if (!VH_DEFAULT_CONTEXT.compareAndSet(null, temporaryContext)) {
temporaryContext = defaultContext;
}
return defaultContext;
}
return temporaryContext;
}
/**
@ -111,7 +128,7 @@ public class SSLContext {
* {@code SSLPermission("setDefaultSSLContext")}
* @since 1.6
*/
public static synchronized void setDefault(SSLContext context) {
public static void setDefault(SSLContext context) {
if (context == null) {
throw new NullPointerException();
}
@ -119,6 +136,7 @@ public class SSLContext {
if (sm != null) {
sm.checkPermission(new SSLPermission("setDefaultSSLContext"));
}
defaultContext = context;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -42,17 +42,7 @@ import java.security.*;
* @see SSLServerSocket
* @author David Brownell
*/
public abstract class SSLServerSocketFactory extends ServerSocketFactory
{
private static SSLServerSocketFactory theFactory;
private static boolean propertyChecked;
private static void log(String msg) {
if (SSLSocketFactory.DEBUG) {
System.out.println(msg);
}
}
public abstract class SSLServerSocketFactory extends ServerSocketFactory {
/**
* Constructor is used only by subclasses.
@ -75,39 +65,9 @@ public abstract class SSLServerSocketFactory extends ServerSocketFactory
* @return the default <code>ServerSocketFactory</code>
* @see SSLContext#getDefault
*/
public static synchronized ServerSocketFactory getDefault() {
if (theFactory != null) {
return theFactory;
}
if (propertyChecked == false) {
propertyChecked = true;
String clsName = SSLSocketFactory.getSecurityProperty
("ssl.ServerSocketFactory.provider");
if (clsName != null) {
log("setting up default SSLServerSocketFactory");
try {
Class<?> cls = null;
try {
cls = Class.forName(clsName);
} catch (ClassNotFoundException e) {
ClassLoader cl = ClassLoader.getSystemClassLoader();
if (cl != null) {
cls = cl.loadClass(clsName);
}
}
log("class " + clsName + " is loaded");
@SuppressWarnings("deprecation")
SSLServerSocketFactory fac = (SSLServerSocketFactory)cls.newInstance();
log("instantiated an instance of class " + clsName);
theFactory = fac;
return fac;
} catch (Exception e) {
log("SSLServerSocketFactory instantiation failed: " + e);
theFactory = new DefaultSSLServerSocketFactory(e);
return theFactory;
}
}
public static ServerSocketFactory getDefault() {
if (DefaultFactoryHolder.defaultFactory != null) {
return DefaultFactoryHolder.defaultFactory;
}
try {
@ -156,8 +116,50 @@ public abstract class SSLServerSocketFactory extends ServerSocketFactory
* @see #getDefaultCipherSuites()
*/
public abstract String [] getSupportedCipherSuites();
}
// lazy initialization holder class idiom for static default factory
//
// See Effective Java Second Edition: Item 71.
private static final class DefaultFactoryHolder {
private static final SSLServerSocketFactory defaultFactory;
static {
SSLServerSocketFactory mediator = null;
String clsName = SSLSocketFactory.getSecurityProperty(
"ssl.ServerSocketFactory.provider");
if (clsName != null) {
log("setting up default SSLServerSocketFactory");
try {
Class<?> cls = null;
try {
cls = Class.forName(clsName);
} catch (ClassNotFoundException e) {
ClassLoader cl = ClassLoader.getSystemClassLoader();
if (cl != null) {
cls = cl.loadClass(clsName);
}
}
log("class " + clsName + " is loaded");
mediator = (SSLServerSocketFactory)cls
.getDeclaredConstructor().newInstance();
log("instantiated an instance of class " + clsName);
} catch (Exception e) {
log("SSLServerSocketFactory instantiation failed: " + e);
mediator = new DefaultSSLServerSocketFactory(e);
}
}
defaultFactory = mediator;
}
private static void log(String msg) {
if (SSLSocketFactory.DEBUG) {
System.out.println(msg);
}
}
}
}
//
// The default factory does NOTHING.

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -42,31 +42,20 @@ import sun.security.action.GetPropertyAction;
* @see SSLSocket
* @author David Brownell
*/
public abstract class SSLSocketFactory extends SocketFactory
{
private static SSLSocketFactory theFactory;
private static boolean propertyChecked;
public abstract class SSLSocketFactory extends SocketFactory {
static final boolean DEBUG;
static {
String s = GetPropertyAction.privilegedGetProperty("javax.net.debug", "")
.toLowerCase(Locale.ENGLISH);
String s = GetPropertyAction.privilegedGetProperty(
"javax.net.debug", "").toLowerCase(Locale.ENGLISH);
DEBUG = s.contains("all") || s.contains("ssl");
}
private static void log(String msg) {
if (DEBUG) {
System.out.println(msg);
}
}
/**
* Constructor is used only by subclasses.
*/
public SSLSocketFactory() {
// blank
}
/**
@ -85,38 +74,9 @@ public abstract class SSLSocketFactory extends SocketFactory
* @return the default <code>SocketFactory</code>
* @see SSLContext#getDefault
*/
public static synchronized SocketFactory getDefault() {
if (theFactory != null) {
return theFactory;
}
if (propertyChecked == false) {
propertyChecked = true;
String clsName = getSecurityProperty("ssl.SocketFactory.provider");
if (clsName != null) {
log("setting up default SSLSocketFactory");
try {
Class<?> cls = null;
try {
cls = Class.forName(clsName);
} catch (ClassNotFoundException e) {
ClassLoader cl = ClassLoader.getSystemClassLoader();
if (cl != null) {
cls = cl.loadClass(clsName);
}
}
log("class " + clsName + " is loaded");
@SuppressWarnings("deprecation")
SSLSocketFactory fac = (SSLSocketFactory)cls.newInstance();
log("instantiated an instance of class " + clsName);
theFactory = fac;
return fac;
} catch (Exception e) {
log("SSLSocketFactory instantiation failed: " + e.toString());
theFactory = new DefaultSSLSocketFactory(e);
return theFactory;
}
}
public static SocketFactory getDefault() {
if (DefaultFactoryHolder.defaultFactory != null) {
return DefaultFactoryHolder.defaultFactory;
}
try {
@ -246,6 +206,49 @@ public abstract class SSLSocketFactory extends SocketFactory
boolean autoClose) throws IOException {
throw new UnsupportedOperationException();
}
// lazy initialization holder class idiom for static default factory
//
// See Effective Java Second Edition: Item 71.
private static final class DefaultFactoryHolder {
private static final SSLSocketFactory defaultFactory;
static {
SSLSocketFactory mediator = null;
String clsName = getSecurityProperty("ssl.SocketFactory.provider");
if (clsName != null) {
log("setting up default SSLSocketFactory");
try {
Class<?> cls = null;
try {
cls = Class.forName(clsName);
} catch (ClassNotFoundException e) {
ClassLoader cl = ClassLoader.getSystemClassLoader();
if (cl != null) {
cls = cl.loadClass(clsName);
}
}
log("class " + clsName + " is loaded");
mediator = (SSLSocketFactory)cls
.getDeclaredConstructor().newInstance();
log("instantiated an instance of class " + clsName);
} catch (Exception e) {
log("SSLSocketFactory instantiation failed: " + e);
mediator = new DefaultSSLSocketFactory(e);
}
}
defaultFactory = mediator;
}
private static void log(String msg) {
if (DEBUG) {
System.out.println(msg);
}
}
}
}

View File

@ -57,8 +57,7 @@ import sun.net.www.http.HttpClient;
public class HttpsURLConnectionImpl
extends javax.net.ssl.HttpsURLConnection {
// NOTE: made protected for plugin so that subclass can set it.
protected DelegateHttpsURLConnection delegate;
private final DelegateHttpsURLConnection delegate;
HttpsURLConnectionImpl(URL u, Handler handler) throws IOException {
this(u, null, handler);
@ -78,13 +77,6 @@ public class HttpsURLConnectionImpl
delegate = new DelegateHttpsURLConnection(url, p, handler, this);
}
// NOTE: introduced for plugin
// subclass needs to overwrite this to set delegate to
// the appropriate delegatee
protected HttpsURLConnectionImpl(URL u) throws IOException {
super(u);
}
/**
* Create a new HttpClient object, bypassing the cache of
* HTTP client objects/connections.
@ -219,11 +211,11 @@ public class HttpsURLConnectionImpl
* - get input, [read input,] get output, [write output]
*/
public synchronized OutputStream getOutputStream() throws IOException {
public OutputStream getOutputStream() throws IOException {
return delegate.getOutputStream();
}
public synchronized InputStream getInputStream() throws IOException {
public InputStream getInputStream() throws IOException {
return delegate.getInputStream();
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -632,7 +632,7 @@ abstract class BaseSSLSocketImpl extends SSLSocket {
}
@Override
public synchronized void setSoTimeout(int timeout) throws SocketException {
public void setSoTimeout(int timeout) throws SocketException {
if (self == this) {
super.setSoTimeout(timeout);
} else {

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -58,7 +58,7 @@ final class DTLSInputRecord extends InputRecord implements DTLSRecord {
}
@Override
public synchronized void close() throws IOException {
public void close() throws IOException {
if (!isClosed) {
super.close();
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1996, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -58,7 +58,9 @@ final class DTLSOutputRecord extends OutputRecord implements DTLSRecord {
}
@Override
public synchronized void close() throws IOException {
public void close() throws IOException {
recordLock.lock();
try {
if (!isClosed) {
if (fragmenter != null && fragmenter.hasAlert()) {
isCloseWaiting = true;
@ -66,6 +68,9 @@ final class DTLSOutputRecord extends OutputRecord implements DTLSRecord {
super.close();
}
}
} finally {
recordLock.unlock();
}
}
boolean isClosed() {

View File

@ -26,6 +26,7 @@
package sun.security.ssl;
import java.security.*;
import java.util.concurrent.locks.ReentrantLock;
/**
* The "KeyManager" for ephemeral RSA keys. Ephemeral DH and ECDH keys
@ -48,6 +49,8 @@ final class EphemeralKeyManager {
new EphemeralKeyPair(null),
};
private final ReentrantLock cachedKeysLock = new ReentrantLock();
EphemeralKeyManager() {
// empty
}
@ -65,9 +68,19 @@ final class EphemeralKeyManager {
index = INDEX_RSA1024;
}
synchronized (keys) {
KeyPair kp = keys[index].getKeyPair();
if (kp == null) {
if (kp != null) {
return kp;
}
cachedKeysLock.lock();
try {
// double check
kp = keys[index].getKeyPair();
if (kp != null) {
return kp;
}
try {
KeyPairGenerator kgen = KeyPairGenerator.getInstance("RSA");
kgen.initialize(length, random);
@ -76,10 +89,12 @@ final class EphemeralKeyManager {
} catch (Exception e) {
// ignore
}
} finally {
cachedKeysLock.unlock();
}
return kp;
}
}
/**
* Inner class to handle storage of ephemeral KeyPairs.

View File

@ -30,6 +30,7 @@ import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.concurrent.locks.ReentrantLock;
import static sun.security.ssl.ClientHello.ClientHelloMessage;
/**
@ -45,6 +46,8 @@ abstract class HelloCookieManager {
private volatile D13HelloCookieManager d13HelloCookieManager;
private volatile T13HelloCookieManager t13HelloCookieManager;
private final ReentrantLock managerLock = new ReentrantLock();
Builder(SecureRandom secureRandom) {
this.secureRandom = secureRandom;
}
@ -56,11 +59,14 @@ abstract class HelloCookieManager {
return d13HelloCookieManager;
}
synchronized (this) {
managerLock.lock();
try {
if (d13HelloCookieManager == null) {
d13HelloCookieManager =
new D13HelloCookieManager(secureRandom);
}
} finally {
managerLock.unlock();
}
return d13HelloCookieManager;
@ -69,11 +75,14 @@ abstract class HelloCookieManager {
return d10HelloCookieManager;
}
synchronized (this) {
managerLock.lock();
try {
if (d10HelloCookieManager == null) {
d10HelloCookieManager =
new D10HelloCookieManager(secureRandom);
}
} finally {
managerLock.unlock();
}
return d10HelloCookieManager;
@ -84,11 +93,14 @@ abstract class HelloCookieManager {
return t13HelloCookieManager;
}
synchronized (this) {
managerLock.lock();
try {
if (t13HelloCookieManager == null) {
t13HelloCookieManager =
new T13HelloCookieManager(secureRandom);
}
} finally {
managerLock.unlock();
}
return t13HelloCookieManager;
@ -114,6 +126,8 @@ abstract class HelloCookieManager {
private byte[] cookieSecret;
private byte[] legacySecret;
private final ReentrantLock d10ManagerLock = new ReentrantLock();
D10HelloCookieManager(SecureRandom secureRandom) {
this.secureRandom = secureRandom;
@ -131,7 +145,8 @@ abstract class HelloCookieManager {
int version;
byte[] secret;
synchronized (this) {
d10ManagerLock.lock();
try {
version = cookieVersion;
secret = cookieSecret;
@ -142,6 +157,8 @@ abstract class HelloCookieManager {
}
cookieVersion++;
} finally {
d10ManagerLock.unlock();
}
MessageDigest md;
@ -168,12 +185,15 @@ abstract class HelloCookieManager {
}
byte[] secret;
synchronized (this) {
d10ManagerLock.lock();
try {
if (((cookieVersion >> 24) & 0xFF) == cookie[0]) {
secret = cookieSecret;
} else {
secret = legacySecret; // including out of window cookies
}
} finally {
d10ManagerLock.unlock();
}
MessageDigest md;
@ -218,6 +238,8 @@ abstract class HelloCookieManager {
private final byte[] cookieSecret;
private final byte[] legacySecret;
private final ReentrantLock t13ManagerLock = new ReentrantLock();
T13HelloCookieManager(SecureRandom secureRandom) {
this.secureRandom = secureRandom;
this.cookieVersion = secureRandom.nextInt();
@ -234,7 +256,8 @@ abstract class HelloCookieManager {
int version;
byte[] secret;
synchronized (this) {
t13ManagerLock.lock();
try {
version = cookieVersion;
secret = cookieSecret;
@ -245,6 +268,8 @@ abstract class HelloCookieManager {
}
cookieVersion++; // allow wrapped version number
} finally {
t13ManagerLock.unlock();
}
MessageDigest md;
@ -313,12 +338,15 @@ abstract class HelloCookieManager {
Arrays.copyOfRange(cookie, 3 + hashLen, cookie.length);
byte[] secret;
synchronized (this) {
t13ManagerLock.lock();
try {
if ((byte)((cookieVersion >> 24) & 0xFF) == cookie[2]) {
secret = cookieSecret;
} else {
secret = legacySecret; // including out of window cookies
}
} finally {
t13ManagerLock.unlock();
}
MessageDigest md;

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1996, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -31,6 +31,7 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.util.concurrent.locks.ReentrantLock;
import javax.crypto.BadPaddingException;
import sun.security.ssl.SSLCipher.SSLReadCipher;
@ -46,7 +47,7 @@ abstract class InputRecord implements Record, Closeable {
TransportContext tc;
final HandshakeHash handshakeHash;
boolean isClosed;
volatile boolean isClosed;
// The ClientHello version to accept. If set to ProtocolVersion.SSL20Hello
// and the first message we read is a ClientHello in V2 format, we convert
@ -56,6 +57,8 @@ abstract class InputRecord implements Record, Closeable {
// fragment size
int fragmentSize;
final ReentrantLock recordLock = new ReentrantLock();
InputRecord(HandshakeHash handshakeHash, SSLReadCipher readCipher) {
this.readCipher = readCipher;
this.helloVersion = ProtocolVersion.TLS10;
@ -92,14 +95,19 @@ abstract class InputRecord implements Record, Closeable {
* and flag the record as holding no data.
*/
@Override
public synchronized void close() throws IOException {
public void close() throws IOException {
recordLock.lock();
try {
if (!isClosed) {
isClosed = true;
readCipher.dispose();
}
} finally {
recordLock.unlock();
}
}
synchronized boolean isClosed() {
boolean isClosed() {
return isClosed;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1996, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -30,6 +30,7 @@ import java.io.Closeable;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.concurrent.locks.ReentrantLock;
import sun.security.ssl.SSLCipher.SSLWriteCipher;
/**
@ -68,6 +69,8 @@ abstract class OutputRecord
// closed or not?
volatile boolean isClosed;
final ReentrantLock recordLock = new ReentrantLock();
/*
* Mappings from V3 cipher suite encodings to their pure V2 equivalents.
* This is taken from the SSL V3 specification, Appendix E.
@ -89,15 +92,25 @@ abstract class OutputRecord
// Please set packetSize and protocolVersion in the implementation.
}
synchronized void setVersion(ProtocolVersion protocolVersion) {
void setVersion(ProtocolVersion protocolVersion) {
recordLock.lock();
try {
this.protocolVersion = protocolVersion;
} finally {
recordLock.unlock();
}
}
/*
* Updates helloVersion of this record.
*/
synchronized void setHelloVersion(ProtocolVersion helloVersion) {
void setHelloVersion(ProtocolVersion helloVersion) {
recordLock.lock();
try {
this.helloVersion = helloVersion;
} finally {
recordLock.unlock();
}
}
/*
@ -108,9 +121,14 @@ abstract class OutputRecord
return false;
}
synchronized boolean seqNumIsHuge() {
boolean seqNumIsHuge() {
recordLock.lock();
try {
return (writeCipher.authenticator != null) &&
writeCipher.authenticator.seqNumIsHuge();
} finally {
recordLock.unlock();
}
}
// SSLEngine and SSLSocket
@ -148,8 +166,10 @@ abstract class OutputRecord
}
// Change write ciphers, may use change_cipher_spec record.
synchronized void changeWriteCiphers(SSLWriteCipher writeCipher,
void changeWriteCiphers(SSLWriteCipher writeCipher,
boolean useChangeCipherSpec) throws IOException {
recordLock.lock();
try {
if (isClosed()) {
if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
SSLLogger.warning("outbound has closed, ignore outbound " +
@ -174,11 +194,16 @@ abstract class OutputRecord
this.writeCipher = writeCipher;
this.isFirstAppOutputRecord = true;
} finally {
recordLock.unlock();
}
}
// Change write ciphers using key_update handshake message.
synchronized void changeWriteCiphers(SSLWriteCipher writeCipher,
void changeWriteCiphers(SSLWriteCipher writeCipher,
byte keyUpdateRequest) throws IOException {
recordLock.lock();
try {
if (isClosed()) {
if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
SSLLogger.warning("outbound has closed, ignore outbound " +
@ -198,18 +223,36 @@ abstract class OutputRecord
this.writeCipher = writeCipher;
this.isFirstAppOutputRecord = true;
} finally {
recordLock.unlock();
}
}
synchronized void changePacketSize(int packetSize) {
void changePacketSize(int packetSize) {
recordLock.lock();
try {
this.packetSize = packetSize;
} finally {
recordLock.unlock();
}
}
synchronized void changeFragmentSize(int fragmentSize) {
void changeFragmentSize(int fragmentSize) {
recordLock.lock();
try {
this.fragmentSize = fragmentSize;
} finally {
recordLock.unlock();
}
}
synchronized int getMaxPacketSize() {
int getMaxPacketSize() {
recordLock.lock();
try {
return packetSize;
} finally {
recordLock.unlock();
}
}
// apply to DTLS SSLEngine
@ -228,13 +271,18 @@ abstract class OutputRecord
}
@Override
public synchronized void close() throws IOException {
public void close() throws IOException {
recordLock.lock();
try {
if (isClosed) {
return;
}
isClosed = true;
writeCipher.dispose();
} finally {
recordLock.unlock();
}
}
boolean isClosed() {

View File

@ -30,6 +30,7 @@ import java.net.Socket;
import java.security.*;
import java.security.cert.*;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
import javax.net.ssl.*;
import sun.security.action.GetPropertyAction;
import sun.security.provider.certpath.AlgorithmChecker;
@ -69,6 +70,8 @@ public abstract class SSLContextImpl extends SSLContextSpi {
private volatile StatusResponseManager statusResponseManager;
private final ReentrantLock contextLock = new ReentrantLock();
SSLContextImpl() {
ephemeralKeyManager = new EphemeralKeyManager();
clientCache = new SSLSessionContextImpl();
@ -230,11 +233,14 @@ public abstract class SSLContextImpl extends SSLContextSpi {
// Used for DTLS in server mode only.
HelloCookieManager getHelloCookieManager(ProtocolVersion protocolVersion) {
if (helloCookieManagerBuilder == null) {
synchronized (this) {
contextLock.lock();
try {
if (helloCookieManagerBuilder == null) {
helloCookieManagerBuilder =
new HelloCookieManager.Builder(secureRandom);
}
} finally {
contextLock.unlock();
}
}
@ -243,7 +249,8 @@ public abstract class SSLContextImpl extends SSLContextSpi {
StatusResponseManager getStatusResponseManager() {
if (serverEnableStapling && statusResponseManager == null) {
synchronized (this) {
contextLock.lock();
try {
if (statusResponseManager == null) {
if (SSLLogger.isOn && SSLLogger.isOn("ssl,sslctx")) {
SSLLogger.finest(
@ -251,6 +258,8 @@ public abstract class SSLContextImpl extends SSLContextSpi {
}
statusResponseManager = new StatusResponseManager();
}
} finally {
contextLock.unlock();
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -33,6 +33,7 @@ import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BiFunction;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
@ -54,6 +55,7 @@ import javax.net.ssl.SSLSession;
final class SSLEngineImpl extends SSLEngine implements SSLTransport {
private final SSLContextImpl sslContext;
final TransportContext conContext;
private final ReentrantLock engineLock = new ReentrantLock();
/**
* Constructor for an SSLEngine from SSLContext, without
@ -93,7 +95,9 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
}
@Override
public synchronized void beginHandshake() throws SSLException {
public void beginHandshake() throws SSLException {
engineLock.lock();
try {
if (conContext.isUnsureMode) {
throw new IllegalStateException(
"Client/Server mode has not yet been set.");
@ -108,19 +112,24 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
throw conContext.fatal(Alert.INTERNAL_ERROR,
"Fail to begin handshake", ex);
}
} finally {
engineLock.unlock();
}
}
@Override
public synchronized SSLEngineResult wrap(ByteBuffer[] appData,
public SSLEngineResult wrap(ByteBuffer[] appData,
int offset, int length, ByteBuffer netData) throws SSLException {
return wrap(appData, offset, length, new ByteBuffer[]{ netData }, 0, 1);
}
// @Override
public synchronized SSLEngineResult wrap(
public SSLEngineResult wrap(
ByteBuffer[] srcs, int srcsOffset, int srcsLength,
ByteBuffer[] dsts, int dstsOffset, int dstsLength) throws SSLException {
engineLock.lock();
try {
if (conContext.isUnsureMode) {
throw new IllegalStateException(
"Client/Server mode has not yet been set.");
@ -130,7 +139,8 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
checkTaskThrown();
// check parameters
checkParams(srcs, srcsOffset, srcsLength, dsts, dstsOffset, dstsLength);
checkParams(srcs, srcsOffset, srcsLength,
dsts, dstsOffset, dstsLength);
try {
return writeRecord(
@ -145,6 +155,9 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
throw conContext.fatal(Alert.INTERNAL_ERROR,
"Fail to wrap application data", ex);
}
} finally {
engineLock.unlock();
}
}
private SSLEngineResult writeRecord(
@ -428,17 +441,19 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
}
@Override
public synchronized SSLEngineResult unwrap(ByteBuffer src,
public SSLEngineResult unwrap(ByteBuffer src,
ByteBuffer[] dsts, int offset, int length) throws SSLException {
return unwrap(
new ByteBuffer[]{src}, 0, 1, dsts, offset, length);
}
// @Override
public synchronized SSLEngineResult unwrap(
public SSLEngineResult unwrap(
ByteBuffer[] srcs, int srcsOffset, int srcsLength,
ByteBuffer[] dsts, int dstsOffset, int dstsLength) throws SSLException {
engineLock.lock();
try {
if (conContext.isUnsureMode) {
throw new IllegalStateException(
"Client/Server mode has not yet been set.");
@ -448,7 +463,8 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
checkTaskThrown();
// check parameters
checkParams(srcs, srcsOffset, srcsLength, dsts, dstsOffset, dstsLength);
checkParams(srcs, srcsOffset, srcsLength,
dsts, dstsOffset, dstsLength);
try {
return readRecord(
@ -470,6 +486,9 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
throw conContext.fatal(Alert.INTERNAL_ERROR,
"Fail to unwrap network record", ex);
}
} finally {
engineLock.unlock();
}
}
private SSLEngineResult readRecord(
@ -703,19 +722,26 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
}
@Override
public synchronized Runnable getDelegatedTask() {
public Runnable getDelegatedTask() {
engineLock.lock();
try {
if (conContext.handshakeContext != null && // PRE or POST handshake
!conContext.handshakeContext.taskDelegated &&
!conContext.handshakeContext.delegatedActions.isEmpty()) {
conContext.handshakeContext.taskDelegated = true;
return new DelegatedTask(this);
}
} finally {
engineLock.unlock();
}
return null;
}
@Override
public synchronized void closeInbound() throws SSLException {
public void closeInbound() throws SSLException {
engineLock.lock();
try {
if (isInboundDone()) {
return;
}
@ -726,24 +752,35 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
// Is it ready to close inbound?
//
// No need to throw exception if the initial handshake is not started.
// No exception if the initial handshake is not started.
if (!conContext.isInputCloseNotified &&
(conContext.isNegotiated || conContext.handshakeContext != null)) {
(conContext.isNegotiated ||
conContext.handshakeContext != null)) {
throw conContext.fatal(Alert.INTERNAL_ERROR,
"closing inbound before receiving peer's close_notify");
}
conContext.closeInbound();
} finally {
engineLock.unlock();
}
}
@Override
public synchronized boolean isInboundDone() {
public boolean isInboundDone() {
engineLock.lock();
try {
return conContext.isInboundClosed();
} finally {
engineLock.unlock();
}
}
@Override
public synchronized void closeOutbound() {
public void closeOutbound() {
engineLock.lock();
try {
if (conContext.isOutboundClosed()) {
return;
}
@ -753,11 +790,19 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
}
conContext.closeOutbound();
} finally {
engineLock.unlock();
}
}
@Override
public synchronized boolean isOutboundDone() {
public boolean isOutboundDone() {
engineLock.lock();
try {
return conContext.isOutboundDone();
} finally {
engineLock.unlock();
}
}
@Override
@ -766,14 +811,24 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
}
@Override
public synchronized String[] getEnabledCipherSuites() {
public String[] getEnabledCipherSuites() {
engineLock.lock();
try {
return CipherSuite.namesOf(conContext.sslConfig.enabledCipherSuites);
} finally {
engineLock.unlock();
}
}
@Override
public synchronized void setEnabledCipherSuites(String[] suites) {
public void setEnabledCipherSuites(String[] suites) {
engineLock.lock();
try {
conContext.sslConfig.enabledCipherSuites =
CipherSuite.validValuesOf(suites);
} finally {
engineLock.unlock();
}
}
@Override
@ -783,119 +838,214 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
}
@Override
public synchronized String[] getEnabledProtocols() {
public String[] getEnabledProtocols() {
engineLock.lock();
try {
return ProtocolVersion.toStringArray(
conContext.sslConfig.enabledProtocols);
} finally {
engineLock.unlock();
}
}
@Override
public synchronized void setEnabledProtocols(String[] protocols) {
public void setEnabledProtocols(String[] protocols) {
engineLock.lock();
try {
if (protocols == null) {
throw new IllegalArgumentException("Protocols cannot be null");
}
conContext.sslConfig.enabledProtocols =
ProtocolVersion.namesOf(protocols);
} finally {
engineLock.unlock();
}
}
@Override
public synchronized SSLSession getSession() {
public SSLSession getSession() {
engineLock.lock();
try {
return conContext.conSession;
} finally {
engineLock.unlock();
}
}
@Override
public synchronized SSLSession getHandshakeSession() {
public SSLSession getHandshakeSession() {
engineLock.lock();
try {
return conContext.handshakeContext == null ?
null : conContext.handshakeContext.handshakeSession;
} finally {
engineLock.unlock();
}
}
@Override
public synchronized SSLEngineResult.HandshakeStatus getHandshakeStatus() {
public SSLEngineResult.HandshakeStatus getHandshakeStatus() {
engineLock.lock();
try {
return conContext.getHandshakeStatus();
} finally {
engineLock.unlock();
}
}
@Override
public synchronized void setUseClientMode(boolean mode) {
public void setUseClientMode(boolean mode) {
engineLock.lock();
try {
conContext.setUseClientMode(mode);
} finally {
engineLock.unlock();
}
}
@Override
public synchronized boolean getUseClientMode() {
public boolean getUseClientMode() {
engineLock.lock();
try {
return conContext.sslConfig.isClientMode;
} finally {
engineLock.unlock();
}
}
@Override
public synchronized void setNeedClientAuth(boolean need) {
public void setNeedClientAuth(boolean need) {
engineLock.lock();
try {
conContext.sslConfig.clientAuthType =
(need ? ClientAuthType.CLIENT_AUTH_REQUIRED :
ClientAuthType.CLIENT_AUTH_NONE);
} finally {
engineLock.unlock();
}
}
@Override
public synchronized boolean getNeedClientAuth() {
public boolean getNeedClientAuth() {
engineLock.lock();
try {
return (conContext.sslConfig.clientAuthType ==
ClientAuthType.CLIENT_AUTH_REQUIRED);
} finally {
engineLock.unlock();
}
}
@Override
public synchronized void setWantClientAuth(boolean want) {
public void setWantClientAuth(boolean want) {
engineLock.lock();
try {
conContext.sslConfig.clientAuthType =
(want ? ClientAuthType.CLIENT_AUTH_REQUESTED :
ClientAuthType.CLIENT_AUTH_NONE);
} finally {
engineLock.unlock();
}
}
@Override
public synchronized boolean getWantClientAuth() {
public boolean getWantClientAuth() {
engineLock.lock();
try {
return (conContext.sslConfig.clientAuthType ==
ClientAuthType.CLIENT_AUTH_REQUESTED);
} finally {
engineLock.unlock();
}
}
@Override
public synchronized void setEnableSessionCreation(boolean flag) {
public void setEnableSessionCreation(boolean flag) {
engineLock.lock();
try {
conContext.sslConfig.enableSessionCreation = flag;
} finally {
engineLock.unlock();
}
}
@Override
public synchronized boolean getEnableSessionCreation() {
public boolean getEnableSessionCreation() {
engineLock.lock();
try {
return conContext.sslConfig.enableSessionCreation;
} finally {
engineLock.unlock();
}
}
@Override
public synchronized SSLParameters getSSLParameters() {
public SSLParameters getSSLParameters() {
engineLock.lock();
try {
return conContext.sslConfig.getSSLParameters();
} finally {
engineLock.unlock();
}
}
@Override
public synchronized void setSSLParameters(SSLParameters params) {
public void setSSLParameters(SSLParameters params) {
engineLock.lock();
try {
conContext.sslConfig.setSSLParameters(params);
if (conContext.sslConfig.maximumPacketSize != 0) {
conContext.outputRecord.changePacketSize(
conContext.sslConfig.maximumPacketSize);
}
} finally {
engineLock.unlock();
}
}
@Override
public synchronized String getApplicationProtocol() {
public String getApplicationProtocol() {
engineLock.lock();
try {
return conContext.applicationProtocol;
} finally {
engineLock.unlock();
}
}
@Override
public synchronized String getHandshakeApplicationProtocol() {
public String getHandshakeApplicationProtocol() {
engineLock.lock();
try {
return conContext.handshakeContext == null ?
null : conContext.handshakeContext.applicationProtocol;
} finally {
engineLock.unlock();
}
}
@Override
public synchronized void setHandshakeApplicationProtocolSelector(
public void setHandshakeApplicationProtocolSelector(
BiFunction<SSLEngine, List<String>, String> selector) {
engineLock.lock();
try {
conContext.sslConfig.engineAPSelector = selector;
} finally {
engineLock.unlock();
}
}
@Override
public synchronized BiFunction<SSLEngine, List<String>, String>
public BiFunction<SSLEngine, List<String>, String>
getHandshakeApplicationProtocolSelector() {
engineLock.lock();
try {
return conContext.sslConfig.engineAPSelector;
} finally {
engineLock.unlock();
}
}
@Override
@ -909,10 +1059,11 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
* null, report back the Exception that happened in the delegated
* task(s).
*/
private synchronized void checkTaskThrown() throws SSLException {
private void checkTaskThrown() throws SSLException {
Exception exc = null;
engineLock.lock();
try {
// First check the handshake context.
HandshakeContext hc = conContext.handshakeContext;
if ((hc != null) && (hc.delegatedThrown != null)) {
@ -921,8 +1072,8 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
}
/*
* hc.delegatedThrown and conContext.delegatedThrown are most likely
* the same, but it's possible we could have had a non-fatal
* hc.delegatedThrown and conContext.delegatedThrown are most
* likely the same, but it's possible we could have had a non-fatal
* exception and thus the new HandshakeContext is still valid
* (alert warning). If so, then we may have a secondary exception
* waiting to be reported from the TransportContext, so we will
@ -942,6 +1093,9 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
conContext.delegatedThrown = null;
}
}
} finally {
engineLock.unlock();
}
// Anything to report?
if (exc == null) {
@ -998,7 +1152,8 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
@Override
public void run() {
synchronized (engine) {
engine.engineLock.lock();
try {
HandshakeContext hc = engine.conContext.handshakeContext;
if (hc == null || hc.delegatedActions.isEmpty()) {
return;
@ -1055,6 +1210,8 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
if (hc != null) {
hc.taskDelegated = false;
}
} finally {
engine.engineLock.unlock();
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1996, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -51,7 +51,9 @@ final class SSLEngineOutputRecord extends OutputRecord implements SSLRecord {
}
@Override
public synchronized void close() throws IOException {
public void close() throws IOException {
recordLock.lock();
try {
if (!isClosed) {
if (fragmenter != null && fragmenter.hasAlert()) {
isCloseWaiting = true;
@ -59,6 +61,9 @@ final class SSLEngineOutputRecord extends OutputRecord implements SSLRecord {
super.close();
}
}
} finally {
recordLock.unlock();
}
}
boolean isClosed() {

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1996, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -28,6 +28,7 @@ package sun.security.ssl;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.concurrent.locks.ReentrantLock;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLServerSocket;
@ -56,6 +57,7 @@ import javax.net.ssl.SSLServerSocket;
final class SSLServerSocketImpl extends SSLServerSocket {
private final SSLContextImpl sslContext;
private final SSLConfiguration sslConfig;
private final ReentrantLock serverSocketLock = new ReentrantLock();
SSLServerSocketImpl(SSLContextImpl sslContext) throws IOException {
@ -84,14 +86,24 @@ final class SSLServerSocketImpl extends SSLServerSocket {
}
@Override
public synchronized String[] getEnabledCipherSuites() {
public String[] getEnabledCipherSuites() {
serverSocketLock.lock();
try {
return CipherSuite.namesOf(sslConfig.enabledCipherSuites);
} finally {
serverSocketLock.unlock();
}
}
@Override
public synchronized void setEnabledCipherSuites(String[] suites) {
public void setEnabledCipherSuites(String[] suites) {
serverSocketLock.lock();
try {
sslConfig.enabledCipherSuites =
CipherSuite.validValuesOf(suites);
} finally {
serverSocketLock.unlock();
}
}
@Override
@ -106,47 +118,79 @@ final class SSLServerSocketImpl extends SSLServerSocket {
}
@Override
public synchronized String[] getEnabledProtocols() {
public String[] getEnabledProtocols() {
serverSocketLock.lock();
try {
return ProtocolVersion.toStringArray(sslConfig.enabledProtocols);
} finally {
serverSocketLock.unlock();
}
}
@Override
public synchronized void setEnabledProtocols(String[] protocols) {
public void setEnabledProtocols(String[] protocols) {
serverSocketLock.lock();
try {
if (protocols == null) {
throw new IllegalArgumentException("Protocols cannot be null");
}
sslConfig.enabledProtocols = ProtocolVersion.namesOf(protocols);
} finally {
serverSocketLock.unlock();
}
}
@Override
public synchronized void setNeedClientAuth(boolean need) {
public void setNeedClientAuth(boolean need) {
serverSocketLock.lock();
try {
sslConfig.clientAuthType =
(need ? ClientAuthType.CLIENT_AUTH_REQUIRED :
ClientAuthType.CLIENT_AUTH_NONE);
} finally {
serverSocketLock.unlock();
}
}
@Override
public synchronized boolean getNeedClientAuth() {
public boolean getNeedClientAuth() {
serverSocketLock.lock();
try {
return (sslConfig.clientAuthType ==
ClientAuthType.CLIENT_AUTH_REQUIRED);
} finally {
serverSocketLock.unlock();
}
}
@Override
public synchronized void setWantClientAuth(boolean want) {
public void setWantClientAuth(boolean want) {
serverSocketLock.lock();
try {
sslConfig.clientAuthType =
(want ? ClientAuthType.CLIENT_AUTH_REQUESTED :
ClientAuthType.CLIENT_AUTH_NONE);
} finally {
serverSocketLock.unlock();
}
}
@Override
public synchronized boolean getWantClientAuth() {
public boolean getWantClientAuth() {
serverSocketLock.lock();
try {
return (sslConfig.clientAuthType ==
ClientAuthType.CLIENT_AUTH_REQUESTED);
} finally {
serverSocketLock.unlock();
}
}
@Override
public synchronized void setUseClientMode(boolean useClientMode) {
public void setUseClientMode(boolean useClientMode) {
serverSocketLock.lock();
try {
/*
* If we need to change the client mode and the enabled
* protocols and cipher suites haven't specifically been
@ -168,31 +212,59 @@ final class SSLServerSocketImpl extends SSLServerSocket {
sslConfig.isClientMode = useClientMode;
}
} finally {
serverSocketLock.unlock();
}
}
@Override
public synchronized boolean getUseClientMode() {
public boolean getUseClientMode() {
serverSocketLock.lock();
try {
return sslConfig.isClientMode;
} finally {
serverSocketLock.unlock();
}
}
@Override
public synchronized void setEnableSessionCreation(boolean flag) {
public void setEnableSessionCreation(boolean flag) {
serverSocketLock.lock();
try {
sslConfig.enableSessionCreation = flag;
} finally {
serverSocketLock.unlock();
}
}
@Override
public synchronized boolean getEnableSessionCreation() {
public boolean getEnableSessionCreation() {
serverSocketLock.lock();
try {
return sslConfig.enableSessionCreation;
} finally {
serverSocketLock.unlock();
}
}
@Override
public synchronized SSLParameters getSSLParameters() {
public SSLParameters getSSLParameters() {
serverSocketLock.lock();
try {
return sslConfig.getSSLParameters();
} finally {
serverSocketLock.unlock();
}
}
@Override
public synchronized void setSSLParameters(SSLParameters params) {
public void setSSLParameters(SSLParameters params) {
serverSocketLock.lock();
try {
sslConfig.setSSLParameters(params);
} finally {
serverSocketLock.unlock();
}
}
@Override

View File

@ -38,6 +38,7 @@ import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.locks.ReentrantLock;
import javax.crypto.SecretKey;
import javax.net.ssl.ExtendedSSLSession;
import javax.net.ssl.SNIServerName;
@ -135,6 +136,8 @@ final class SSLSessionImpl extends ExtendedSSLSession {
// in this session.
private final String identificationProtocol;
private final ReentrantLock sessionLock = new ReentrantLock();
/*
* Create a new non-rejoinable session, using the default (null)
* cipher spec. This constructor returns a session which could
@ -289,15 +292,22 @@ final class SSLSessionImpl extends ExtendedSSLSession {
return resumptionMasterSecret;
}
synchronized SecretKey getPreSharedKey() {
SecretKey getPreSharedKey() {
sessionLock.lock();
try {
return preSharedKey;
} finally {
sessionLock.unlock();
}
}
synchronized SecretKey consumePreSharedKey() {
SecretKey consumePreSharedKey() {
sessionLock.lock();
try {
return preSharedKey;
} finally {
preSharedKey = null;
sessionLock.unlock();
}
}
@ -313,11 +323,13 @@ final class SSLSessionImpl extends ExtendedSSLSession {
* be used once. This method will return the identity and then clear it
* so it cannot be used again.
*/
synchronized byte[] consumePskIdentity() {
byte[] consumePskIdentity() {
sessionLock.lock();
try {
return pskIdentity;
} finally {
pskIdentity = null;
sessionLock.unlock();
}
}
@ -393,8 +405,13 @@ final class SSLSessionImpl extends ExtendedSSLSession {
}
@Override
public synchronized boolean isValid() {
public boolean isValid() {
sessionLock.lock();
try {
return isRejoinable();
} finally {
sessionLock.unlock();
}
}
/**
@ -777,7 +794,9 @@ final class SSLSessionImpl extends ExtendedSSLSession {
* no connections will be able to rejoin this session.
*/
@Override
public synchronized void invalidate() {
public void invalidate() {
sessionLock.lock();
try {
//
// Can't invalidate the NULL session -- this would be
// attempted when we get a handshaking error on a brand
@ -791,6 +810,7 @@ final class SSLSessionImpl extends ExtendedSSLSession {
context.remove(sessionId);
context = null;
}
if (invalidated) {
return;
}
@ -801,6 +821,9 @@ final class SSLSessionImpl extends ExtendedSSLSession {
for (SSLSessionImpl child : childSessions) {
child.invalidate();
}
} finally {
sessionLock.unlock();
}
}
/*
@ -912,8 +935,13 @@ final class SSLSessionImpl extends ExtendedSSLSession {
* Expand the buffer size of both SSL/TLS network packet and
* application data.
*/
protected synchronized void expandBufferSizes() {
protected void expandBufferSizes() {
sessionLock.lock();
try {
acceptLargeFragments = true;
} finally {
sessionLock.unlock();
}
}
/**
@ -921,7 +949,9 @@ final class SSLSessionImpl extends ExtendedSSLSession {
* when using this session.
*/
@Override
public synchronized int getPacketBufferSize() {
public int getPacketBufferSize() {
sessionLock.lock();
try {
// Use the bigger packet size calculated from maximumPacketSize
// and negotiatedMaxFragLen.
int packetSize = 0;
@ -946,6 +976,9 @@ final class SSLSessionImpl extends ExtendedSSLSession {
return acceptLargeFragments ?
SSLRecord.maxLargeRecordSize : SSLRecord.maxRecordSize;
}
} finally {
sessionLock.unlock();
}
}
/**
@ -953,7 +986,9 @@ final class SSLSessionImpl extends ExtendedSSLSession {
* expected when using this session.
*/
@Override
public synchronized int getApplicationBufferSize() {
public int getApplicationBufferSize() {
sessionLock.lock();
try {
// Use the bigger fragment size calculated from maximumPacketSize
// and negotiatedMaxFragLen.
int fragmentSize = 0;
@ -979,6 +1014,9 @@ final class SSLSessionImpl extends ExtendedSSLSession {
SSLRecord.maxLargeRecordSize : SSLRecord.maxRecordSize;
return (maxPacketSize - SSLRecord.headerSize);
}
} finally {
sessionLock.unlock();
}
}
/**
@ -989,10 +1027,14 @@ final class SSLSessionImpl extends ExtendedSSLSession {
* the negotiated maximum fragment length, or {@code -1} if
* no such length has been negotiated.
*/
synchronized void setNegotiatedMaxFragSize(
void setNegotiatedMaxFragSize(
int negotiatedMaxFragLen) {
sessionLock.lock();
try {
this.negotiatedMaxFragLen = negotiatedMaxFragLen;
} finally {
sessionLock.unlock();
}
}
/**
@ -1002,16 +1044,31 @@ final class SSLSessionImpl extends ExtendedSSLSession {
* @return the negotiated maximum fragment length, or {@code -1} if
* no such length has been negotiated.
*/
synchronized int getNegotiatedMaxFragSize() {
int getNegotiatedMaxFragSize() {
sessionLock.lock();
try {
return negotiatedMaxFragLen;
} finally {
sessionLock.unlock();
}
}
synchronized void setMaximumPacketSize(int maximumPacketSize) {
void setMaximumPacketSize(int maximumPacketSize) {
sessionLock.lock();
try {
this.maximumPacketSize = maximumPacketSize;
} finally {
sessionLock.unlock();
}
}
synchronized int getMaximumPacketSize() {
int getMaximumPacketSize() {
sessionLock.lock();
try {
return maximumPacketSize;
} finally {
sessionLock.unlock();
}
}
/**

View File

@ -38,6 +38,7 @@ import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BiFunction;
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.SSLException;
@ -84,6 +85,9 @@ public final class SSLSocketImpl
private boolean isConnected = false;
private volatile boolean tlsIsClosed = false;
private final ReentrantLock socketLock = new ReentrantLock();
private final ReentrantLock handshakeLock = new ReentrantLock();
/*
* Is the local name service trustworthy?
*
@ -292,14 +296,25 @@ public final class SSLSocketImpl
}
@Override
public synchronized String[] getEnabledCipherSuites() {
return CipherSuite.namesOf(conContext.sslConfig.enabledCipherSuites);
public String[] getEnabledCipherSuites() {
socketLock.lock();
try {
return CipherSuite.namesOf(
conContext.sslConfig.enabledCipherSuites);
} finally {
socketLock.unlock();
}
}
@Override
public synchronized void setEnabledCipherSuites(String[] suites) {
public void setEnabledCipherSuites(String[] suites) {
socketLock.lock();
try {
conContext.sslConfig.enabledCipherSuites =
CipherSuite.validValuesOf(suites);
} finally {
socketLock.unlock();
}
}
@Override
@ -309,19 +324,29 @@ public final class SSLSocketImpl
}
@Override
public synchronized String[] getEnabledProtocols() {
public String[] getEnabledProtocols() {
socketLock.lock();
try {
return ProtocolVersion.toStringArray(
conContext.sslConfig.enabledProtocols);
} finally {
socketLock.unlock();
}
}
@Override
public synchronized void setEnabledProtocols(String[] protocols) {
public void setEnabledProtocols(String[] protocols) {
if (protocols == null) {
throw new IllegalArgumentException("Protocols cannot be null");
}
socketLock.lock();
try {
conContext.sslConfig.enabledProtocols =
ProtocolVersion.namesOf(protocols);
} finally {
socketLock.unlock();
}
}
@Override
@ -341,29 +366,44 @@ public final class SSLSocketImpl
}
@Override
public synchronized SSLSession getHandshakeSession() {
public SSLSession getHandshakeSession() {
socketLock.lock();
try {
return conContext.handshakeContext == null ?
null : conContext.handshakeContext.handshakeSession;
} finally {
socketLock.unlock();
}
}
@Override
public synchronized void addHandshakeCompletedListener(
public void addHandshakeCompletedListener(
HandshakeCompletedListener listener) {
if (listener == null) {
throw new IllegalArgumentException("listener is null");
}
socketLock.lock();
try {
conContext.sslConfig.addHandshakeCompletedListener(listener);
} finally {
socketLock.unlock();
}
}
@Override
public synchronized void removeHandshakeCompletedListener(
public void removeHandshakeCompletedListener(
HandshakeCompletedListener listener) {
if (listener == null) {
throw new IllegalArgumentException("listener is null");
}
socketLock.lock();
try {
conContext.sslConfig.removeHandshakeCompletedListener(listener);
} finally {
socketLock.unlock();
}
}
@Override
@ -377,7 +417,8 @@ public final class SSLSocketImpl
throw new SocketException("Socket has been closed or broken");
}
synchronized (conContext) { // handshake lock
handshakeLock.lock();
try {
// double check the context status
if (conContext.isBroken || conContext.isInboundClosed() ||
conContext.isOutboundClosed()) {
@ -400,53 +441,95 @@ public final class SSLSocketImpl
} catch (Exception oe) { // including RuntimeException
handleException(oe);
}
} finally {
handshakeLock.unlock();
}
}
@Override
public synchronized void setUseClientMode(boolean mode) {
public void setUseClientMode(boolean mode) {
socketLock.lock();
try {
conContext.setUseClientMode(mode);
} finally {
socketLock.unlock();
}
}
@Override
public synchronized boolean getUseClientMode() {
public boolean getUseClientMode() {
socketLock.lock();
try {
return conContext.sslConfig.isClientMode;
} finally {
socketLock.unlock();
}
}
@Override
public synchronized void setNeedClientAuth(boolean need) {
public void setNeedClientAuth(boolean need) {
socketLock.lock();
try {
conContext.sslConfig.clientAuthType =
(need ? ClientAuthType.CLIENT_AUTH_REQUIRED :
ClientAuthType.CLIENT_AUTH_NONE);
} finally {
socketLock.unlock();
}
}
@Override
public synchronized boolean getNeedClientAuth() {
public boolean getNeedClientAuth() {
socketLock.lock();
try {
return (conContext.sslConfig.clientAuthType ==
ClientAuthType.CLIENT_AUTH_REQUIRED);
} finally {
socketLock.unlock();
}
}
@Override
public synchronized void setWantClientAuth(boolean want) {
public void setWantClientAuth(boolean want) {
socketLock.lock();
try {
conContext.sslConfig.clientAuthType =
(want ? ClientAuthType.CLIENT_AUTH_REQUESTED :
ClientAuthType.CLIENT_AUTH_NONE);
} finally {
socketLock.unlock();
}
}
@Override
public synchronized boolean getWantClientAuth() {
public boolean getWantClientAuth() {
socketLock.lock();
try {
return (conContext.sslConfig.clientAuthType ==
ClientAuthType.CLIENT_AUTH_REQUESTED);
} finally {
socketLock.unlock();
}
}
@Override
public synchronized void setEnableSessionCreation(boolean flag) {
public void setEnableSessionCreation(boolean flag) {
socketLock.lock();
try {
conContext.sslConfig.enableSessionCreation = flag;
} finally {
socketLock.unlock();
}
}
@Override
public synchronized boolean getEnableSessionCreation() {
public boolean getEnableSessionCreation() {
socketLock.lock();
try {
return conContext.sslConfig.enableSessionCreation;
} finally {
socketLock.unlock();
}
}
@Override
@ -535,8 +618,9 @@ public final class SSLSocketImpl
// Need a lock here so that the user_canceled alert and the
// close_notify alert can be delivered together.
conContext.outputRecord.recordLock.lock();
try {
try {
synchronized (conContext.outputRecord) {
// send a user_canceled alert if needed.
if (useUserCanceled) {
conContext.warning(Alert.USER_CANCELED);
@ -544,7 +628,6 @@ public final class SSLSocketImpl
// send a close_notify alert
conContext.warning(Alert.CLOSE_NOTIFY);
}
} finally {
if (!conContext.isOutboundClosed()) {
conContext.outputRecord.close();
@ -554,6 +637,9 @@ public final class SSLSocketImpl
super.shutdownOutput();
}
}
} finally {
conContext.outputRecord.recordLock.unlock();
}
if (!isInputShutdown()) {
bruteForceCloseInput(hasCloseReceipt);
@ -681,7 +767,9 @@ public final class SSLSocketImpl
}
@Override
public synchronized InputStream getInputStream() throws IOException {
public InputStream getInputStream() throws IOException {
socketLock.lock();
try {
if (isClosed()) {
throw new SocketException("Socket is closed");
}
@ -695,6 +783,9 @@ public final class SSLSocketImpl
}
return appInput;
} finally {
socketLock.unlock();
}
}
private void ensureNegotiated() throws IOException {
@ -703,7 +794,8 @@ public final class SSLSocketImpl
return;
}
synchronized (conContext) { // handshake lock
handshakeLock.lock();
try {
// double check the context status
if (conContext.isNegotiated || conContext.isBroken ||
conContext.isInboundClosed() ||
@ -712,6 +804,8 @@ public final class SSLSocketImpl
}
startHandshake();
} finally {
handshakeLock.unlock();
}
}
@ -729,6 +823,9 @@ public final class SSLSocketImpl
// Is application data available in the stream?
private volatile boolean appDataIsAvailable;
// reading lock
private final ReentrantLock readLock = new ReentrantLock();
AppInputStream() {
this.appDataIsAvailable = false;
this.buffer = ByteBuffer.allocate(4096);
@ -807,7 +904,8 @@ public final class SSLSocketImpl
//
// Note that the receiving and processing of post-handshake message
// are also synchronized with the read lock.
synchronized (this) {
readLock.lock();
try {
int remains = available();
if (remains > 0) {
int howmany = Math.min(remains, len);
@ -839,6 +937,8 @@ public final class SSLSocketImpl
// dummy for compiler
return -1;
}
} finally {
readLock.unlock();
}
}
@ -850,11 +950,13 @@ public final class SSLSocketImpl
* things simpler.
*/
@Override
public synchronized long skip(long n) throws IOException {
public long skip(long n) throws IOException {
// dummy array used to implement skip()
byte[] skipArray = new byte[256];
long skipped = 0;
readLock.lock();
try {
while (n > 0) {
int len = (int)Math.min(n, skipArray.length);
int r = read(skipArray, 0, len);
@ -864,6 +966,9 @@ public final class SSLSocketImpl
n -= r;
skipped += r;
}
} finally {
readLock.unlock();
}
return skipped;
}
@ -910,8 +1015,18 @@ public final class SSLSocketImpl
* Try the best to use up the input records so as to close the
* socket gracefully, without impact the performance too much.
*/
private synchronized void deplete() {
if (!conContext.isInboundClosed()) {
private void deplete() {
if (conContext.isInboundClosed()) {
return;
}
readLock.lock();
try {
// double check
if (conContext.isInboundClosed()) {
return;
}
if (!(conContext.inputRecord instanceof SSLSocketInputRecord)) {
return;
}
@ -927,12 +1042,16 @@ public final class SSLSocketImpl
"input stream close depletion failed", ioe);
}
}
} finally {
readLock.unlock();
}
}
}
@Override
public synchronized OutputStream getOutputStream() throws IOException {
public OutputStream getOutputStream() throws IOException {
socketLock.lock();
try {
if (isClosed()) {
throw new SocketException("Socket is closed");
}
@ -946,6 +1065,9 @@ public final class SSLSocketImpl
}
return appOutput;
} finally {
socketLock.unlock();
}
}
@ -1035,44 +1157,74 @@ public final class SSLSocketImpl
}
@Override
public synchronized SSLParameters getSSLParameters() {
public SSLParameters getSSLParameters() {
socketLock.lock();
try {
return conContext.sslConfig.getSSLParameters();
} finally {
socketLock.unlock();
}
}
@Override
public synchronized void setSSLParameters(SSLParameters params) {
public void setSSLParameters(SSLParameters params) {
socketLock.lock();
try {
conContext.sslConfig.setSSLParameters(params);
if (conContext.sslConfig.maximumPacketSize != 0) {
conContext.outputRecord.changePacketSize(
conContext.sslConfig.maximumPacketSize);
}
} finally {
socketLock.unlock();
}
}
@Override
public synchronized String getApplicationProtocol() {
public String getApplicationProtocol() {
socketLock.lock();
try {
return conContext.applicationProtocol;
} finally {
socketLock.unlock();
}
}
@Override
public synchronized String getHandshakeApplicationProtocol() {
public String getHandshakeApplicationProtocol() {
socketLock.lock();
try {
if (conContext.handshakeContext != null) {
return conContext.handshakeContext.applicationProtocol;
}
} finally {
socketLock.unlock();
}
return null;
}
@Override
public synchronized void setHandshakeApplicationProtocolSelector(
public void setHandshakeApplicationProtocolSelector(
BiFunction<SSLSocket, List<String>, String> selector) {
socketLock.lock();
try {
conContext.sslConfig.socketAPSelector = selector;
} finally {
socketLock.unlock();
}
}
@Override
public synchronized BiFunction<SSLSocket, List<String>, String>
public BiFunction<SSLSocket, List<String>, String>
getHandshakeApplicationProtocolSelector() {
socketLock.lock();
try {
return conContext.sslConfig.socketAPSelector;
} finally {
socketLock.unlock();
}
}
/**
@ -1142,8 +1294,11 @@ public final class SSLSocketImpl
try {
Plaintext plainText;
synchronized (this) {
socketLock.lock();
try {
plainText = decode(buffer);
} finally {
socketLock.unlock();
}
if (plainText.contentType == ContentType.APPLICATION_DATA.id &&
buffer.position() > 0) {
@ -1222,9 +1377,12 @@ public final class SSLSocketImpl
*
* Called by connect, the layered constructor, and SSLServerSocket.
*/
synchronized void doneConnect() throws IOException {
void doneConnect() throws IOException {
socketLock.lock();
try {
// In server mode, it is not necessary to set host and serverNames.
// Otherwise, would require a reverse DNS lookup to get the hostname.
// Otherwise, would require a reverse DNS lookup to get
// the hostname.
if (peerHost == null || peerHost.isEmpty()) {
boolean useNameService =
trustNameService && conContext.sslConfig.isClientMode;
@ -1243,6 +1401,9 @@ public final class SSLSocketImpl
conContext.outputRecord.setDeliverStream(sockOutput);
this.isConnected = true;
} finally {
socketLock.unlock();
}
}
private void useImplicitHost(boolean useNameService) {
@ -1288,11 +1449,16 @@ public final class SSLSocketImpl
// Please NOTE that this method MUST be called before calling to
// SSLSocket.setSSLParameters(). Otherwise, the {@code host} parameter
// may override SNIHostName in the customized server name indication.
public synchronized void setHost(String host) {
public void setHost(String host) {
socketLock.lock();
try {
this.peerHost = host;
this.conContext.sslConfig.serverNames =
Utilities.addToSNIServerNameList(
conContext.sslConfig.serverNames, host);
} finally {
socketLock.unlock();
}
}
/**

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1996, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -51,8 +51,9 @@ final class SSLSocketOutputRecord extends OutputRecord implements SSLRecord {
}
@Override
synchronized void encodeAlert(
byte level, byte description) throws IOException {
void encodeAlert(byte level, byte description) throws IOException {
recordLock.lock();
try {
if (isClosed()) {
if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
SSLLogger.warning("outbound has closed, ignore outbound " +
@ -88,11 +89,16 @@ final class SSLSocketOutputRecord extends OutputRecord implements SSLRecord {
// reset the internal buffer
count = 0;
} finally {
recordLock.unlock();
}
}
@Override
synchronized void encodeHandshake(byte[] source,
void encodeHandshake(byte[] source,
int offset, int length) throws IOException {
recordLock.lock();
try {
if (isClosed()) {
if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
SSLLogger.warning("outbound has closed, ignore outbound " +
@ -117,7 +123,8 @@ final class SSLSocketOutputRecord extends OutputRecord implements SSLRecord {
ByteBuffer v2ClientHello = encodeV2ClientHello(
source, (offset + 4), (length - 4));
byte[] record = v2ClientHello.array(); // array offset is zero
// array offset is zero
byte[] record = v2ClientHello.array();
int limit = v2ClientHello.limit();
handshakeHash.deliver(record, 2, (limit - 2));
@ -196,10 +203,15 @@ final class SSLSocketOutputRecord extends OutputRecord implements SSLRecord {
// reset the internal buffer
count = position;
}
} finally {
recordLock.unlock();
}
}
@Override
synchronized void encodeChangeCipherSpec() throws IOException {
void encodeChangeCipherSpec() throws IOException {
recordLock.lock();
try {
if (isClosed()) {
if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
SSLLogger.warning("outbound has closed, ignore outbound " +
@ -228,10 +240,15 @@ final class SSLSocketOutputRecord extends OutputRecord implements SSLRecord {
// reset the internal buffer
count = 0;
} finally {
recordLock.unlock();
}
}
@Override
public synchronized void flush() throws IOException {
public void flush() throws IOException {
recordLock.lock();
try {
int position = headerSize + writeCipher.getExplicitNonceSize();
if (count <= position) {
return;
@ -258,13 +275,18 @@ final class SSLSocketOutputRecord extends OutputRecord implements SSLRecord {
// reset the internal buffer
count = 0; // DON'T use position
} finally {
recordLock.unlock();
}
}
@Override
synchronized void deliver(
byte[] source, int offset, int length) throws IOException {
void deliver(byte[] source, int offset, int length) throws IOException {
recordLock.lock();
try {
if (isClosed()) {
throw new SocketException("Connection or outbound has been closed");
throw new SocketException(
"Connection or outbound has been closed");
}
if (writeCipher.authenticator.seqNumOverflow()) {
@ -282,8 +304,8 @@ final class SSLSocketOutputRecord extends OutputRecord implements SSLRecord {
int fragLen;
if (packetSize > 0) {
fragLen = Math.min(maxRecordSize, packetSize);
fragLen =
writeCipher.calculateFragmentSize(fragLen, headerSize);
fragLen = writeCipher.calculateFragmentSize(
fragLen, headerSize);
fragLen = Math.min(fragLen, Record.maxDataSize);
} else {
@ -314,7 +336,8 @@ final class SSLSocketOutputRecord extends OutputRecord implements SSLRecord {
}
// Encrypt the fragment and wrap up a record.
encrypt(writeCipher, ContentType.APPLICATION_DATA.id, headerSize);
encrypt(writeCipher,
ContentType.APPLICATION_DATA.id, headerSize);
// deliver this message
deliverStream.write(buf, 0, count); // may throw IOException
@ -334,11 +357,19 @@ final class SSLSocketOutputRecord extends OutputRecord implements SSLRecord {
offset += fragLen;
}
} finally {
recordLock.unlock();
}
}
@Override
synchronized void setDeliverStream(OutputStream outputStream) {
void setDeliverStream(OutputStream outputStream) {
recordLock.lock();
try {
this.deliverStream = outputStream;
} finally {
recordLock.unlock();
}
}
/*

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -102,25 +102,21 @@ final class SunX509KeyManagerImpl extends X509ExtendedKeyManager {
* Basic container for credentials implemented as an inner class.
*/
private static class X509Credentials {
PrivateKey privateKey;
X509Certificate[] certificates;
private Set<X500Principal> issuerX500Principals;
final PrivateKey privateKey;
final X509Certificate[] certificates;
private final Set<X500Principal> issuerX500Principals;
X509Credentials(PrivateKey privateKey, X509Certificate[] certificates) {
// assert privateKey and certificates != null
this.privateKey = privateKey;
this.certificates = certificates;
this.issuerX500Principals = new HashSet<>(certificates.length);
for (X509Certificate certificate : certificates) {
issuerX500Principals.add(certificate.getIssuerX500Principal());
}
}
synchronized Set<X500Principal> getIssuerX500Principals() {
// lazy initialization
if (issuerX500Principals == null) {
issuerX500Principals = new HashSet<X500Principal>();
for (int i = 0; i < certificates.length; i++) {
issuerX500Principals.add(
certificates[i].getIssuerX500Principal());
}
}
Set<X500Principal> getIssuerX500Principals() {
return issuerX500Principals;
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -496,13 +496,16 @@ class TransportContext implements ConnectionContext {
}
if (needCloseNotify) {
synchronized (outputRecord) {
outputRecord.recordLock.lock();
try {
try {
// send a close_notify alert
warning(Alert.CLOSE_NOTIFY);
} finally {
outputRecord.close();
}
} finally {
outputRecord.recordLock.unlock();
}
}
}
@ -541,7 +544,8 @@ class TransportContext implements ConnectionContext {
// Need a lock here so that the user_canceled alert and the
// close_notify alert can be delivered together.
synchronized (outputRecord) {
outputRecord.recordLock.lock();
try {
try {
// send a user_canceled alert if needed.
if (useUserCanceled) {
@ -553,6 +557,8 @@ class TransportContext implements ConnectionContext {
} finally {
outputRecord.close();
}
} finally {
outputRecord.recordLock.unlock();
}
}

View File

@ -30,6 +30,7 @@ import java.lang.ref.WeakReference;
import java.security.*;
import java.security.cert.*;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
import sun.security.action.*;
import sun.security.validator.TrustStoreUtil;
@ -244,6 +245,8 @@ final class TrustStoreManager {
// objects can be atomically cleared, and reloaded if needed.
private WeakReference<Set<X509Certificate>> csRef;
private final ReentrantLock tamLock = new ReentrantLock();
private TrustAnchorManager() {
this.descriptor = null;
this.ksRef = new WeakReference<>(null);
@ -255,7 +258,7 @@ final class TrustStoreManager {
*
* @return null if the underlying KeyStore is not available.
*/
synchronized KeyStore getKeyStore(
KeyStore getKeyStore(
TrustStoreDescriptor descriptor) throws Exception {
TrustStoreDescriptor temporaryDesc = this.descriptor;
@ -264,6 +267,14 @@ final class TrustStoreManager {
return ks;
}
tamLock.lock();
try {
// double check
ks = ksRef.get();
if ((ks != null) && descriptor.equals(temporaryDesc)) {
return ks;
}
// Reload a new key store.
if (SSLLogger.isOn && SSLLogger.isOn("trustmanager")) {
SSLLogger.fine("Reload the trust store");
@ -272,6 +283,9 @@ final class TrustStoreManager {
ks = loadKeyStore(descriptor);
this.descriptor = descriptor;
this.ksRef = new WeakReference<>(ks);
} finally {
tamLock.unlock();
}
return ks;
}
@ -282,12 +296,21 @@ final class TrustStoreManager {
*
* @return empty collection if the underlying KeyStore is not available.
*/
synchronized Set<X509Certificate> getTrustedCerts(
Set<X509Certificate> getTrustedCerts(
TrustStoreDescriptor descriptor) throws Exception {
KeyStore ks = null;
TrustStoreDescriptor temporaryDesc = this.descriptor;
Set<X509Certificate> certs = csRef.get();
if ((certs != null) && descriptor.equals(temporaryDesc)) {
return certs;
}
tamLock.lock();
try {
// double check
temporaryDesc = this.descriptor;
certs = csRef.get();
if (certs != null) {
if (descriptor.equals(temporaryDesc)) {
return certs;
@ -311,6 +334,7 @@ final class TrustStoreManager {
SSLLogger.fine("Reload the trust store");
}
ks = loadKeyStore(descriptor);
this.ksRef = new WeakReference<>(ks);
}
// Reload trust certs from the key store.
@ -323,9 +347,10 @@ final class TrustStoreManager {
SSLLogger.fine("Reloaded " + certs.size() + " trust certs");
}
// Note that as ks is a local variable, it is not
// necessary to add it to the ksRef weak reference.
this.csRef = new WeakReference<>(certs);
} finally {
tamLock.unlock();
}
return certs;
}

View File

@ -29,6 +29,7 @@ import java.net.Socket;
import java.security.*;
import java.security.cert.*;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
import javax.net.ssl.*;
import sun.security.util.AnchorCertificates;
import sun.security.util.HostnameChecker;
@ -63,6 +64,8 @@ final class X509TrustManagerImpl extends X509ExtendedTrustManager
// the different extension checks. They are initialized lazily on demand.
private volatile Validator clientValidator, serverValidator;
private final ReentrantLock validatorLock = new ReentrantLock();
X509TrustManagerImpl(String validatorType,
Collection<X509Certificate> trustedCerts) {
@ -157,12 +160,15 @@ final class X509TrustManagerImpl extends X509ExtendedTrustManager
if (isClient) {
v = clientValidator;
if (v == null) {
synchronized (this) {
validatorLock.lock();
try {
v = clientValidator;
if (v == null) {
v = getValidator(Validator.VAR_TLS_CLIENT);
clientValidator = v;
}
} finally {
validatorLock.unlock();
}
}
} else {
@ -170,12 +176,15 @@ final class X509TrustManagerImpl extends X509ExtendedTrustManager
// (guaranteed under the new Tiger memory model)
v = serverValidator;
if (v == null) {
synchronized (this) {
validatorLock.lock();
try {
v = serverValidator;
if (v == null) {
v = getValidator(Validator.VAR_TLS_SERVER);
serverValidator = v;
}
} finally {
validatorLock.unlock();
}
}
}