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. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -26,8 +26,9 @@
package javax.net.ssl; package javax.net.ssl;
import java.security.*; import java.security.*;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.util.Objects; import java.util.Objects;
import sun.security.jca.GetInstance; import sun.security.jca.GetInstance;
/** /**
@ -58,6 +59,20 @@ public class SSLContext {
private final String protocol; 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. * Creates an SSLContext object.
* *
@ -72,8 +87,6 @@ public class SSLContext {
this.protocol = protocol; this.protocol = protocol;
} }
private static SSLContext defaultContext;
/** /**
* Returns the default SSL context. * Returns the default SSL context.
* *
@ -91,12 +104,16 @@ public class SSLContext {
* {@link SSLContext#getInstance SSLContext.getInstance()} call fails * {@link SSLContext#getInstance SSLContext.getInstance()} call fails
* @since 1.6 * @since 1.6
*/ */
public static synchronized SSLContext getDefault() public static SSLContext getDefault() throws NoSuchAlgorithmException {
throws NoSuchAlgorithmException { SSLContext temporaryContext = defaultContext;
if (defaultContext == null) { if (temporaryContext == null) {
defaultContext = SSLContext.getInstance("Default"); 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")} * {@code SSLPermission("setDefaultSSLContext")}
* @since 1.6 * @since 1.6
*/ */
public static synchronized void setDefault(SSLContext context) { public static void setDefault(SSLContext context) {
if (context == null) { if (context == null) {
throw new NullPointerException(); throw new NullPointerException();
} }
@ -119,6 +136,7 @@ public class SSLContext {
if (sm != null) { if (sm != null) {
sm.checkPermission(new SSLPermission("setDefaultSSLContext")); sm.checkPermission(new SSLPermission("setDefaultSSLContext"));
} }
defaultContext = context; 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. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -42,17 +42,7 @@ import java.security.*;
* @see SSLServerSocket * @see SSLServerSocket
* @author David Brownell * @author David Brownell
*/ */
public abstract class SSLServerSocketFactory extends ServerSocketFactory 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);
}
}
/** /**
* Constructor is used only by subclasses. * Constructor is used only by subclasses.
@ -75,39 +65,9 @@ public abstract class SSLServerSocketFactory extends ServerSocketFactory
* @return the default <code>ServerSocketFactory</code> * @return the default <code>ServerSocketFactory</code>
* @see SSLContext#getDefault * @see SSLContext#getDefault
*/ */
public static synchronized ServerSocketFactory getDefault() { public static ServerSocketFactory getDefault() {
if (theFactory != null) { if (DefaultFactoryHolder.defaultFactory != null) {
return theFactory; return DefaultFactoryHolder.defaultFactory;
}
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;
}
}
} }
try { try {
@ -156,8 +116,50 @@ public abstract class SSLServerSocketFactory extends ServerSocketFactory
* @see #getDefaultCipherSuites() * @see #getDefaultCipherSuites()
*/ */
public abstract String [] getSupportedCipherSuites(); 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. // 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. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -42,31 +42,20 @@ import sun.security.action.GetPropertyAction;
* @see SSLSocket * @see SSLSocket
* @author David Brownell * @author David Brownell
*/ */
public abstract class SSLSocketFactory extends SocketFactory public abstract class SSLSocketFactory extends SocketFactory {
{
private static SSLSocketFactory theFactory;
private static boolean propertyChecked;
static final boolean DEBUG; static final boolean DEBUG;
static { static {
String s = GetPropertyAction.privilegedGetProperty("javax.net.debug", "") String s = GetPropertyAction.privilegedGetProperty(
.toLowerCase(Locale.ENGLISH); "javax.net.debug", "").toLowerCase(Locale.ENGLISH);
DEBUG = s.contains("all") || s.contains("ssl"); 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. * Constructor is used only by subclasses.
*/ */
public SSLSocketFactory() { public SSLSocketFactory() {
// blank
} }
/** /**
@ -85,38 +74,9 @@ public abstract class SSLSocketFactory extends SocketFactory
* @return the default <code>SocketFactory</code> * @return the default <code>SocketFactory</code>
* @see SSLContext#getDefault * @see SSLContext#getDefault
*/ */
public static synchronized SocketFactory getDefault() { public static SocketFactory getDefault() {
if (theFactory != null) { if (DefaultFactoryHolder.defaultFactory != null) {
return theFactory; return DefaultFactoryHolder.defaultFactory;
}
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;
}
}
} }
try { try {
@ -246,6 +206,49 @@ public abstract class SSLSocketFactory extends SocketFactory
boolean autoClose) throws IOException { boolean autoClose) throws IOException {
throw new UnsupportedOperationException(); 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 public class HttpsURLConnectionImpl
extends javax.net.ssl.HttpsURLConnection { extends javax.net.ssl.HttpsURLConnection {
// NOTE: made protected for plugin so that subclass can set it. private final DelegateHttpsURLConnection delegate;
protected DelegateHttpsURLConnection delegate;
HttpsURLConnectionImpl(URL u, Handler handler) throws IOException { HttpsURLConnectionImpl(URL u, Handler handler) throws IOException {
this(u, null, handler); this(u, null, handler);
@ -78,13 +77,6 @@ public class HttpsURLConnectionImpl
delegate = new DelegateHttpsURLConnection(url, p, handler, this); 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 * Create a new HttpClient object, bypassing the cache of
* HTTP client objects/connections. * HTTP client objects/connections.
@ -219,11 +211,11 @@ public class HttpsURLConnectionImpl
* - get input, [read input,] get output, [write output] * - get input, [read input,] get output, [write output]
*/ */
public synchronized OutputStream getOutputStream() throws IOException { public OutputStream getOutputStream() throws IOException {
return delegate.getOutputStream(); return delegate.getOutputStream();
} }
public synchronized InputStream getInputStream() throws IOException { public InputStream getInputStream() throws IOException {
return delegate.getInputStream(); 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. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -632,7 +632,7 @@ abstract class BaseSSLSocketImpl extends SSLSocket {
} }
@Override @Override
public synchronized void setSoTimeout(int timeout) throws SocketException { public void setSoTimeout(int timeout) throws SocketException {
if (self == this) { if (self == this) {
super.setSoTimeout(timeout); super.setSoTimeout(timeout);
} else { } 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. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * 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 @Override
public synchronized void close() throws IOException { public void close() throws IOException {
if (!isClosed) { if (!isClosed) {
super.close(); 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. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * 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 @Override
public synchronized void close() throws IOException { public void close() throws IOException {
recordLock.lock();
try {
if (!isClosed) { if (!isClosed) {
if (fragmenter != null && fragmenter.hasAlert()) { if (fragmenter != null && fragmenter.hasAlert()) {
isCloseWaiting = true; isCloseWaiting = true;
@ -66,6 +68,9 @@ final class DTLSOutputRecord extends OutputRecord implements DTLSRecord {
super.close(); super.close();
} }
} }
} finally {
recordLock.unlock();
}
} }
boolean isClosed() { boolean isClosed() {

View File

@ -26,6 +26,7 @@
package sun.security.ssl; package sun.security.ssl;
import java.security.*; import java.security.*;
import java.util.concurrent.locks.ReentrantLock;
/** /**
* The "KeyManager" for ephemeral RSA keys. Ephemeral DH and ECDH keys * The "KeyManager" for ephemeral RSA keys. Ephemeral DH and ECDH keys
@ -48,6 +49,8 @@ final class EphemeralKeyManager {
new EphemeralKeyPair(null), new EphemeralKeyPair(null),
}; };
private final ReentrantLock cachedKeysLock = new ReentrantLock();
EphemeralKeyManager() { EphemeralKeyManager() {
// empty // empty
} }
@ -65,9 +68,19 @@ final class EphemeralKeyManager {
index = INDEX_RSA1024; index = INDEX_RSA1024;
} }
synchronized (keys) {
KeyPair kp = keys[index].getKeyPair(); 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 { try {
KeyPairGenerator kgen = KeyPairGenerator.getInstance("RSA"); KeyPairGenerator kgen = KeyPairGenerator.getInstance("RSA");
kgen.initialize(length, random); kgen.initialize(length, random);
@ -76,10 +89,12 @@ final class EphemeralKeyManager {
} catch (Exception e) { } catch (Exception e) {
// ignore // ignore
} }
} finally {
cachedKeysLock.unlock();
} }
return kp; return kp;
} }
}
/** /**
* Inner class to handle storage of ephemeral KeyPairs. * 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.NoSuchAlgorithmException;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.util.Arrays; import java.util.Arrays;
import java.util.concurrent.locks.ReentrantLock;
import static sun.security.ssl.ClientHello.ClientHelloMessage; import static sun.security.ssl.ClientHello.ClientHelloMessage;
/** /**
@ -45,6 +46,8 @@ abstract class HelloCookieManager {
private volatile D13HelloCookieManager d13HelloCookieManager; private volatile D13HelloCookieManager d13HelloCookieManager;
private volatile T13HelloCookieManager t13HelloCookieManager; private volatile T13HelloCookieManager t13HelloCookieManager;
private final ReentrantLock managerLock = new ReentrantLock();
Builder(SecureRandom secureRandom) { Builder(SecureRandom secureRandom) {
this.secureRandom = secureRandom; this.secureRandom = secureRandom;
} }
@ -56,11 +59,14 @@ abstract class HelloCookieManager {
return d13HelloCookieManager; return d13HelloCookieManager;
} }
synchronized (this) { managerLock.lock();
try {
if (d13HelloCookieManager == null) { if (d13HelloCookieManager == null) {
d13HelloCookieManager = d13HelloCookieManager =
new D13HelloCookieManager(secureRandom); new D13HelloCookieManager(secureRandom);
} }
} finally {
managerLock.unlock();
} }
return d13HelloCookieManager; return d13HelloCookieManager;
@ -69,11 +75,14 @@ abstract class HelloCookieManager {
return d10HelloCookieManager; return d10HelloCookieManager;
} }
synchronized (this) { managerLock.lock();
try {
if (d10HelloCookieManager == null) { if (d10HelloCookieManager == null) {
d10HelloCookieManager = d10HelloCookieManager =
new D10HelloCookieManager(secureRandom); new D10HelloCookieManager(secureRandom);
} }
} finally {
managerLock.unlock();
} }
return d10HelloCookieManager; return d10HelloCookieManager;
@ -84,11 +93,14 @@ abstract class HelloCookieManager {
return t13HelloCookieManager; return t13HelloCookieManager;
} }
synchronized (this) { managerLock.lock();
try {
if (t13HelloCookieManager == null) { if (t13HelloCookieManager == null) {
t13HelloCookieManager = t13HelloCookieManager =
new T13HelloCookieManager(secureRandom); new T13HelloCookieManager(secureRandom);
} }
} finally {
managerLock.unlock();
} }
return t13HelloCookieManager; return t13HelloCookieManager;
@ -114,6 +126,8 @@ abstract class HelloCookieManager {
private byte[] cookieSecret; private byte[] cookieSecret;
private byte[] legacySecret; private byte[] legacySecret;
private final ReentrantLock d10ManagerLock = new ReentrantLock();
D10HelloCookieManager(SecureRandom secureRandom) { D10HelloCookieManager(SecureRandom secureRandom) {
this.secureRandom = secureRandom; this.secureRandom = secureRandom;
@ -131,7 +145,8 @@ abstract class HelloCookieManager {
int version; int version;
byte[] secret; byte[] secret;
synchronized (this) { d10ManagerLock.lock();
try {
version = cookieVersion; version = cookieVersion;
secret = cookieSecret; secret = cookieSecret;
@ -142,6 +157,8 @@ abstract class HelloCookieManager {
} }
cookieVersion++; cookieVersion++;
} finally {
d10ManagerLock.unlock();
} }
MessageDigest md; MessageDigest md;
@ -168,12 +185,15 @@ abstract class HelloCookieManager {
} }
byte[] secret; byte[] secret;
synchronized (this) { d10ManagerLock.lock();
try {
if (((cookieVersion >> 24) & 0xFF) == cookie[0]) { if (((cookieVersion >> 24) & 0xFF) == cookie[0]) {
secret = cookieSecret; secret = cookieSecret;
} else { } else {
secret = legacySecret; // including out of window cookies secret = legacySecret; // including out of window cookies
} }
} finally {
d10ManagerLock.unlock();
} }
MessageDigest md; MessageDigest md;
@ -218,6 +238,8 @@ abstract class HelloCookieManager {
private final byte[] cookieSecret; private final byte[] cookieSecret;
private final byte[] legacySecret; private final byte[] legacySecret;
private final ReentrantLock t13ManagerLock = new ReentrantLock();
T13HelloCookieManager(SecureRandom secureRandom) { T13HelloCookieManager(SecureRandom secureRandom) {
this.secureRandom = secureRandom; this.secureRandom = secureRandom;
this.cookieVersion = secureRandom.nextInt(); this.cookieVersion = secureRandom.nextInt();
@ -234,7 +256,8 @@ abstract class HelloCookieManager {
int version; int version;
byte[] secret; byte[] secret;
synchronized (this) { t13ManagerLock.lock();
try {
version = cookieVersion; version = cookieVersion;
secret = cookieSecret; secret = cookieSecret;
@ -245,6 +268,8 @@ abstract class HelloCookieManager {
} }
cookieVersion++; // allow wrapped version number cookieVersion++; // allow wrapped version number
} finally {
t13ManagerLock.unlock();
} }
MessageDigest md; MessageDigest md;
@ -313,12 +338,15 @@ abstract class HelloCookieManager {
Arrays.copyOfRange(cookie, 3 + hashLen, cookie.length); Arrays.copyOfRange(cookie, 3 + hashLen, cookie.length);
byte[] secret; byte[] secret;
synchronized (this) { t13ManagerLock.lock();
try {
if ((byte)((cookieVersion >> 24) & 0xFF) == cookie[2]) { if ((byte)((cookieVersion >> 24) & 0xFF) == cookie[2]) {
secret = cookieSecret; secret = cookieSecret;
} else { } else {
secret = legacySecret; // including out of window cookies secret = legacySecret; // including out of window cookies
} }
} finally {
t13ManagerLock.unlock();
} }
MessageDigest md; 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. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * 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.io.OutputStream;
import java.nio.BufferUnderflowException; import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.concurrent.locks.ReentrantLock;
import javax.crypto.BadPaddingException; import javax.crypto.BadPaddingException;
import sun.security.ssl.SSLCipher.SSLReadCipher; import sun.security.ssl.SSLCipher.SSLReadCipher;
@ -46,7 +47,7 @@ abstract class InputRecord implements Record, Closeable {
TransportContext tc; TransportContext tc;
final HandshakeHash handshakeHash; final HandshakeHash handshakeHash;
boolean isClosed; volatile boolean isClosed;
// The ClientHello version to accept. If set to ProtocolVersion.SSL20Hello // The ClientHello version to accept. If set to ProtocolVersion.SSL20Hello
// and the first message we read is a ClientHello in V2 format, we convert // 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 // fragment size
int fragmentSize; int fragmentSize;
final ReentrantLock recordLock = new ReentrantLock();
InputRecord(HandshakeHash handshakeHash, SSLReadCipher readCipher) { InputRecord(HandshakeHash handshakeHash, SSLReadCipher readCipher) {
this.readCipher = readCipher; this.readCipher = readCipher;
this.helloVersion = ProtocolVersion.TLS10; this.helloVersion = ProtocolVersion.TLS10;
@ -92,14 +95,19 @@ abstract class InputRecord implements Record, Closeable {
* and flag the record as holding no data. * and flag the record as holding no data.
*/ */
@Override @Override
public synchronized void close() throws IOException { public void close() throws IOException {
recordLock.lock();
try {
if (!isClosed) { if (!isClosed) {
isClosed = true; isClosed = true;
readCipher.dispose(); readCipher.dispose();
} }
} finally {
recordLock.unlock();
}
} }
synchronized boolean isClosed() { boolean isClosed() {
return 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. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * 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.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.concurrent.locks.ReentrantLock;
import sun.security.ssl.SSLCipher.SSLWriteCipher; import sun.security.ssl.SSLCipher.SSLWriteCipher;
/** /**
@ -68,6 +69,8 @@ abstract class OutputRecord
// closed or not? // closed or not?
volatile boolean isClosed; volatile boolean isClosed;
final ReentrantLock recordLock = new ReentrantLock();
/* /*
* Mappings from V3 cipher suite encodings to their pure V2 equivalents. * Mappings from V3 cipher suite encodings to their pure V2 equivalents.
* This is taken from the SSL V3 specification, Appendix E. * 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. // Please set packetSize and protocolVersion in the implementation.
} }
synchronized void setVersion(ProtocolVersion protocolVersion) { void setVersion(ProtocolVersion protocolVersion) {
recordLock.lock();
try {
this.protocolVersion = protocolVersion; this.protocolVersion = protocolVersion;
} finally {
recordLock.unlock();
}
} }
/* /*
* Updates helloVersion of this record. * Updates helloVersion of this record.
*/ */
synchronized void setHelloVersion(ProtocolVersion helloVersion) { void setHelloVersion(ProtocolVersion helloVersion) {
recordLock.lock();
try {
this.helloVersion = helloVersion; this.helloVersion = helloVersion;
} finally {
recordLock.unlock();
}
} }
/* /*
@ -108,9 +121,14 @@ abstract class OutputRecord
return false; return false;
} }
synchronized boolean seqNumIsHuge() { boolean seqNumIsHuge() {
recordLock.lock();
try {
return (writeCipher.authenticator != null) && return (writeCipher.authenticator != null) &&
writeCipher.authenticator.seqNumIsHuge(); writeCipher.authenticator.seqNumIsHuge();
} finally {
recordLock.unlock();
}
} }
// SSLEngine and SSLSocket // SSLEngine and SSLSocket
@ -148,8 +166,10 @@ abstract class OutputRecord
} }
// Change write ciphers, may use change_cipher_spec record. // Change write ciphers, may use change_cipher_spec record.
synchronized void changeWriteCiphers(SSLWriteCipher writeCipher, void changeWriteCiphers(SSLWriteCipher writeCipher,
boolean useChangeCipherSpec) throws IOException { boolean useChangeCipherSpec) throws IOException {
recordLock.lock();
try {
if (isClosed()) { if (isClosed()) {
if (SSLLogger.isOn && SSLLogger.isOn("ssl")) { if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
SSLLogger.warning("outbound has closed, ignore outbound " + SSLLogger.warning("outbound has closed, ignore outbound " +
@ -174,11 +194,16 @@ abstract class OutputRecord
this.writeCipher = writeCipher; this.writeCipher = writeCipher;
this.isFirstAppOutputRecord = true; this.isFirstAppOutputRecord = true;
} finally {
recordLock.unlock();
}
} }
// Change write ciphers using key_update handshake message. // Change write ciphers using key_update handshake message.
synchronized void changeWriteCiphers(SSLWriteCipher writeCipher, void changeWriteCiphers(SSLWriteCipher writeCipher,
byte keyUpdateRequest) throws IOException { byte keyUpdateRequest) throws IOException {
recordLock.lock();
try {
if (isClosed()) { if (isClosed()) {
if (SSLLogger.isOn && SSLLogger.isOn("ssl")) { if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
SSLLogger.warning("outbound has closed, ignore outbound " + SSLLogger.warning("outbound has closed, ignore outbound " +
@ -198,18 +223,36 @@ abstract class OutputRecord
this.writeCipher = writeCipher; this.writeCipher = writeCipher;
this.isFirstAppOutputRecord = true; this.isFirstAppOutputRecord = true;
} finally {
recordLock.unlock();
}
} }
synchronized void changePacketSize(int packetSize) { void changePacketSize(int packetSize) {
recordLock.lock();
try {
this.packetSize = packetSize; this.packetSize = packetSize;
} finally {
recordLock.unlock();
}
} }
synchronized void changeFragmentSize(int fragmentSize) { void changeFragmentSize(int fragmentSize) {
recordLock.lock();
try {
this.fragmentSize = fragmentSize; this.fragmentSize = fragmentSize;
} finally {
recordLock.unlock();
}
} }
synchronized int getMaxPacketSize() { int getMaxPacketSize() {
recordLock.lock();
try {
return packetSize; return packetSize;
} finally {
recordLock.unlock();
}
} }
// apply to DTLS SSLEngine // apply to DTLS SSLEngine
@ -228,13 +271,18 @@ abstract class OutputRecord
} }
@Override @Override
public synchronized void close() throws IOException { public void close() throws IOException {
recordLock.lock();
try {
if (isClosed) { if (isClosed) {
return; return;
} }
isClosed = true; isClosed = true;
writeCipher.dispose(); writeCipher.dispose();
} finally {
recordLock.unlock();
}
} }
boolean isClosed() { boolean isClosed() {

View File

@ -30,6 +30,7 @@ import java.net.Socket;
import java.security.*; import java.security.*;
import java.security.cert.*; import java.security.cert.*;
import java.util.*; import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
import javax.net.ssl.*; import javax.net.ssl.*;
import sun.security.action.GetPropertyAction; import sun.security.action.GetPropertyAction;
import sun.security.provider.certpath.AlgorithmChecker; import sun.security.provider.certpath.AlgorithmChecker;
@ -69,6 +70,8 @@ public abstract class SSLContextImpl extends SSLContextSpi {
private volatile StatusResponseManager statusResponseManager; private volatile StatusResponseManager statusResponseManager;
private final ReentrantLock contextLock = new ReentrantLock();
SSLContextImpl() { SSLContextImpl() {
ephemeralKeyManager = new EphemeralKeyManager(); ephemeralKeyManager = new EphemeralKeyManager();
clientCache = new SSLSessionContextImpl(); clientCache = new SSLSessionContextImpl();
@ -230,11 +233,14 @@ public abstract class SSLContextImpl extends SSLContextSpi {
// Used for DTLS in server mode only. // Used for DTLS in server mode only.
HelloCookieManager getHelloCookieManager(ProtocolVersion protocolVersion) { HelloCookieManager getHelloCookieManager(ProtocolVersion protocolVersion) {
if (helloCookieManagerBuilder == null) { if (helloCookieManagerBuilder == null) {
synchronized (this) { contextLock.lock();
try {
if (helloCookieManagerBuilder == null) { if (helloCookieManagerBuilder == null) {
helloCookieManagerBuilder = helloCookieManagerBuilder =
new HelloCookieManager.Builder(secureRandom); new HelloCookieManager.Builder(secureRandom);
} }
} finally {
contextLock.unlock();
} }
} }
@ -243,7 +249,8 @@ public abstract class SSLContextImpl extends SSLContextSpi {
StatusResponseManager getStatusResponseManager() { StatusResponseManager getStatusResponseManager() {
if (serverEnableStapling && statusResponseManager == null) { if (serverEnableStapling && statusResponseManager == null) {
synchronized (this) { contextLock.lock();
try {
if (statusResponseManager == null) { if (statusResponseManager == null) {
if (SSLLogger.isOn && SSLLogger.isOn("ssl,sslctx")) { if (SSLLogger.isOn && SSLLogger.isOn("ssl,sslctx")) {
SSLLogger.finest( SSLLogger.finest(
@ -251,6 +258,8 @@ public abstract class SSLContextImpl extends SSLContextSpi {
} }
statusResponseManager = new StatusResponseManager(); 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. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * 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.security.PrivilegedExceptionAction;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BiFunction; import java.util.function.BiFunction;
import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLEngineResult;
@ -54,6 +55,7 @@ import javax.net.ssl.SSLSession;
final class SSLEngineImpl extends SSLEngine implements SSLTransport { final class SSLEngineImpl extends SSLEngine implements SSLTransport {
private final SSLContextImpl sslContext; private final SSLContextImpl sslContext;
final TransportContext conContext; final TransportContext conContext;
private final ReentrantLock engineLock = new ReentrantLock();
/** /**
* Constructor for an SSLEngine from SSLContext, without * Constructor for an SSLEngine from SSLContext, without
@ -93,7 +95,9 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
} }
@Override @Override
public synchronized void beginHandshake() throws SSLException { public void beginHandshake() throws SSLException {
engineLock.lock();
try {
if (conContext.isUnsureMode) { if (conContext.isUnsureMode) {
throw new IllegalStateException( throw new IllegalStateException(
"Client/Server mode has not yet been set."); "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, throw conContext.fatal(Alert.INTERNAL_ERROR,
"Fail to begin handshake", ex); "Fail to begin handshake", ex);
} }
} finally {
engineLock.unlock();
}
} }
@Override @Override
public synchronized SSLEngineResult wrap(ByteBuffer[] appData, public SSLEngineResult wrap(ByteBuffer[] appData,
int offset, int length, ByteBuffer netData) throws SSLException { int offset, int length, ByteBuffer netData) throws SSLException {
return wrap(appData, offset, length, new ByteBuffer[]{ netData }, 0, 1); return wrap(appData, offset, length, new ByteBuffer[]{ netData }, 0, 1);
} }
// @Override // @Override
public synchronized SSLEngineResult wrap( public SSLEngineResult wrap(
ByteBuffer[] srcs, int srcsOffset, int srcsLength, ByteBuffer[] srcs, int srcsOffset, int srcsLength,
ByteBuffer[] dsts, int dstsOffset, int dstsLength) throws SSLException { ByteBuffer[] dsts, int dstsOffset, int dstsLength) throws SSLException {
engineLock.lock();
try {
if (conContext.isUnsureMode) { if (conContext.isUnsureMode) {
throw new IllegalStateException( throw new IllegalStateException(
"Client/Server mode has not yet been set."); "Client/Server mode has not yet been set.");
@ -130,7 +139,8 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
checkTaskThrown(); checkTaskThrown();
// check parameters // check parameters
checkParams(srcs, srcsOffset, srcsLength, dsts, dstsOffset, dstsLength); checkParams(srcs, srcsOffset, srcsLength,
dsts, dstsOffset, dstsLength);
try { try {
return writeRecord( return writeRecord(
@ -145,6 +155,9 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
throw conContext.fatal(Alert.INTERNAL_ERROR, throw conContext.fatal(Alert.INTERNAL_ERROR,
"Fail to wrap application data", ex); "Fail to wrap application data", ex);
} }
} finally {
engineLock.unlock();
}
} }
private SSLEngineResult writeRecord( private SSLEngineResult writeRecord(
@ -428,17 +441,19 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
} }
@Override @Override
public synchronized SSLEngineResult unwrap(ByteBuffer src, public SSLEngineResult unwrap(ByteBuffer src,
ByteBuffer[] dsts, int offset, int length) throws SSLException { ByteBuffer[] dsts, int offset, int length) throws SSLException {
return unwrap( return unwrap(
new ByteBuffer[]{src}, 0, 1, dsts, offset, length); new ByteBuffer[]{src}, 0, 1, dsts, offset, length);
} }
// @Override // @Override
public synchronized SSLEngineResult unwrap( public SSLEngineResult unwrap(
ByteBuffer[] srcs, int srcsOffset, int srcsLength, ByteBuffer[] srcs, int srcsOffset, int srcsLength,
ByteBuffer[] dsts, int dstsOffset, int dstsLength) throws SSLException { ByteBuffer[] dsts, int dstsOffset, int dstsLength) throws SSLException {
engineLock.lock();
try {
if (conContext.isUnsureMode) { if (conContext.isUnsureMode) {
throw new IllegalStateException( throw new IllegalStateException(
"Client/Server mode has not yet been set."); "Client/Server mode has not yet been set.");
@ -448,7 +463,8 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
checkTaskThrown(); checkTaskThrown();
// check parameters // check parameters
checkParams(srcs, srcsOffset, srcsLength, dsts, dstsOffset, dstsLength); checkParams(srcs, srcsOffset, srcsLength,
dsts, dstsOffset, dstsLength);
try { try {
return readRecord( return readRecord(
@ -470,6 +486,9 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
throw conContext.fatal(Alert.INTERNAL_ERROR, throw conContext.fatal(Alert.INTERNAL_ERROR,
"Fail to unwrap network record", ex); "Fail to unwrap network record", ex);
} }
} finally {
engineLock.unlock();
}
} }
private SSLEngineResult readRecord( private SSLEngineResult readRecord(
@ -703,19 +722,26 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
} }
@Override @Override
public synchronized Runnable getDelegatedTask() { public Runnable getDelegatedTask() {
engineLock.lock();
try {
if (conContext.handshakeContext != null && // PRE or POST handshake if (conContext.handshakeContext != null && // PRE or POST handshake
!conContext.handshakeContext.taskDelegated && !conContext.handshakeContext.taskDelegated &&
!conContext.handshakeContext.delegatedActions.isEmpty()) { !conContext.handshakeContext.delegatedActions.isEmpty()) {
conContext.handshakeContext.taskDelegated = true; conContext.handshakeContext.taskDelegated = true;
return new DelegatedTask(this); return new DelegatedTask(this);
} }
} finally {
engineLock.unlock();
}
return null; return null;
} }
@Override @Override
public synchronized void closeInbound() throws SSLException { public void closeInbound() throws SSLException {
engineLock.lock();
try {
if (isInboundDone()) { if (isInboundDone()) {
return; return;
} }
@ -726,24 +752,35 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
// Is it ready to close inbound? // 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 && if (!conContext.isInputCloseNotified &&
(conContext.isNegotiated || conContext.handshakeContext != null)) { (conContext.isNegotiated ||
conContext.handshakeContext != null)) {
throw conContext.fatal(Alert.INTERNAL_ERROR, throw conContext.fatal(Alert.INTERNAL_ERROR,
"closing inbound before receiving peer's close_notify"); "closing inbound before receiving peer's close_notify");
} }
conContext.closeInbound(); conContext.closeInbound();
} finally {
engineLock.unlock();
}
} }
@Override @Override
public synchronized boolean isInboundDone() { public boolean isInboundDone() {
engineLock.lock();
try {
return conContext.isInboundClosed(); return conContext.isInboundClosed();
} finally {
engineLock.unlock();
}
} }
@Override @Override
public synchronized void closeOutbound() { public void closeOutbound() {
engineLock.lock();
try {
if (conContext.isOutboundClosed()) { if (conContext.isOutboundClosed()) {
return; return;
} }
@ -753,11 +790,19 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
} }
conContext.closeOutbound(); conContext.closeOutbound();
} finally {
engineLock.unlock();
}
} }
@Override @Override
public synchronized boolean isOutboundDone() { public boolean isOutboundDone() {
engineLock.lock();
try {
return conContext.isOutboundDone(); return conContext.isOutboundDone();
} finally {
engineLock.unlock();
}
} }
@Override @Override
@ -766,14 +811,24 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
} }
@Override @Override
public synchronized String[] getEnabledCipherSuites() { public String[] getEnabledCipherSuites() {
engineLock.lock();
try {
return CipherSuite.namesOf(conContext.sslConfig.enabledCipherSuites); return CipherSuite.namesOf(conContext.sslConfig.enabledCipherSuites);
} finally {
engineLock.unlock();
}
} }
@Override @Override
public synchronized void setEnabledCipherSuites(String[] suites) { public void setEnabledCipherSuites(String[] suites) {
engineLock.lock();
try {
conContext.sslConfig.enabledCipherSuites = conContext.sslConfig.enabledCipherSuites =
CipherSuite.validValuesOf(suites); CipherSuite.validValuesOf(suites);
} finally {
engineLock.unlock();
}
} }
@Override @Override
@ -783,119 +838,214 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
} }
@Override @Override
public synchronized String[] getEnabledProtocols() { public String[] getEnabledProtocols() {
engineLock.lock();
try {
return ProtocolVersion.toStringArray( return ProtocolVersion.toStringArray(
conContext.sslConfig.enabledProtocols); conContext.sslConfig.enabledProtocols);
} finally {
engineLock.unlock();
}
} }
@Override @Override
public synchronized void setEnabledProtocols(String[] protocols) { public void setEnabledProtocols(String[] protocols) {
engineLock.lock();
try {
if (protocols == null) { if (protocols == null) {
throw new IllegalArgumentException("Protocols cannot be null"); throw new IllegalArgumentException("Protocols cannot be null");
} }
conContext.sslConfig.enabledProtocols = conContext.sslConfig.enabledProtocols =
ProtocolVersion.namesOf(protocols); ProtocolVersion.namesOf(protocols);
} finally {
engineLock.unlock();
}
} }
@Override @Override
public synchronized SSLSession getSession() { public SSLSession getSession() {
engineLock.lock();
try {
return conContext.conSession; return conContext.conSession;
} finally {
engineLock.unlock();
}
} }
@Override @Override
public synchronized SSLSession getHandshakeSession() { public SSLSession getHandshakeSession() {
engineLock.lock();
try {
return conContext.handshakeContext == null ? return conContext.handshakeContext == null ?
null : conContext.handshakeContext.handshakeSession; null : conContext.handshakeContext.handshakeSession;
} finally {
engineLock.unlock();
}
} }
@Override @Override
public synchronized SSLEngineResult.HandshakeStatus getHandshakeStatus() { public SSLEngineResult.HandshakeStatus getHandshakeStatus() {
engineLock.lock();
try {
return conContext.getHandshakeStatus(); return conContext.getHandshakeStatus();
} finally {
engineLock.unlock();
}
} }
@Override @Override
public synchronized void setUseClientMode(boolean mode) { public void setUseClientMode(boolean mode) {
engineLock.lock();
try {
conContext.setUseClientMode(mode); conContext.setUseClientMode(mode);
} finally {
engineLock.unlock();
}
} }
@Override @Override
public synchronized boolean getUseClientMode() { public boolean getUseClientMode() {
engineLock.lock();
try {
return conContext.sslConfig.isClientMode; return conContext.sslConfig.isClientMode;
} finally {
engineLock.unlock();
}
} }
@Override @Override
public synchronized void setNeedClientAuth(boolean need) { public void setNeedClientAuth(boolean need) {
engineLock.lock();
try {
conContext.sslConfig.clientAuthType = conContext.sslConfig.clientAuthType =
(need ? ClientAuthType.CLIENT_AUTH_REQUIRED : (need ? ClientAuthType.CLIENT_AUTH_REQUIRED :
ClientAuthType.CLIENT_AUTH_NONE); ClientAuthType.CLIENT_AUTH_NONE);
} finally {
engineLock.unlock();
}
} }
@Override @Override
public synchronized boolean getNeedClientAuth() { public boolean getNeedClientAuth() {
engineLock.lock();
try {
return (conContext.sslConfig.clientAuthType == return (conContext.sslConfig.clientAuthType ==
ClientAuthType.CLIENT_AUTH_REQUIRED); ClientAuthType.CLIENT_AUTH_REQUIRED);
} finally {
engineLock.unlock();
}
} }
@Override @Override
public synchronized void setWantClientAuth(boolean want) { public void setWantClientAuth(boolean want) {
engineLock.lock();
try {
conContext.sslConfig.clientAuthType = conContext.sslConfig.clientAuthType =
(want ? ClientAuthType.CLIENT_AUTH_REQUESTED : (want ? ClientAuthType.CLIENT_AUTH_REQUESTED :
ClientAuthType.CLIENT_AUTH_NONE); ClientAuthType.CLIENT_AUTH_NONE);
} finally {
engineLock.unlock();
}
} }
@Override @Override
public synchronized boolean getWantClientAuth() { public boolean getWantClientAuth() {
engineLock.lock();
try {
return (conContext.sslConfig.clientAuthType == return (conContext.sslConfig.clientAuthType ==
ClientAuthType.CLIENT_AUTH_REQUESTED); ClientAuthType.CLIENT_AUTH_REQUESTED);
} finally {
engineLock.unlock();
}
} }
@Override @Override
public synchronized void setEnableSessionCreation(boolean flag) { public void setEnableSessionCreation(boolean flag) {
engineLock.lock();
try {
conContext.sslConfig.enableSessionCreation = flag; conContext.sslConfig.enableSessionCreation = flag;
} finally {
engineLock.unlock();
}
} }
@Override @Override
public synchronized boolean getEnableSessionCreation() { public boolean getEnableSessionCreation() {
engineLock.lock();
try {
return conContext.sslConfig.enableSessionCreation; return conContext.sslConfig.enableSessionCreation;
} finally {
engineLock.unlock();
}
} }
@Override @Override
public synchronized SSLParameters getSSLParameters() { public SSLParameters getSSLParameters() {
engineLock.lock();
try {
return conContext.sslConfig.getSSLParameters(); return conContext.sslConfig.getSSLParameters();
} finally {
engineLock.unlock();
}
} }
@Override @Override
public synchronized void setSSLParameters(SSLParameters params) { public void setSSLParameters(SSLParameters params) {
engineLock.lock();
try {
conContext.sslConfig.setSSLParameters(params); conContext.sslConfig.setSSLParameters(params);
if (conContext.sslConfig.maximumPacketSize != 0) { if (conContext.sslConfig.maximumPacketSize != 0) {
conContext.outputRecord.changePacketSize( conContext.outputRecord.changePacketSize(
conContext.sslConfig.maximumPacketSize); conContext.sslConfig.maximumPacketSize);
} }
} finally {
engineLock.unlock();
}
} }
@Override @Override
public synchronized String getApplicationProtocol() { public String getApplicationProtocol() {
engineLock.lock();
try {
return conContext.applicationProtocol; return conContext.applicationProtocol;
} finally {
engineLock.unlock();
}
} }
@Override @Override
public synchronized String getHandshakeApplicationProtocol() { public String getHandshakeApplicationProtocol() {
engineLock.lock();
try {
return conContext.handshakeContext == null ? return conContext.handshakeContext == null ?
null : conContext.handshakeContext.applicationProtocol; null : conContext.handshakeContext.applicationProtocol;
} finally {
engineLock.unlock();
}
} }
@Override @Override
public synchronized void setHandshakeApplicationProtocolSelector( public void setHandshakeApplicationProtocolSelector(
BiFunction<SSLEngine, List<String>, String> selector) { BiFunction<SSLEngine, List<String>, String> selector) {
engineLock.lock();
try {
conContext.sslConfig.engineAPSelector = selector; conContext.sslConfig.engineAPSelector = selector;
} finally {
engineLock.unlock();
}
} }
@Override @Override
public synchronized BiFunction<SSLEngine, List<String>, String> public BiFunction<SSLEngine, List<String>, String>
getHandshakeApplicationProtocolSelector() { getHandshakeApplicationProtocolSelector() {
engineLock.lock();
try {
return conContext.sslConfig.engineAPSelector; return conContext.sslConfig.engineAPSelector;
} finally {
engineLock.unlock();
}
} }
@Override @Override
@ -909,10 +1059,11 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
* null, report back the Exception that happened in the delegated * null, report back the Exception that happened in the delegated
* task(s). * task(s).
*/ */
private synchronized void checkTaskThrown() throws SSLException { private void checkTaskThrown() throws SSLException {
Exception exc = null; Exception exc = null;
engineLock.lock();
try {
// First check the handshake context. // First check the handshake context.
HandshakeContext hc = conContext.handshakeContext; HandshakeContext hc = conContext.handshakeContext;
if ((hc != null) && (hc.delegatedThrown != null)) { 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 * hc.delegatedThrown and conContext.delegatedThrown are most
* the same, but it's possible we could have had a non-fatal * likely the same, but it's possible we could have had a non-fatal
* exception and thus the new HandshakeContext is still valid * exception and thus the new HandshakeContext is still valid
* (alert warning). If so, then we may have a secondary exception * (alert warning). If so, then we may have a secondary exception
* waiting to be reported from the TransportContext, so we will * waiting to be reported from the TransportContext, so we will
@ -942,6 +1093,9 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
conContext.delegatedThrown = null; conContext.delegatedThrown = null;
} }
} }
} finally {
engineLock.unlock();
}
// Anything to report? // Anything to report?
if (exc == null) { if (exc == null) {
@ -998,7 +1152,8 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
@Override @Override
public void run() { public void run() {
synchronized (engine) { engine.engineLock.lock();
try {
HandshakeContext hc = engine.conContext.handshakeContext; HandshakeContext hc = engine.conContext.handshakeContext;
if (hc == null || hc.delegatedActions.isEmpty()) { if (hc == null || hc.delegatedActions.isEmpty()) {
return; return;
@ -1055,6 +1210,8 @@ final class SSLEngineImpl extends SSLEngine implements SSLTransport {
if (hc != null) { if (hc != null) {
hc.taskDelegated = false; 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. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * 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 @Override
public synchronized void close() throws IOException { public void close() throws IOException {
recordLock.lock();
try {
if (!isClosed) { if (!isClosed) {
if (fragmenter != null && fragmenter.hasAlert()) { if (fragmenter != null && fragmenter.hasAlert()) {
isCloseWaiting = true; isCloseWaiting = true;
@ -59,6 +61,9 @@ final class SSLEngineOutputRecord extends OutputRecord implements SSLRecord {
super.close(); super.close();
} }
} }
} finally {
recordLock.unlock();
}
} }
boolean isClosed() { 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. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * 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.io.IOException;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.Socket; import java.net.Socket;
import java.util.concurrent.locks.ReentrantLock;
import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLServerSocket; import javax.net.ssl.SSLServerSocket;
@ -56,6 +57,7 @@ import javax.net.ssl.SSLServerSocket;
final class SSLServerSocketImpl extends SSLServerSocket { final class SSLServerSocketImpl extends SSLServerSocket {
private final SSLContextImpl sslContext; private final SSLContextImpl sslContext;
private final SSLConfiguration sslConfig; private final SSLConfiguration sslConfig;
private final ReentrantLock serverSocketLock = new ReentrantLock();
SSLServerSocketImpl(SSLContextImpl sslContext) throws IOException { SSLServerSocketImpl(SSLContextImpl sslContext) throws IOException {
@ -84,14 +86,24 @@ final class SSLServerSocketImpl extends SSLServerSocket {
} }
@Override @Override
public synchronized String[] getEnabledCipherSuites() { public String[] getEnabledCipherSuites() {
serverSocketLock.lock();
try {
return CipherSuite.namesOf(sslConfig.enabledCipherSuites); return CipherSuite.namesOf(sslConfig.enabledCipherSuites);
} finally {
serverSocketLock.unlock();
}
} }
@Override @Override
public synchronized void setEnabledCipherSuites(String[] suites) { public void setEnabledCipherSuites(String[] suites) {
serverSocketLock.lock();
try {
sslConfig.enabledCipherSuites = sslConfig.enabledCipherSuites =
CipherSuite.validValuesOf(suites); CipherSuite.validValuesOf(suites);
} finally {
serverSocketLock.unlock();
}
} }
@Override @Override
@ -106,47 +118,79 @@ final class SSLServerSocketImpl extends SSLServerSocket {
} }
@Override @Override
public synchronized String[] getEnabledProtocols() { public String[] getEnabledProtocols() {
serverSocketLock.lock();
try {
return ProtocolVersion.toStringArray(sslConfig.enabledProtocols); return ProtocolVersion.toStringArray(sslConfig.enabledProtocols);
} finally {
serverSocketLock.unlock();
}
} }
@Override @Override
public synchronized void setEnabledProtocols(String[] protocols) { public void setEnabledProtocols(String[] protocols) {
serverSocketLock.lock();
try {
if (protocols == null) { if (protocols == null) {
throw new IllegalArgumentException("Protocols cannot be null"); throw new IllegalArgumentException("Protocols cannot be null");
} }
sslConfig.enabledProtocols = ProtocolVersion.namesOf(protocols); sslConfig.enabledProtocols = ProtocolVersion.namesOf(protocols);
} finally {
serverSocketLock.unlock();
}
} }
@Override @Override
public synchronized void setNeedClientAuth(boolean need) { public void setNeedClientAuth(boolean need) {
serverSocketLock.lock();
try {
sslConfig.clientAuthType = sslConfig.clientAuthType =
(need ? ClientAuthType.CLIENT_AUTH_REQUIRED : (need ? ClientAuthType.CLIENT_AUTH_REQUIRED :
ClientAuthType.CLIENT_AUTH_NONE); ClientAuthType.CLIENT_AUTH_NONE);
} finally {
serverSocketLock.unlock();
}
} }
@Override @Override
public synchronized boolean getNeedClientAuth() { public boolean getNeedClientAuth() {
serverSocketLock.lock();
try {
return (sslConfig.clientAuthType == return (sslConfig.clientAuthType ==
ClientAuthType.CLIENT_AUTH_REQUIRED); ClientAuthType.CLIENT_AUTH_REQUIRED);
} finally {
serverSocketLock.unlock();
}
} }
@Override @Override
public synchronized void setWantClientAuth(boolean want) { public void setWantClientAuth(boolean want) {
serverSocketLock.lock();
try {
sslConfig.clientAuthType = sslConfig.clientAuthType =
(want ? ClientAuthType.CLIENT_AUTH_REQUESTED : (want ? ClientAuthType.CLIENT_AUTH_REQUESTED :
ClientAuthType.CLIENT_AUTH_NONE); ClientAuthType.CLIENT_AUTH_NONE);
} finally {
serverSocketLock.unlock();
}
} }
@Override @Override
public synchronized boolean getWantClientAuth() { public boolean getWantClientAuth() {
serverSocketLock.lock();
try {
return (sslConfig.clientAuthType == return (sslConfig.clientAuthType ==
ClientAuthType.CLIENT_AUTH_REQUESTED); ClientAuthType.CLIENT_AUTH_REQUESTED);
} finally {
serverSocketLock.unlock();
}
} }
@Override @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 * If we need to change the client mode and the enabled
* protocols and cipher suites haven't specifically been * protocols and cipher suites haven't specifically been
@ -168,31 +212,59 @@ final class SSLServerSocketImpl extends SSLServerSocket {
sslConfig.isClientMode = useClientMode; sslConfig.isClientMode = useClientMode;
} }
} finally {
serverSocketLock.unlock();
}
} }
@Override @Override
public synchronized boolean getUseClientMode() { public boolean getUseClientMode() {
serverSocketLock.lock();
try {
return sslConfig.isClientMode; return sslConfig.isClientMode;
} finally {
serverSocketLock.unlock();
}
} }
@Override @Override
public synchronized void setEnableSessionCreation(boolean flag) { public void setEnableSessionCreation(boolean flag) {
serverSocketLock.lock();
try {
sslConfig.enableSessionCreation = flag; sslConfig.enableSessionCreation = flag;
} finally {
serverSocketLock.unlock();
}
} }
@Override @Override
public synchronized boolean getEnableSessionCreation() { public boolean getEnableSessionCreation() {
serverSocketLock.lock();
try {
return sslConfig.enableSessionCreation; return sslConfig.enableSessionCreation;
} finally {
serverSocketLock.unlock();
}
} }
@Override @Override
public synchronized SSLParameters getSSLParameters() { public SSLParameters getSSLParameters() {
serverSocketLock.lock();
try {
return sslConfig.getSSLParameters(); return sslConfig.getSSLParameters();
} finally {
serverSocketLock.unlock();
}
} }
@Override @Override
public synchronized void setSSLParameters(SSLParameters params) { public void setSSLParameters(SSLParameters params) {
serverSocketLock.lock();
try {
sslConfig.setSSLParameters(params); sslConfig.setSSLParameters(params);
} finally {
serverSocketLock.unlock();
}
} }
@Override @Override

View File

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

View File

@ -38,6 +38,7 @@ import java.net.SocketException;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.List; import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BiFunction; import java.util.function.BiFunction;
import javax.net.ssl.HandshakeCompletedListener; import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.SSLException; import javax.net.ssl.SSLException;
@ -84,6 +85,9 @@ public final class SSLSocketImpl
private boolean isConnected = false; private boolean isConnected = false;
private volatile boolean tlsIsClosed = false; private volatile boolean tlsIsClosed = false;
private final ReentrantLock socketLock = new ReentrantLock();
private final ReentrantLock handshakeLock = new ReentrantLock();
/* /*
* Is the local name service trustworthy? * Is the local name service trustworthy?
* *
@ -292,14 +296,25 @@ public final class SSLSocketImpl
} }
@Override @Override
public synchronized String[] getEnabledCipherSuites() { public String[] getEnabledCipherSuites() {
return CipherSuite.namesOf(conContext.sslConfig.enabledCipherSuites); socketLock.lock();
try {
return CipherSuite.namesOf(
conContext.sslConfig.enabledCipherSuites);
} finally {
socketLock.unlock();
}
} }
@Override @Override
public synchronized void setEnabledCipherSuites(String[] suites) { public void setEnabledCipherSuites(String[] suites) {
socketLock.lock();
try {
conContext.sslConfig.enabledCipherSuites = conContext.sslConfig.enabledCipherSuites =
CipherSuite.validValuesOf(suites); CipherSuite.validValuesOf(suites);
} finally {
socketLock.unlock();
}
} }
@Override @Override
@ -309,19 +324,29 @@ public final class SSLSocketImpl
} }
@Override @Override
public synchronized String[] getEnabledProtocols() { public String[] getEnabledProtocols() {
socketLock.lock();
try {
return ProtocolVersion.toStringArray( return ProtocolVersion.toStringArray(
conContext.sslConfig.enabledProtocols); conContext.sslConfig.enabledProtocols);
} finally {
socketLock.unlock();
}
} }
@Override @Override
public synchronized void setEnabledProtocols(String[] protocols) { public void setEnabledProtocols(String[] protocols) {
if (protocols == null) { if (protocols == null) {
throw new IllegalArgumentException("Protocols cannot be null"); throw new IllegalArgumentException("Protocols cannot be null");
} }
socketLock.lock();
try {
conContext.sslConfig.enabledProtocols = conContext.sslConfig.enabledProtocols =
ProtocolVersion.namesOf(protocols); ProtocolVersion.namesOf(protocols);
} finally {
socketLock.unlock();
}
} }
@Override @Override
@ -341,29 +366,44 @@ public final class SSLSocketImpl
} }
@Override @Override
public synchronized SSLSession getHandshakeSession() { public SSLSession getHandshakeSession() {
socketLock.lock();
try {
return conContext.handshakeContext == null ? return conContext.handshakeContext == null ?
null : conContext.handshakeContext.handshakeSession; null : conContext.handshakeContext.handshakeSession;
} finally {
socketLock.unlock();
}
} }
@Override @Override
public synchronized void addHandshakeCompletedListener( public void addHandshakeCompletedListener(
HandshakeCompletedListener listener) { HandshakeCompletedListener listener) {
if (listener == null) { if (listener == null) {
throw new IllegalArgumentException("listener is null"); throw new IllegalArgumentException("listener is null");
} }
socketLock.lock();
try {
conContext.sslConfig.addHandshakeCompletedListener(listener); conContext.sslConfig.addHandshakeCompletedListener(listener);
} finally {
socketLock.unlock();
}
} }
@Override @Override
public synchronized void removeHandshakeCompletedListener( public void removeHandshakeCompletedListener(
HandshakeCompletedListener listener) { HandshakeCompletedListener listener) {
if (listener == null) { if (listener == null) {
throw new IllegalArgumentException("listener is null"); throw new IllegalArgumentException("listener is null");
} }
socketLock.lock();
try {
conContext.sslConfig.removeHandshakeCompletedListener(listener); conContext.sslConfig.removeHandshakeCompletedListener(listener);
} finally {
socketLock.unlock();
}
} }
@Override @Override
@ -377,7 +417,8 @@ public final class SSLSocketImpl
throw new SocketException("Socket has been closed or broken"); throw new SocketException("Socket has been closed or broken");
} }
synchronized (conContext) { // handshake lock handshakeLock.lock();
try {
// double check the context status // double check the context status
if (conContext.isBroken || conContext.isInboundClosed() || if (conContext.isBroken || conContext.isInboundClosed() ||
conContext.isOutboundClosed()) { conContext.isOutboundClosed()) {
@ -400,53 +441,95 @@ public final class SSLSocketImpl
} catch (Exception oe) { // including RuntimeException } catch (Exception oe) { // including RuntimeException
handleException(oe); handleException(oe);
} }
} finally {
handshakeLock.unlock();
} }
} }
@Override @Override
public synchronized void setUseClientMode(boolean mode) { public void setUseClientMode(boolean mode) {
socketLock.lock();
try {
conContext.setUseClientMode(mode); conContext.setUseClientMode(mode);
} finally {
socketLock.unlock();
}
} }
@Override @Override
public synchronized boolean getUseClientMode() { public boolean getUseClientMode() {
socketLock.lock();
try {
return conContext.sslConfig.isClientMode; return conContext.sslConfig.isClientMode;
} finally {
socketLock.unlock();
}
} }
@Override @Override
public synchronized void setNeedClientAuth(boolean need) { public void setNeedClientAuth(boolean need) {
socketLock.lock();
try {
conContext.sslConfig.clientAuthType = conContext.sslConfig.clientAuthType =
(need ? ClientAuthType.CLIENT_AUTH_REQUIRED : (need ? ClientAuthType.CLIENT_AUTH_REQUIRED :
ClientAuthType.CLIENT_AUTH_NONE); ClientAuthType.CLIENT_AUTH_NONE);
} finally {
socketLock.unlock();
}
} }
@Override @Override
public synchronized boolean getNeedClientAuth() { public boolean getNeedClientAuth() {
socketLock.lock();
try {
return (conContext.sslConfig.clientAuthType == return (conContext.sslConfig.clientAuthType ==
ClientAuthType.CLIENT_AUTH_REQUIRED); ClientAuthType.CLIENT_AUTH_REQUIRED);
} finally {
socketLock.unlock();
}
} }
@Override @Override
public synchronized void setWantClientAuth(boolean want) { public void setWantClientAuth(boolean want) {
socketLock.lock();
try {
conContext.sslConfig.clientAuthType = conContext.sslConfig.clientAuthType =
(want ? ClientAuthType.CLIENT_AUTH_REQUESTED : (want ? ClientAuthType.CLIENT_AUTH_REQUESTED :
ClientAuthType.CLIENT_AUTH_NONE); ClientAuthType.CLIENT_AUTH_NONE);
} finally {
socketLock.unlock();
}
} }
@Override @Override
public synchronized boolean getWantClientAuth() { public boolean getWantClientAuth() {
socketLock.lock();
try {
return (conContext.sslConfig.clientAuthType == return (conContext.sslConfig.clientAuthType ==
ClientAuthType.CLIENT_AUTH_REQUESTED); ClientAuthType.CLIENT_AUTH_REQUESTED);
} finally {
socketLock.unlock();
}
} }
@Override @Override
public synchronized void setEnableSessionCreation(boolean flag) { public void setEnableSessionCreation(boolean flag) {
socketLock.lock();
try {
conContext.sslConfig.enableSessionCreation = flag; conContext.sslConfig.enableSessionCreation = flag;
} finally {
socketLock.unlock();
}
} }
@Override @Override
public synchronized boolean getEnableSessionCreation() { public boolean getEnableSessionCreation() {
socketLock.lock();
try {
return conContext.sslConfig.enableSessionCreation; return conContext.sslConfig.enableSessionCreation;
} finally {
socketLock.unlock();
}
} }
@Override @Override
@ -535,8 +618,9 @@ public final class SSLSocketImpl
// Need a lock here so that the user_canceled alert and the // Need a lock here so that the user_canceled alert and the
// close_notify alert can be delivered together. // close_notify alert can be delivered together.
conContext.outputRecord.recordLock.lock();
try {
try { try {
synchronized (conContext.outputRecord) {
// send a user_canceled alert if needed. // send a user_canceled alert if needed.
if (useUserCanceled) { if (useUserCanceled) {
conContext.warning(Alert.USER_CANCELED); conContext.warning(Alert.USER_CANCELED);
@ -544,7 +628,6 @@ public final class SSLSocketImpl
// send a close_notify alert // send a close_notify alert
conContext.warning(Alert.CLOSE_NOTIFY); conContext.warning(Alert.CLOSE_NOTIFY);
}
} finally { } finally {
if (!conContext.isOutboundClosed()) { if (!conContext.isOutboundClosed()) {
conContext.outputRecord.close(); conContext.outputRecord.close();
@ -554,6 +637,9 @@ public final class SSLSocketImpl
super.shutdownOutput(); super.shutdownOutput();
} }
} }
} finally {
conContext.outputRecord.recordLock.unlock();
}
if (!isInputShutdown()) { if (!isInputShutdown()) {
bruteForceCloseInput(hasCloseReceipt); bruteForceCloseInput(hasCloseReceipt);
@ -681,7 +767,9 @@ public final class SSLSocketImpl
} }
@Override @Override
public synchronized InputStream getInputStream() throws IOException { public InputStream getInputStream() throws IOException {
socketLock.lock();
try {
if (isClosed()) { if (isClosed()) {
throw new SocketException("Socket is closed"); throw new SocketException("Socket is closed");
} }
@ -695,6 +783,9 @@ public final class SSLSocketImpl
} }
return appInput; return appInput;
} finally {
socketLock.unlock();
}
} }
private void ensureNegotiated() throws IOException { private void ensureNegotiated() throws IOException {
@ -703,7 +794,8 @@ public final class SSLSocketImpl
return; return;
} }
synchronized (conContext) { // handshake lock handshakeLock.lock();
try {
// double check the context status // double check the context status
if (conContext.isNegotiated || conContext.isBroken || if (conContext.isNegotiated || conContext.isBroken ||
conContext.isInboundClosed() || conContext.isInboundClosed() ||
@ -712,6 +804,8 @@ public final class SSLSocketImpl
} }
startHandshake(); startHandshake();
} finally {
handshakeLock.unlock();
} }
} }
@ -729,6 +823,9 @@ public final class SSLSocketImpl
// Is application data available in the stream? // Is application data available in the stream?
private volatile boolean appDataIsAvailable; private volatile boolean appDataIsAvailable;
// reading lock
private final ReentrantLock readLock = new ReentrantLock();
AppInputStream() { AppInputStream() {
this.appDataIsAvailable = false; this.appDataIsAvailable = false;
this.buffer = ByteBuffer.allocate(4096); this.buffer = ByteBuffer.allocate(4096);
@ -807,7 +904,8 @@ public final class SSLSocketImpl
// //
// Note that the receiving and processing of post-handshake message // Note that the receiving and processing of post-handshake message
// are also synchronized with the read lock. // are also synchronized with the read lock.
synchronized (this) { readLock.lock();
try {
int remains = available(); int remains = available();
if (remains > 0) { if (remains > 0) {
int howmany = Math.min(remains, len); int howmany = Math.min(remains, len);
@ -839,6 +937,8 @@ public final class SSLSocketImpl
// dummy for compiler // dummy for compiler
return -1; return -1;
} }
} finally {
readLock.unlock();
} }
} }
@ -850,11 +950,13 @@ public final class SSLSocketImpl
* things simpler. * things simpler.
*/ */
@Override @Override
public synchronized long skip(long n) throws IOException { public long skip(long n) throws IOException {
// dummy array used to implement skip() // dummy array used to implement skip()
byte[] skipArray = new byte[256]; byte[] skipArray = new byte[256];
long skipped = 0; long skipped = 0;
readLock.lock();
try {
while (n > 0) { while (n > 0) {
int len = (int)Math.min(n, skipArray.length); int len = (int)Math.min(n, skipArray.length);
int r = read(skipArray, 0, len); int r = read(skipArray, 0, len);
@ -864,6 +966,9 @@ public final class SSLSocketImpl
n -= r; n -= r;
skipped += r; skipped += r;
} }
} finally {
readLock.unlock();
}
return skipped; return skipped;
} }
@ -910,8 +1015,18 @@ public final class SSLSocketImpl
* Try the best to use up the input records so as to close the * Try the best to use up the input records so as to close the
* socket gracefully, without impact the performance too much. * socket gracefully, without impact the performance too much.
*/ */
private synchronized void deplete() { private void deplete() {
if (!conContext.isInboundClosed()) { if (conContext.isInboundClosed()) {
return;
}
readLock.lock();
try {
// double check
if (conContext.isInboundClosed()) {
return;
}
if (!(conContext.inputRecord instanceof SSLSocketInputRecord)) { if (!(conContext.inputRecord instanceof SSLSocketInputRecord)) {
return; return;
} }
@ -927,12 +1042,16 @@ public final class SSLSocketImpl
"input stream close depletion failed", ioe); "input stream close depletion failed", ioe);
} }
} }
} finally {
readLock.unlock();
} }
} }
} }
@Override @Override
public synchronized OutputStream getOutputStream() throws IOException { public OutputStream getOutputStream() throws IOException {
socketLock.lock();
try {
if (isClosed()) { if (isClosed()) {
throw new SocketException("Socket is closed"); throw new SocketException("Socket is closed");
} }
@ -946,6 +1065,9 @@ public final class SSLSocketImpl
} }
return appOutput; return appOutput;
} finally {
socketLock.unlock();
}
} }
@ -1035,44 +1157,74 @@ public final class SSLSocketImpl
} }
@Override @Override
public synchronized SSLParameters getSSLParameters() { public SSLParameters getSSLParameters() {
socketLock.lock();
try {
return conContext.sslConfig.getSSLParameters(); return conContext.sslConfig.getSSLParameters();
} finally {
socketLock.unlock();
}
} }
@Override @Override
public synchronized void setSSLParameters(SSLParameters params) { public void setSSLParameters(SSLParameters params) {
socketLock.lock();
try {
conContext.sslConfig.setSSLParameters(params); conContext.sslConfig.setSSLParameters(params);
if (conContext.sslConfig.maximumPacketSize != 0) { if (conContext.sslConfig.maximumPacketSize != 0) {
conContext.outputRecord.changePacketSize( conContext.outputRecord.changePacketSize(
conContext.sslConfig.maximumPacketSize); conContext.sslConfig.maximumPacketSize);
} }
} finally {
socketLock.unlock();
}
} }
@Override @Override
public synchronized String getApplicationProtocol() { public String getApplicationProtocol() {
socketLock.lock();
try {
return conContext.applicationProtocol; return conContext.applicationProtocol;
} finally {
socketLock.unlock();
}
} }
@Override @Override
public synchronized String getHandshakeApplicationProtocol() { public String getHandshakeApplicationProtocol() {
socketLock.lock();
try {
if (conContext.handshakeContext != null) { if (conContext.handshakeContext != null) {
return conContext.handshakeContext.applicationProtocol; return conContext.handshakeContext.applicationProtocol;
} }
} finally {
socketLock.unlock();
}
return null; return null;
} }
@Override @Override
public synchronized void setHandshakeApplicationProtocolSelector( public void setHandshakeApplicationProtocolSelector(
BiFunction<SSLSocket, List<String>, String> selector) { BiFunction<SSLSocket, List<String>, String> selector) {
socketLock.lock();
try {
conContext.sslConfig.socketAPSelector = selector; conContext.sslConfig.socketAPSelector = selector;
} finally {
socketLock.unlock();
}
} }
@Override @Override
public synchronized BiFunction<SSLSocket, List<String>, String> public BiFunction<SSLSocket, List<String>, String>
getHandshakeApplicationProtocolSelector() { getHandshakeApplicationProtocolSelector() {
socketLock.lock();
try {
return conContext.sslConfig.socketAPSelector; return conContext.sslConfig.socketAPSelector;
} finally {
socketLock.unlock();
}
} }
/** /**
@ -1142,8 +1294,11 @@ public final class SSLSocketImpl
try { try {
Plaintext plainText; Plaintext plainText;
synchronized (this) { socketLock.lock();
try {
plainText = decode(buffer); plainText = decode(buffer);
} finally {
socketLock.unlock();
} }
if (plainText.contentType == ContentType.APPLICATION_DATA.id && if (plainText.contentType == ContentType.APPLICATION_DATA.id &&
buffer.position() > 0) { buffer.position() > 0) {
@ -1222,9 +1377,12 @@ public final class SSLSocketImpl
* *
* Called by connect, the layered constructor, and SSLServerSocket. * 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. // 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()) { if (peerHost == null || peerHost.isEmpty()) {
boolean useNameService = boolean useNameService =
trustNameService && conContext.sslConfig.isClientMode; trustNameService && conContext.sslConfig.isClientMode;
@ -1243,6 +1401,9 @@ public final class SSLSocketImpl
conContext.outputRecord.setDeliverStream(sockOutput); conContext.outputRecord.setDeliverStream(sockOutput);
this.isConnected = true; this.isConnected = true;
} finally {
socketLock.unlock();
}
} }
private void useImplicitHost(boolean useNameService) { private void useImplicitHost(boolean useNameService) {
@ -1288,11 +1449,16 @@ public final class SSLSocketImpl
// Please NOTE that this method MUST be called before calling to // Please NOTE that this method MUST be called before calling to
// SSLSocket.setSSLParameters(). Otherwise, the {@code host} parameter // SSLSocket.setSSLParameters(). Otherwise, the {@code host} parameter
// may override SNIHostName in the customized server name indication. // 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.peerHost = host;
this.conContext.sslConfig.serverNames = this.conContext.sslConfig.serverNames =
Utilities.addToSNIServerNameList( Utilities.addToSNIServerNameList(
conContext.sslConfig.serverNames, host); 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. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * 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 @Override
synchronized void encodeAlert( void encodeAlert(byte level, byte description) throws IOException {
byte level, byte description) throws IOException { recordLock.lock();
try {
if (isClosed()) { if (isClosed()) {
if (SSLLogger.isOn && SSLLogger.isOn("ssl")) { if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
SSLLogger.warning("outbound has closed, ignore outbound " + SSLLogger.warning("outbound has closed, ignore outbound " +
@ -88,11 +89,16 @@ final class SSLSocketOutputRecord extends OutputRecord implements SSLRecord {
// reset the internal buffer // reset the internal buffer
count = 0; count = 0;
} finally {
recordLock.unlock();
}
} }
@Override @Override
synchronized void encodeHandshake(byte[] source, void encodeHandshake(byte[] source,
int offset, int length) throws IOException { int offset, int length) throws IOException {
recordLock.lock();
try {
if (isClosed()) { if (isClosed()) {
if (SSLLogger.isOn && SSLLogger.isOn("ssl")) { if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
SSLLogger.warning("outbound has closed, ignore outbound " + SSLLogger.warning("outbound has closed, ignore outbound " +
@ -117,7 +123,8 @@ final class SSLSocketOutputRecord extends OutputRecord implements SSLRecord {
ByteBuffer v2ClientHello = encodeV2ClientHello( ByteBuffer v2ClientHello = encodeV2ClientHello(
source, (offset + 4), (length - 4)); 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(); int limit = v2ClientHello.limit();
handshakeHash.deliver(record, 2, (limit - 2)); handshakeHash.deliver(record, 2, (limit - 2));
@ -196,10 +203,15 @@ final class SSLSocketOutputRecord extends OutputRecord implements SSLRecord {
// reset the internal buffer // reset the internal buffer
count = position; count = position;
} }
} finally {
recordLock.unlock();
}
} }
@Override @Override
synchronized void encodeChangeCipherSpec() throws IOException { void encodeChangeCipherSpec() throws IOException {
recordLock.lock();
try {
if (isClosed()) { if (isClosed()) {
if (SSLLogger.isOn && SSLLogger.isOn("ssl")) { if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
SSLLogger.warning("outbound has closed, ignore outbound " + SSLLogger.warning("outbound has closed, ignore outbound " +
@ -228,10 +240,15 @@ final class SSLSocketOutputRecord extends OutputRecord implements SSLRecord {
// reset the internal buffer // reset the internal buffer
count = 0; count = 0;
} finally {
recordLock.unlock();
}
} }
@Override @Override
public synchronized void flush() throws IOException { public void flush() throws IOException {
recordLock.lock();
try {
int position = headerSize + writeCipher.getExplicitNonceSize(); int position = headerSize + writeCipher.getExplicitNonceSize();
if (count <= position) { if (count <= position) {
return; return;
@ -258,13 +275,18 @@ final class SSLSocketOutputRecord extends OutputRecord implements SSLRecord {
// reset the internal buffer // reset the internal buffer
count = 0; // DON'T use position count = 0; // DON'T use position
} finally {
recordLock.unlock();
}
} }
@Override @Override
synchronized void deliver( void deliver(byte[] source, int offset, int length) throws IOException {
byte[] source, int offset, int length) throws IOException { recordLock.lock();
try {
if (isClosed()) { if (isClosed()) {
throw new SocketException("Connection or outbound has been closed"); throw new SocketException(
"Connection or outbound has been closed");
} }
if (writeCipher.authenticator.seqNumOverflow()) { if (writeCipher.authenticator.seqNumOverflow()) {
@ -282,8 +304,8 @@ final class SSLSocketOutputRecord extends OutputRecord implements SSLRecord {
int fragLen; int fragLen;
if (packetSize > 0) { if (packetSize > 0) {
fragLen = Math.min(maxRecordSize, packetSize); fragLen = Math.min(maxRecordSize, packetSize);
fragLen = fragLen = writeCipher.calculateFragmentSize(
writeCipher.calculateFragmentSize(fragLen, headerSize); fragLen, headerSize);
fragLen = Math.min(fragLen, Record.maxDataSize); fragLen = Math.min(fragLen, Record.maxDataSize);
} else { } else {
@ -314,7 +336,8 @@ final class SSLSocketOutputRecord extends OutputRecord implements SSLRecord {
} }
// Encrypt the fragment and wrap up a record. // 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 // deliver this message
deliverStream.write(buf, 0, count); // may throw IOException deliverStream.write(buf, 0, count); // may throw IOException
@ -334,11 +357,19 @@ final class SSLSocketOutputRecord extends OutputRecord implements SSLRecord {
offset += fragLen; offset += fragLen;
} }
} finally {
recordLock.unlock();
}
} }
@Override @Override
synchronized void setDeliverStream(OutputStream outputStream) { void setDeliverStream(OutputStream outputStream) {
recordLock.lock();
try {
this.deliverStream = outputStream; 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. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * 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. * Basic container for credentials implemented as an inner class.
*/ */
private static class X509Credentials { private static class X509Credentials {
PrivateKey privateKey; final PrivateKey privateKey;
X509Certificate[] certificates; final X509Certificate[] certificates;
private Set<X500Principal> issuerX500Principals; private final Set<X500Principal> issuerX500Principals;
X509Credentials(PrivateKey privateKey, X509Certificate[] certificates) { X509Credentials(PrivateKey privateKey, X509Certificate[] certificates) {
// assert privateKey and certificates != null // assert privateKey and certificates != null
this.privateKey = privateKey; this.privateKey = privateKey;
this.certificates = certificates; this.certificates = certificates;
this.issuerX500Principals = new HashSet<>(certificates.length);
for (X509Certificate certificate : certificates) {
issuerX500Principals.add(certificate.getIssuerX500Principal());
}
} }
synchronized Set<X500Principal> getIssuerX500Principals() { 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());
}
}
return issuerX500Principals; 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. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -496,13 +496,16 @@ class TransportContext implements ConnectionContext {
} }
if (needCloseNotify) { if (needCloseNotify) {
synchronized (outputRecord) { outputRecord.recordLock.lock();
try {
try { try {
// send a close_notify alert // send a close_notify alert
warning(Alert.CLOSE_NOTIFY); warning(Alert.CLOSE_NOTIFY);
} finally { } finally {
outputRecord.close(); 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 // Need a lock here so that the user_canceled alert and the
// close_notify alert can be delivered together. // close_notify alert can be delivered together.
synchronized (outputRecord) { outputRecord.recordLock.lock();
try {
try { try {
// send a user_canceled alert if needed. // send a user_canceled alert if needed.
if (useUserCanceled) { if (useUserCanceled) {
@ -553,6 +557,8 @@ class TransportContext implements ConnectionContext {
} finally { } finally {
outputRecord.close(); outputRecord.close();
} }
} finally {
outputRecord.recordLock.unlock();
} }
} }

View File

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

View File

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