1 /*
   2  * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 
  27 package sun.security.ssl;
  28 
  29 import java.io.*;
  30 import java.nio.*;
  31 import java.net.*;
  32 import java.security.GeneralSecurityException;
  33 import java.security.AccessController;
  34 import java.security.AccessControlContext;
  35 import java.security.PrivilegedAction;
  36 import java.security.AlgorithmConstraints;
  37 import java.util.*;
  38 import java.util.concurrent.TimeUnit;
  39 import java.util.concurrent.locks.ReentrantLock;
  40 import java.util.function.BiFunction;
  41 
  42 import javax.crypto.BadPaddingException;
  43 import javax.net.ssl.*;
  44 
  45 import jdk.internal.misc.JavaNetInetAddressAccess;
  46 import jdk.internal.misc.SharedSecrets;
  47 
  48 /**
  49  * Implementation of an SSL socket.  This is a normal connection type
  50  * socket, implementing SSL over some lower level socket, such as TCP.
  51  * Because it is layered over some lower level socket, it MUST override
  52  * all default socket methods.
  53  *
  54  * <P> This API offers a non-traditional option for establishing SSL
  55  * connections.  You may first establish the connection directly, then pass
  56  * that connection to the SSL socket constructor with a flag saying which
  57  * role should be taken in the handshake protocol.  (The two ends of the
  58  * connection must not choose the same role!)  This allows setup of SSL
  59  * proxying or tunneling, and also allows the kind of "role reversal"
  60  * that is required for most FTP data transfers.
  61  *
  62  * @see javax.net.ssl.SSLSocket
  63  * @see SSLServerSocket
  64  *
  65  * @author David Brownell
  66  */
  67 public final class SSLSocketImpl extends BaseSSLSocketImpl {
  68 
  69     /*
  70      * ERROR HANDLING GUIDELINES
  71      * (which exceptions to throw and catch and which not to throw and catch)
  72      *
  73      * . if there is an IOException (SocketException) when accessing the
  74      *   underlying Socket, pass it through
  75      *
  76      * . do not throw IOExceptions, throw SSLExceptions (or a subclass)
  77      *
  78      * . for internal errors (things that indicate a bug in JSSE or a
  79      *   grossly misconfigured J2RE), throw either an SSLException or
  80      *   a RuntimeException at your convenience.
  81      *
  82      * . handshaking code (Handshaker or HandshakeMessage) should generally
  83      *   pass through exceptions, but can handle them if they know what to
  84      *   do.
  85      *
  86      * . exception chaining should be used for all new code. If you happen
  87      *   to touch old code that does not use chaining, you should change it.
  88      *
  89      * . there is a top level exception handler that sits at all entry
  90      *   points from application code to SSLSocket read/write code. It
  91      *   makes sure that all errors are handled (see handleException()).
  92      *
  93      * . JSSE internal code should generally not call close(), call
  94      *   closeInternal().
  95      */
  96 
  97     /*
  98      * There's a state machine associated with each connection, which
  99      * among other roles serves to negotiate session changes.
 100      *
 101      * - START with constructor, until the TCP connection's around.
 102      * - HANDSHAKE picks session parameters before allowing traffic.
 103      *          There are many substates due to sequencing requirements
 104      *          for handshake messages.
 105      * - DATA may be transmitted.
 106      * - RENEGOTIATE state allows concurrent data and handshaking
 107      *          traffic ("same" substates as HANDSHAKE), and terminates
 108      *          in selection of new session (and connection) parameters
 109      * - ERROR state immediately precedes abortive disconnect.
 110      * - SENT_CLOSE sent a close_notify to the peer. For layered,
 111      *          non-autoclose socket, must now read close_notify
 112      *          from peer before closing the connection. For nonlayered or
 113      *          non-autoclose socket, close connection and go onto
 114      *          cs_CLOSED state.
 115      * - CLOSED after sending close_notify alert, & socket is closed.
 116      *          SSL connection objects are not reused.
 117      * - APP_CLOSED once the application calls close(). Then it behaves like
 118      *          a closed socket, e.g.. getInputStream() throws an Exception.
 119      *
 120      * State affects what SSL record types may legally be sent:
 121      *
 122      * - Handshake ... only in HANDSHAKE and RENEGOTIATE states
 123      * - App Data ... only in DATA and RENEGOTIATE states
 124      * - Alert ... in HANDSHAKE, DATA, RENEGOTIATE
 125      *
 126      * Re what may be received:  same as what may be sent, except that
 127      * HandshakeRequest handshaking messages can come from servers even
 128      * in the application data state, to request entry to RENEGOTIATE.
 129      *
 130      * The state machine within HANDSHAKE and RENEGOTIATE states controls
 131      * the pending session, not the connection state, until the change
 132      * cipher spec and "Finished" handshake messages are processed and
 133      * make the "new" session become the current one.
 134      *
 135      * NOTE: details of the SMs always need to be nailed down better.
 136      * The text above illustrates the core ideas.
 137      *
 138      *                +---->-------+------>--------->-------+
 139      *                |            |                        |
 140      *     <-----<    ^            ^  <-----<               v
 141      *START>----->HANDSHAKE>----->DATA>----->RENEGOTIATE  SENT_CLOSE
 142      *                v            v               v        |   |
 143      *                |            |               |        |   v
 144      *                +------------+---------------+        v ERROR
 145      *                |                                     |   |
 146      *                v                                     |   |
 147      *               ERROR>------>----->CLOSED<--------<----+-- +
 148      *                                     |
 149      *                                     v
 150      *                                 APP_CLOSED
 151      *
 152      * ALSO, note that the purpose of handshaking (renegotiation is
 153      * included) is to assign a different, and perhaps new, session to
 154      * the connection.  The SSLv3 spec is a bit confusing on that new
 155      * protocol feature.
 156      */
 157     private static final int    cs_START = 0;
 158     private static final int    cs_HANDSHAKE = 1;
 159     private static final int    cs_DATA = 2;
 160     private static final int    cs_RENEGOTIATE = 3;
 161     private static final int    cs_ERROR = 4;
 162     private static final int    cs_SENT_CLOSE = 5;
 163     private static final int    cs_CLOSED = 6;
 164     private static final int    cs_APP_CLOSED = 7;
 165 
 166     /*
 167      * Drives the protocol state machine.
 168      */
 169     private volatile int        connectionState;
 170 
 171     /*
 172      * Flag indicating if the next record we receive MUST be a Finished
 173      * message. Temporarily set during the handshake to ensure that
 174      * a change cipher spec message is followed by a finished message.
 175      */
 176     private boolean             expectingFinished;
 177 
 178     /*
 179      * For improved diagnostics, we detail connection closure
 180      * If the socket is closed (connectionState >= cs_ERROR),
 181      * closeReason != null indicates if the socket was closed
 182      * because of an error or because or normal shutdown.
 183      */
 184     private SSLException        closeReason;
 185 
 186     /*
 187      * Per-connection private state that doesn't change when the
 188      * session is changed.
 189      */
 190     private ClientAuthType      doClientAuth =
 191                                         ClientAuthType.CLIENT_AUTH_NONE;
 192     private boolean             roleIsServer;
 193     private boolean             enableSessionCreation = true;
 194     private String              host;
 195     private boolean             autoClose = true;
 196     private AccessControlContext acc;
 197 
 198     // The cipher suites enabled for use on this connection.
 199     private CipherSuiteList     enabledCipherSuites;
 200 
 201     // The endpoint identification protocol
 202     private String              identificationProtocol = null;
 203 
 204     // The cryptographic algorithm constraints
 205     private AlgorithmConstraints    algorithmConstraints = null;
 206 
 207     // The server name indication and matchers
 208     List<SNIServerName>         serverNames =
 209                                     Collections.<SNIServerName>emptyList();
 210     Collection<SNIMatcher>      sniMatchers =
 211                                     Collections.<SNIMatcher>emptyList();
 212 
 213     // Is the serverNames set to empty with SSLParameters.setServerNames()?
 214     private boolean             noSniExtension = false;
 215 
 216     // Is the sniMatchers set to empty with SSLParameters.setSNIMatchers()?
 217     private boolean             noSniMatcher = false;
 218 
 219     // Configured application protocol values
 220     String[] applicationProtocols = new String[0];
 221 
 222     // Negotiated application protocol value.
 223     //
 224     // The value under negotiation will be obtained from handshaker.
 225     String applicationProtocol = null;
 226 
 227     // Callback function that selects the application protocol value during
 228     // the SSL/TLS handshake.
 229     BiFunction<SSLSocket, List<String>, String> applicationProtocolSelector;
 230 
 231     /*
 232      * READ ME * READ ME * READ ME * READ ME * READ ME * READ ME *
 233      * IMPORTANT STUFF TO UNDERSTANDING THE SYNCHRONIZATION ISSUES.
 234      * READ ME * READ ME * READ ME * READ ME * READ ME * READ ME *
 235      *
 236      * There are several locks here.
 237      *
 238      * The primary lock is the per-instance lock used by
 239      * synchronized(this) and the synchronized methods.  It controls all
 240      * access to things such as the connection state and variables which
 241      * affect handshaking.  If we are inside a synchronized method, we
 242      * can access the state directly, otherwise, we must use the
 243      * synchronized equivalents.
 244      *
 245      * The handshakeLock is used to ensure that only one thread performs
 246      * the *complete initial* handshake.  If someone is handshaking, any
 247      * stray application or startHandshake() requests who find the
 248      * connection state is cs_HANDSHAKE will stall on handshakeLock
 249      * until handshaking is done.  Once the handshake is done, we either
 250      * succeeded or failed, but we can never go back to the cs_HANDSHAKE
 251      * or cs_START state again.
 252      *
 253      * Note that the read/write() calls here in SSLSocketImpl are not
 254      * obviously synchronized.  In fact, it's very nonintuitive, and
 255      * requires careful examination of code paths.  Grab some coffee,
 256      * and be careful with any code changes.
 257      *
 258      * There can be only three threads active at a time in the I/O
 259      * subsection of this class.
 260      *    1.  startHandshake
 261      *    2.  AppInputStream
 262      *    3.  AppOutputStream
 263      * One thread could call startHandshake().
 264      * AppInputStream/AppOutputStream read() and write() calls are each
 265      * synchronized on 'this' in their respective classes, so only one
 266      * app. thread will be doing a SSLSocketImpl.read() or .write()'s at
 267      * a time.
 268      *
 269      * If handshaking is required (state cs_HANDSHAKE), and
 270      * getConnectionState() for some/all threads returns cs_HANDSHAKE,
 271      * only one can grab the handshakeLock, and the rest will stall
 272      * either on getConnectionState(), or on the handshakeLock if they
 273      * happen to successfully race through the getConnectionState().
 274      *
 275      * If a writer is doing the initial handshaking, it must create a
 276      * temporary reader to read the responses from the other side.  As a
 277      * side-effect, the writer's reader will have priority over any
 278      * other reader.  However, the writer's reader is not allowed to
 279      * consume any application data.  When handshakeLock is finally
 280      * released, we either have a cs_DATA connection, or a
 281      * cs_CLOSED/cs_ERROR socket.
 282      *
 283      * The writeLock is held while writing on a socket connection and
 284      * also to protect the MAC and cipher for their direction.  The
 285      * writeLock is package private for Handshaker which holds it while
 286      * writing the ChangeCipherSpec message.
 287      *
 288      * To avoid the problem of a thread trying to change operational
 289      * modes on a socket while handshaking is going on, we synchronize
 290      * on 'this'.  If handshaking has not started yet, we tell the
 291      * handshaker to change its mode.  If handshaking has started,
 292      * we simply store that request until the next pending session
 293      * is created, at which time the new handshaker's state is set.
 294      *
 295      * The readLock is held during readRecord(), which is responsible
 296      * for reading an SSLInputRecord, decrypting it, and processing it.
 297      * The readLock ensures that these three steps are done atomically
 298      * and that once started, no other thread can block on SSLInputRecord.read.
 299      * This is necessary so that processing of close_notify alerts
 300      * from the peer are handled properly.
 301      */
 302     private final Object        handshakeLock = new Object();
 303     final ReentrantLock         writeLock = new ReentrantLock();
 304     private final Object        readLock = new Object();
 305 
 306     InputRecord                 inputRecord;
 307     OutputRecord                outputRecord;
 308 
 309     /*
 310      * security parameters for secure renegotiation.
 311      */
 312     private boolean             secureRenegotiation;
 313     private byte[]              clientVerifyData;
 314     private byte[]              serverVerifyData;
 315 
 316     /*
 317      * The authentication context holds all information used to establish
 318      * who this end of the connection is (certificate chains, private keys,
 319      * etc) and who is trusted (e.g. as CAs or websites).
 320      */
 321     private SSLContextImpl      sslContext;
 322 
 323 
 324     /*
 325      * This connection is one of (potentially) many associated with
 326      * any given session.  The output of the handshake protocol is a
 327      * new session ... although all the protocol description talks
 328      * about changing the cipher spec (and it does change), in fact
 329      * that's incidental since it's done by changing everything that
 330      * is associated with a session at the same time.  (TLS/IETF may
 331      * change that to add client authentication w/o new key exchg.)
 332      */
 333     private Handshaker                  handshaker;
 334     private SSLSessionImpl              sess;
 335     private volatile SSLSessionImpl     handshakeSession;
 336 
 337 
 338     /*
 339      * If anyone wants to get notified about handshake completions,
 340      * they'll show up on this list.
 341      */
 342     private HashMap<HandshakeCompletedListener, AccessControlContext>
 343                                                         handshakeListeners;
 344 
 345     /*
 346      * Reuse the same internal input/output streams.
 347      */
 348     private InputStream         sockInput;
 349     private OutputStream        sockOutput;
 350 
 351 
 352     /*
 353      * These input and output streams block their data in SSL records,
 354      * and usually arrange integrity and privacy protection for those
 355      * records.  The guts of the SSL protocol are wrapped up in these
 356      * streams, and in the handshaking that establishes the details of
 357      * that integrity and privacy protection.
 358      */
 359     private AppInputStream      input;
 360     private AppOutputStream     output;
 361 
 362     /*
 363      * The protocol versions enabled for use on this connection.
 364      *
 365      * Note: we support a pseudo protocol called SSLv2Hello which when
 366      * set will result in an SSL v2 Hello being sent with SSL (version 3.0)
 367      * or TLS (version 3.1, 3.2, etc.) version info.
 368      */
 369     private ProtocolList enabledProtocols;
 370 
 371     /*
 372      * The SSL version associated with this connection.
 373      */
 374     private ProtocolVersion     protocolVersion = ProtocolVersion.DEFAULT_TLS;
 375 
 376     /* Class and subclass dynamic debugging support */
 377     private static final Debug debug = Debug.getInstance("ssl");
 378 
 379     /*
 380      * Whether local cipher suites preference in server side should be
 381      * honored during handshaking?
 382      */
 383     private boolean preferLocalCipherSuites = false;
 384 
 385     /*
 386      * The maximum expected network packet size for SSL/TLS/DTLS records.
 387      */
 388     private int maximumPacketSize = 0;
 389 
 390     /*
 391      * Is the local name service trustworthy?
 392      *
 393      * If the local name service is not trustworthy, reverse host name
 394      * resolution should not be performed for endpoint identification.
 395      */
 396     static final boolean trustNameService =
 397             Debug.getBooleanProperty("jdk.tls.trustNameService", false);
 398 
 399     static final int retryCloseAttempts =
 400             Debug.getIntegerProperty("jdk.tls.closeRetries", 5);
 401 
 402     //
 403     // CONSTRUCTORS AND INITIALIZATION CODE
 404     //
 405 
 406     /**
 407      * Constructs an SSL connection to a named host at a specified port,
 408      * using the authentication context provided.  This endpoint acts as
 409      * the client, and may rejoin an existing SSL session if appropriate.
 410      *
 411      * @param context authentication context to use
 412      * @param host name of the host with which to connect
 413      * @param port number of the server's port
 414      */
 415     SSLSocketImpl(SSLContextImpl context, String host, int port)
 416             throws IOException, UnknownHostException {
 417         super();
 418         this.host = host;
 419         this.serverNames =
 420             Utilities.addToSNIServerNameList(this.serverNames, this.host);
 421         init(context, false);
 422         SocketAddress socketAddress =
 423                host != null ? new InetSocketAddress(host, port) :
 424                new InetSocketAddress(InetAddress.getByName(null), port);
 425         connect(socketAddress, 0);
 426     }
 427 
 428 
 429     /**
 430      * Constructs an SSL connection to a server at a specified address.
 431      * and TCP port, using the authentication context provided.  This
 432      * endpoint acts as the client, and may rejoin an existing SSL session
 433      * if appropriate.
 434      *
 435      * @param context authentication context to use
 436      * @param address the server's host
 437      * @param port its port
 438      */
 439     SSLSocketImpl(SSLContextImpl context, InetAddress host, int port)
 440             throws IOException {
 441         super();
 442         init(context, false);
 443         SocketAddress socketAddress = new InetSocketAddress(host, port);
 444         connect(socketAddress, 0);
 445     }
 446 
 447     /**
 448      * Constructs an SSL connection to a named host at a specified port,
 449      * using the authentication context provided.  This endpoint acts as
 450      * the client, and may rejoin an existing SSL session if appropriate.
 451      *
 452      * @param context authentication context to use
 453      * @param host name of the host with which to connect
 454      * @param port number of the server's port
 455      * @param localAddr the local address the socket is bound to
 456      * @param localPort the local port the socket is bound to
 457      */
 458     SSLSocketImpl(SSLContextImpl context, String host, int port,
 459             InetAddress localAddr, int localPort)
 460             throws IOException, UnknownHostException {
 461         super();
 462         this.host = host;
 463         this.serverNames =
 464             Utilities.addToSNIServerNameList(this.serverNames, this.host);
 465         init(context, false);
 466         bind(new InetSocketAddress(localAddr, localPort));
 467         SocketAddress socketAddress =
 468                host != null ? new InetSocketAddress(host, port) :
 469                new InetSocketAddress(InetAddress.getByName(null), port);
 470         connect(socketAddress, 0);
 471     }
 472 
 473 
 474     /**
 475      * Constructs an SSL connection to a server at a specified address.
 476      * and TCP port, using the authentication context provided.  This
 477      * endpoint acts as the client, and may rejoin an existing SSL session
 478      * if appropriate.
 479      *
 480      * @param context authentication context to use
 481      * @param address the server's host
 482      * @param port its port
 483      * @param localAddr the local address the socket is bound to
 484      * @param localPort the local port the socket is bound to
 485      */
 486     SSLSocketImpl(SSLContextImpl context, InetAddress host, int port,
 487             InetAddress localAddr, int localPort)
 488             throws IOException {
 489         super();
 490         init(context, false);
 491         bind(new InetSocketAddress(localAddr, localPort));
 492         SocketAddress socketAddress = new InetSocketAddress(host, port);
 493         connect(socketAddress, 0);
 494     }
 495 
 496     /*
 497      * Package-private constructor used ONLY by SSLServerSocket.  The
 498      * java.net package accepts the TCP connection after this call is
 499      * made.  This just initializes handshake state to use "server mode",
 500      * giving control over the use of SSL client authentication.
 501      */
 502     SSLSocketImpl(SSLContextImpl context, boolean serverMode,
 503             CipherSuiteList suites, ClientAuthType clientAuth,
 504             boolean sessionCreation, ProtocolList protocols,
 505             String identificationProtocol,
 506             AlgorithmConstraints algorithmConstraints,
 507             Collection<SNIMatcher> sniMatchers,
 508             boolean preferLocalCipherSuites,
 509             String[] applicationProtocols) throws IOException {
 510 
 511         super();
 512         doClientAuth = clientAuth;
 513         enableSessionCreation = sessionCreation;
 514         this.identificationProtocol = identificationProtocol;
 515         this.algorithmConstraints = algorithmConstraints;
 516         this.sniMatchers = sniMatchers;
 517         this.preferLocalCipherSuites = preferLocalCipherSuites;
 518         this.applicationProtocols = applicationProtocols;
 519         init(context, serverMode);
 520 
 521         /*
 522          * Override what was picked out for us.
 523          */
 524         enabledCipherSuites = suites;
 525         enabledProtocols = protocols;
 526     }
 527 
 528 
 529     /**
 530      * Package-private constructor used to instantiate an unconnected
 531      * socket. The java.net package will connect it, either when the
 532      * connect() call is made by the application.  This instance is
 533      * meant to set handshake state to use "client mode".
 534      */
 535     SSLSocketImpl(SSLContextImpl context) {
 536         super();
 537         init(context, false);
 538     }
 539 
 540 
 541     /**
 542      * Layer SSL traffic over an existing connection, rather than creating
 543      * a new connection.  The existing connection may be used only for SSL
 544      * traffic (using this SSLSocket) until the SSLSocket.close() call
 545      * returns. However, if a protocol error is detected, that existing
 546      * connection is automatically closed.
 547      *
 548      * <P> This particular constructor always uses the socket in the
 549      * role of an SSL client. It may be useful in cases which start
 550      * using SSL after some initial data transfers, for example in some
 551      * SSL tunneling applications or as part of some kinds of application
 552      * protocols which negotiate use of a SSL based security.
 553      *
 554      * @param sock the existing connection
 555      * @param context the authentication context to use
 556      */
 557     SSLSocketImpl(SSLContextImpl context, Socket sock, String host,
 558             int port, boolean autoClose) throws IOException {
 559         super(sock);
 560         // We always layer over a connected socket
 561         if (!sock.isConnected()) {
 562             throw new SocketException("Underlying socket is not connected");
 563         }
 564         this.host = host;
 565         this.serverNames =
 566             Utilities.addToSNIServerNameList(this.serverNames, this.host);
 567         init(context, false);
 568         this.autoClose = autoClose;
 569         doneConnect();
 570     }
 571 
 572     /**
 573      * Creates a server mode {@link Socket} layered over an
 574      * existing connected socket, and is able to read data which has
 575      * already been consumed/removed from the {@link Socket}'s
 576      * underlying {@link InputStream}.
 577      */
 578     SSLSocketImpl(SSLContextImpl context, Socket sock,
 579             InputStream consumed, boolean autoClose) throws IOException {
 580         super(sock, consumed);
 581         // We always layer over a connected socket
 582         if (!sock.isConnected()) {
 583             throw new SocketException("Underlying socket is not connected");
 584         }
 585 
 586         // In server mode, it is not necessary to set host and serverNames.
 587         // Otherwise, would require a reverse DNS lookup to get the hostname.
 588 
 589         init(context, true);
 590         this.autoClose = autoClose;
 591         doneConnect();
 592     }
 593 
 594     /**
 595      * Initializes the client socket.
 596      */
 597     private void init(SSLContextImpl context, boolean isServer) {
 598         sslContext = context;
 599         sess = SSLSessionImpl.nullSession;
 600         handshakeSession = null;
 601 
 602         /*
 603          * role is as specified, state is START until after
 604          * the low level connection's established.
 605          */
 606         roleIsServer = isServer;
 607         connectionState = cs_START;
 608 
 609         // initial security parameters for secure renegotiation
 610         secureRenegotiation = false;
 611         clientVerifyData = new byte[0];
 612         serverVerifyData = new byte[0];
 613 
 614         enabledCipherSuites =
 615                 sslContext.getDefaultCipherSuiteList(roleIsServer);
 616         enabledProtocols =
 617                 sslContext.getDefaultProtocolList(roleIsServer);
 618 
 619         inputRecord = new SSLSocketInputRecord();;
 620         outputRecord = new SSLSocketOutputRecord();
 621 
 622         maximumPacketSize = outputRecord.getMaxPacketSize();
 623 
 624         // save the acc
 625         acc = AccessController.getContext();
 626 
 627         input = new AppInputStream(this);
 628         output = new AppOutputStream(this);
 629     }
 630 
 631     /**
 632      * Connects this socket to the server with a specified timeout
 633      * value.
 634      *
 635      * This method is either called on an unconnected SSLSocketImpl by the
 636      * application, or it is called in the constructor of a regular
 637      * SSLSocketImpl. If we are layering on top on another socket, then
 638      * this method should not be called, because we assume that the
 639      * underlying socket is already connected by the time it is passed to
 640      * us.
 641      *
 642      * @param   endpoint the <code>SocketAddress</code>
 643      * @param   timeout  the timeout value to be used, 0 is no timeout
 644      * @throws  IOException if an error occurs during the connection
 645      * @throws  SocketTimeoutException if timeout expires before connecting
 646      */
 647     @Override
 648     public void connect(SocketAddress endpoint, int timeout)
 649             throws IOException {
 650 
 651         if (isLayered()) {
 652             throw new SocketException("Already connected");
 653         }
 654 
 655         if (!(endpoint instanceof InetSocketAddress)) {
 656             throw new SocketException(
 657                                   "Cannot handle non-Inet socket addresses.");
 658         }
 659 
 660         super.connect(endpoint, timeout);
 661 
 662         if (host == null || host.length() == 0) {
 663             useImplicitHost(false);
 664         }
 665 
 666         doneConnect();
 667     }
 668 
 669     /**
 670      * Initialize the handshaker and socket streams.
 671      *
 672      * Called by connect, the layered constructor, and SSLServerSocket.
 673      */
 674     void doneConnect() throws IOException {
 675         /*
 676          * Save the input and output streams.  May be done only after
 677          * java.net actually connects using the socket "self", else
 678          * we get some pretty bizarre failure modes.
 679          */
 680         sockInput = super.getInputStream();
 681         sockOutput = super.getOutputStream();
 682 
 683         inputRecord.setDeliverStream(sockOutput);
 684         outputRecord.setDeliverStream(sockOutput);
 685 
 686         /*
 687          * Move to handshaking state, with pending session initialized
 688          * to defaults and the appropriate kind of handshaker set up.
 689          */
 690         initHandshaker();
 691     }
 692 
 693     private synchronized int getConnectionState() {
 694         return connectionState;
 695     }
 696 
 697     private synchronized void setConnectionState(int state) {
 698         connectionState = state;
 699     }
 700 
 701     AccessControlContext getAcc() {
 702         return acc;
 703     }
 704 
 705     //
 706     // READING AND WRITING RECORDS
 707     //
 708 
 709     /*
 710      * Application data record output.
 711      *
 712      * Application data can't be sent until the first handshake establishes
 713      * a session.
 714      */
 715     void writeRecord(byte[] source, int offset, int length) throws IOException {
 716         /*
 717          * The loop is in case of HANDSHAKE --> ERROR transitions, etc
 718          */
 719         // Don't bother to check the emptiness of source applicatoin data
 720         // before the security connection established.
 721         for (boolean readyForApp = false; !readyForApp;) {
 722             /*
 723              * Not all states support passing application data.  We
 724              * synchronize access to the connection state, so that
 725              * synchronous handshakes can complete cleanly.
 726              */
 727             switch (getConnectionState()) {
 728 
 729                 /*
 730                  * We've deferred the initial handshaking till just now,
 731                  * when presumably a thread's decided it's OK to block for
 732                  * longish periods of time for I/O purposes (as well as
 733                  * configured the cipher suites it wants to use).
 734                  */
 735                 case cs_HANDSHAKE:
 736                     performInitialHandshake();
 737                     break;
 738 
 739                 case cs_DATA:
 740                 case cs_RENEGOTIATE:
 741                     readyForApp = true;
 742                     break;
 743 
 744                 case cs_ERROR:
 745                     fatal(Alerts.alert_close_notify,
 746                             "error while writing to socket");
 747                     break; // dummy
 748 
 749                 case cs_SENT_CLOSE:
 750                 case cs_CLOSED:
 751                 case cs_APP_CLOSED:
 752                     // we should never get here (check in AppOutputStream)
 753                     // this is just a fallback
 754                     if (closeReason != null) {
 755                         throw closeReason;
 756                     } else {
 757                         throw new SocketException("Socket closed");
 758                     }
 759 
 760                 /*
 761                  * Else something's goofy in this state machine's use.
 762                  */
 763                 default:
 764                     throw new SSLProtocolException(
 765                             "State error, send app data");
 766             }
 767         }
 768 
 769         //
 770         // Don't bother to really write empty records.  We went this
 771         // far to drive the handshake machinery, for correctness; not
 772         // writing empty records improves performance by cutting CPU
 773         // time and network resource usage.  However, some protocol
 774         // implementations are fragile and don't like to see empty
 775         // records, so this also increases robustness.
 776         //
 777         if (length > 0) {
 778             IOException ioe = null;
 779             byte description = 0;    // 0: never used, make the compiler happy
 780             writeLock.lock();
 781             try {
 782                 outputRecord.deliver(source, offset, length);
 783             } catch (SSLHandshakeException she) {
 784                 // may be record sequence number overflow
 785                 description = Alerts.alert_handshake_failure;
 786                 ioe = she;
 787             } catch (IOException e) {
 788                 description = Alerts.alert_unexpected_message;
 789                 ioe = e;
 790             } finally {
 791                 writeLock.unlock();
 792             }
 793 
 794             // Be care of deadlock. Please don't place the call to fatal()
 795             // into the writeLock locked block.
 796             if (ioe != null) {
 797                 fatal(description, ioe);
 798             }
 799         }
 800 
 801         /*
 802          * Check the sequence number state
 803          *
 804          * Note that in order to maintain the connection I/O
 805          * properly, we check the sequence number after the last
 806          * record writing process. As we request renegotiation
 807          * or close the connection for wrapped sequence number
 808          * when there is enough sequence number space left to
 809          * handle a few more records, so the sequence number
 810          * of the last record cannot be wrapped.
 811          *
 812          * Don't bother to kickstart the renegotiation when the
 813          * local is asking for it.
 814          */
 815         if ((connectionState == cs_DATA) && outputRecord.seqNumIsHuge()) {
 816             /*
 817              * Ask for renegotiation when need to renew sequence number.
 818              *
 819              * Don't bother to kickstart the renegotiation when the local is
 820              * asking for it.
 821              */
 822             if (debug != null && Debug.isOn("ssl")) {
 823                 System.out.println(Thread.currentThread().getName() +
 824                         ", request renegotiation " +
 825                         "to avoid sequence number overflow");
 826             }
 827 
 828             startHandshake();
 829         }
 830     }
 831 
 832     /*
 833      * Alert record output.
 834      */
 835     void writeAlert(byte level, byte description) throws IOException {
 836 
 837         // If the record is a close notify alert, we need to honor
 838         // socket option SO_LINGER. Note that we will try to send
 839         // the close notify even if the SO_LINGER set to zero.
 840         if ((description == Alerts.alert_close_notify) && getSoLinger() >= 0) {
 841 
 842             // keep and clear the current thread interruption status.
 843             boolean interrupted = Thread.interrupted();
 844             try {
 845                 if (writeLock.tryLock(getSoLinger(), TimeUnit.SECONDS)) {
 846                     try {
 847                         outputRecord.encodeAlert(level, description);
 848                     } finally {
 849                         writeLock.unlock();
 850                     }
 851                 } else {
 852                     SSLException ssle = new SSLException(
 853                             "SO_LINGER timeout," +
 854                             " close_notify message cannot be sent.");
 855 
 856 
 857                     // For layered, non-autoclose sockets, we are not
 858                     // able to bring them into a usable state, so we
 859                     // treat it as fatal error.
 860                     if (isLayered() && !autoClose) {
 861                         // Note that the alert description is
 862                         // specified as -1, so no message will be send
 863                         // to peer anymore.
 864                         fatal((byte)(-1), ssle);
 865                     } else if ((debug != null) && Debug.isOn("ssl")) {
 866                         System.out.println(
 867                             Thread.currentThread().getName() +
 868                             ", received Exception: " + ssle);
 869                     }
 870 
 871                     // RFC2246 requires that the session becomes
 872                     // unresumable if any connection is terminated
 873                     // without proper close_notify messages with
 874                     // level equal to warning.
 875                     //
 876                     // RFC4346 no longer requires that a session not be
 877                     // resumed if failure to properly close a connection.
 878                     //
 879                     // We choose to make the session unresumable if
 880                     // failed to send the close_notify message.
 881                     //
 882                     sess.invalidate();
 883                 }
 884             } catch (InterruptedException ie) {
 885                 // keep interrupted status
 886                 interrupted = true;
 887             }
 888 
 889             // restore the interrupted status
 890             if (interrupted) {
 891                 Thread.currentThread().interrupt();
 892             }
 893         } else {
 894             writeLock.lock();
 895             try {
 896                 outputRecord.encodeAlert(level, description);
 897             } finally {
 898                 writeLock.unlock();
 899             }
 900         }
 901 
 902         // Don't bother to check sequence number overlap here.  If sequence
 903         // number is huge, there should be enough sequence number space to
 904         // request renegotiation in next application data read and write.
 905     }
 906 
 907 
 908     int bytesInCompletePacket() throws IOException {
 909         if (getConnectionState() == cs_HANDSHAKE) {
 910             performInitialHandshake();
 911         }
 912 
 913         synchronized (readLock) {
 914             int state = getConnectionState();
 915             if ((state == cs_CLOSED) ||
 916                     (state == cs_ERROR) || (state == cs_APP_CLOSED)) {
 917                 return -1;
 918             }
 919 
 920             try {
 921                 return inputRecord.bytesInCompletePacket(sockInput);
 922             } catch (EOFException eofe) {
 923                 boolean handshaking = (connectionState <= cs_HANDSHAKE);
 924                 boolean rethrow = requireCloseNotify || handshaking;
 925                 if ((debug != null) && Debug.isOn("ssl")) {
 926                     System.out.println(Thread.currentThread().getName() +
 927                         ", received EOFException: "
 928                         + (rethrow ? "error" : "ignored"));
 929                 }
 930 
 931                 if (!rethrow) {
 932                     // treat as if we had received a close_notify
 933                     closeInternal(false);
 934                 } else {
 935                     SSLException e;
 936                     if (handshaking) {
 937                         e = new SSLHandshakeException(
 938                             "Remote host terminated the handshake");
 939                     } else {
 940                         e = new SSLProtocolException(
 941                             "Remote host terminated the handshake");
 942                     }
 943                     e.initCause(eofe);
 944                     throw e;
 945                 }
 946             }
 947 
 948             return -1;
 949         }
 950     }
 951 
 952     // the caller have synchronized readLock
 953     void expectingFinishFlight() {
 954         inputRecord.expectingFinishFlight();
 955     }
 956 
 957     /*
 958      * Read an application data record.
 959      *
 960      * Alerts and handshake messages are internally handled directly.
 961      */
 962     int readRecord(ByteBuffer buffer) throws IOException {
 963         if (getConnectionState() == cs_HANDSHAKE) {
 964             performInitialHandshake();
 965         }
 966 
 967         return readRecord(buffer, true);
 968     }
 969 
 970     /*
 971      * Read a record, no application data input required.
 972      *
 973      * Alerts and handshake messages are internally handled directly.
 974      */
 975     int readRecord(boolean needAppData) throws IOException {
 976         return readRecord(null, needAppData);
 977     }
 978 
 979     /*
 980      * Clear the pipeline of records from the peer, optionally returning
 981      * application data.   Caller is responsible for knowing that it's
 982      * possible to do this kind of clearing, if they don't want app
 983      * data -- e.g. since it's the initial SSL handshake.
 984      *
 985      * Don't synchronize (this) during a blocking read() since it
 986      * protects data which is accessed on the write side as well.
 987      */
 988     private int readRecord(ByteBuffer buffer, boolean needAppData)
 989             throws IOException {
 990         int state;
 991 
 992         // readLock protects reading and processing of an SSLInputRecord.
 993         // It keeps the reading from sockInput and processing of the record
 994         // atomic so that no two threads can be blocked on the
 995         // read from the same input stream at the same time.
 996         // This is required for example when a reader thread is
 997         // blocked on the read and another thread is trying to
 998         // close the socket. For a non-autoclose, layered socket,
 999         // the thread performing the close needs to read the close_notify.
1000         //
1001         // Use readLock instead of 'this' for locking because
1002         // 'this' also protects data accessed during writing.
1003         synchronized (readLock) {
1004             /*
1005              * Read and handle records ... return application data
1006              * ONLY if it's needed.
1007              */
1008             Plaintext plainText = null;
1009             while (((state = getConnectionState()) != cs_CLOSED) &&
1010                     (state != cs_ERROR) && (state != cs_APP_CLOSED)) {
1011 
1012                 /*
1013                  * clean the buffer and check if it is too small, e.g. because
1014                  * the AppInputStream did not have the chance to see the
1015                  * current packet length but rather something like that of the
1016                  * handshake before. In that case we return 0 at this point to
1017                  * give the caller the chance to adjust the buffer.
1018                  */
1019                 if (buffer != null) {
1020                     buffer.clear();
1021 
1022                     if (buffer.remaining() <
1023                             inputRecord.bytesInCompletePacket(sockInput)) {
1024                         return 0;
1025                     }
1026                 }
1027 
1028                 /*
1029                  * Read a record ... maybe emitting an alert if we get a
1030                  * comprehensible but unsupported "hello" message during
1031                  * format checking (e.g. V2).
1032                  */
1033                 try {
1034                     plainText = inputRecord.decode(sockInput, buffer);
1035                 } catch (BadPaddingException bpe) {
1036                     byte alertType = (state != cs_DATA) ?
1037                             Alerts.alert_handshake_failure :
1038                             Alerts.alert_bad_record_mac;
1039                     fatal(alertType, bpe.getMessage(), bpe);
1040                 } catch (SSLProtocolException spe) {
1041                     try {
1042                         fatal(Alerts.alert_unexpected_message, spe);
1043                     } catch (IOException x) {
1044                         // discard this exception, throw the original exception
1045                     }
1046                     throw spe;
1047                 } catch (SSLHandshakeException she) {
1048                     // may be record sequence number overflow
1049                     fatal(Alerts.alert_handshake_failure, she);
1050                 } catch (EOFException eof) {
1051                     boolean handshaking = (connectionState <= cs_HANDSHAKE);
1052                     boolean rethrow = requireCloseNotify || handshaking;
1053                     if ((debug != null) && Debug.isOn("ssl")) {
1054                         System.out.println(Thread.currentThread().getName() +
1055                             ", received EOFException: "
1056                             + (rethrow ? "error" : "ignored"));
1057                     }
1058                     if (rethrow) {
1059                         SSLException e;
1060                         if (handshaking) {
1061                             e = new SSLHandshakeException(
1062                                     "Remote host terminated the handshake");
1063                         } else {
1064                             e = new SSLProtocolException(
1065                                     "Remote host terminated the connection");
1066                         }
1067                         e.initCause(eof);
1068                         throw e;
1069                     } else {
1070                         // treat as if we had received a close_notify
1071                         closeInternal(false);
1072                         continue;
1073                     }
1074                 }
1075 
1076                 // PlainText should never be null. Process input record.
1077                 int volume = processInputRecord(plainText, needAppData);
1078 
1079                 if (plainText.contentType == Record.ct_application_data) {
1080                     return volume;
1081                 }
1082 
1083                 if (plainText.contentType == Record.ct_handshake) {
1084                     if (!needAppData && connectionState == cs_DATA) {
1085                         return volume;
1086                     }   // otherwise, need to read more for app data.
1087                 }
1088 
1089                 // continue to read more net data
1090             }   // while
1091 
1092             //
1093             // couldn't read, due to some kind of error
1094             //
1095             return -1;
1096         }  // readLock synchronization
1097     }
1098 
1099     /*
1100      * Process the plainText input record.
1101      */
1102     private synchronized int processInputRecord(
1103             Plaintext plainText, boolean needAppData) throws IOException {
1104 
1105         /*
1106          * Process the record.
1107          */
1108         int volume = 0;    // no application data
1109         switch (plainText.contentType) {
1110             case Record.ct_handshake:
1111                 /*
1112                  * Handshake messages always go to a pending session
1113                  * handshaker ... if there isn't one, create one.  This
1114                  * must work asynchronously, for renegotiation.
1115                  *
1116                  * NOTE that handshaking will either resume a session
1117                  * which was in the cache (and which might have other
1118                  * connections in it already), or else will start a new
1119                  * session (new keys exchanged) with just this connection
1120                  * in it.
1121                  */
1122                 initHandshaker();
1123                 if (!handshaker.activated()) {
1124                     // prior to handshaking, activate the handshake
1125                     if (connectionState == cs_RENEGOTIATE) {
1126                         // don't use SSLv2Hello when renegotiating
1127                         handshaker.activate(protocolVersion);
1128                     } else {
1129                         handshaker.activate(null);
1130                     }
1131                 }
1132 
1133                 /*
1134                  * process the handshake record ... may contain just
1135                  * a partial handshake message or multiple messages.
1136                  *
1137                  * The handshaker state machine will ensure that it's
1138                  * a finished message.
1139                  */
1140                 handshaker.processRecord(plainText.fragment, expectingFinished);
1141                 expectingFinished = false;
1142 
1143                 if (handshaker.invalidated) {
1144                     handshaker = null;
1145                     inputRecord.setHandshakeHash(null);
1146                     outputRecord.setHandshakeHash(null);
1147 
1148                     // if state is cs_RENEGOTIATE, revert it to cs_DATA
1149                     if (connectionState == cs_RENEGOTIATE) {
1150                         connectionState = cs_DATA;
1151                     }
1152                 } else if (handshaker.isDone()) {
1153                     // reset the parameters for secure renegotiation.
1154                     secureRenegotiation =
1155                                     handshaker.isSecureRenegotiation();
1156                     clientVerifyData = handshaker.getClientVerifyData();
1157                     serverVerifyData = handshaker.getServerVerifyData();
1158                     // set connection ALPN value
1159                     applicationProtocol =
1160                         handshaker.getHandshakeApplicationProtocol();
1161 
1162                     sess = handshaker.getSession();
1163                     handshakeSession = null;
1164                     handshaker = null;
1165                     inputRecord.setHandshakeHash(null);
1166                     outputRecord.setHandshakeHash(null);
1167                     connectionState = cs_DATA;
1168 
1169                     //
1170                     // Tell folk about handshake completion, but do
1171                     // it in a separate thread.
1172                     //
1173                     if (handshakeListeners != null) {
1174                         HandshakeCompletedEvent event =
1175                             new HandshakeCompletedEvent(this, sess);
1176 
1177                         Thread thread = new Thread(
1178                             null,
1179                             new NotifyHandshake(
1180                                 handshakeListeners.entrySet(), event),
1181                             "HandshakeCompletedNotify-Thread",
1182                             0,
1183                             false);
1184                         thread.start();
1185                     }
1186                 }
1187 
1188                 break;
1189 
1190             case Record.ct_application_data:
1191                 if (connectionState != cs_DATA
1192                         && connectionState != cs_RENEGOTIATE
1193                         && connectionState != cs_SENT_CLOSE) {
1194                     throw new SSLProtocolException(
1195                         "Data received in non-data state: " +
1196                         connectionState);
1197                 }
1198                 if (expectingFinished) {
1199                     throw new SSLProtocolException
1200                             ("Expecting finished message, received data");
1201                 }
1202                 if (!needAppData) {
1203                     throw new SSLException("Discarding app data");
1204                 }
1205 
1206                 volume = plainText.fragment.remaining();
1207                 break;
1208 
1209             case Record.ct_alert:
1210                 recvAlert(plainText.fragment);
1211                 break;
1212 
1213             case Record.ct_change_cipher_spec:
1214                 if ((connectionState != cs_HANDSHAKE
1215                         && connectionState != cs_RENEGOTIATE)) {
1216                     // For the CCS message arriving in the wrong state
1217                     fatal(Alerts.alert_unexpected_message,
1218                             "illegal change cipher spec msg, conn state = "
1219                             + connectionState);
1220                 } else if (plainText.fragment.remaining() != 1
1221                         || plainText.fragment.get() != 1) {
1222                     // For structural/content issues with the CCS
1223                     fatal(Alerts.alert_unexpected_message,
1224                             "Malformed change cipher spec msg");
1225                 }
1226 
1227                 //
1228                 // The first message after a change_cipher_spec
1229                 // record MUST be a "Finished" handshake record,
1230                 // else it's a protocol violation.  We force this
1231                 // to be checked by a minor tweak to the state
1232                 // machine.
1233                 //
1234                 handshaker.receiveChangeCipherSpec();
1235 
1236                 CipherBox readCipher;
1237                 Authenticator readAuthenticator;
1238                 try {
1239                     readCipher = handshaker.newReadCipher();
1240                     readAuthenticator = handshaker.newReadAuthenticator();
1241                 } catch (GeneralSecurityException e) {
1242                     // can't happen
1243                     throw new SSLException("Algorithm missing:  ", e);
1244                 }
1245                 inputRecord.changeReadCiphers(readAuthenticator, readCipher);
1246 
1247                 // next message MUST be a finished message
1248                 expectingFinished = true;
1249 
1250                 break;
1251 
1252             default:
1253                 //
1254                 // TLS requires that unrecognized records be ignored.
1255                 //
1256                 if (debug != null && Debug.isOn("ssl")) {
1257                     System.out.println(Thread.currentThread().getName() +
1258                         ", Received record type: " + plainText.contentType);
1259                 }
1260                 break;
1261         }
1262 
1263         /*
1264          * Check the sequence number state
1265          *
1266          * Note that in order to maintain the connection I/O
1267          * properly, we check the sequence number after the last
1268          * record reading process. As we request renegotiation
1269          * or close the connection for wrapped sequence number
1270          * when there is enough sequence number space left to
1271          * handle a few more records, so the sequence number
1272          * of the last record cannot be wrapped.
1273          *
1274          * Don't bother to kickstart the renegotiation when the
1275          * local is asking for it.
1276          */
1277         if ((connectionState == cs_DATA) && inputRecord.seqNumIsHuge()) {
1278             /*
1279              * Ask for renegotiation when need to renew sequence number.
1280              *
1281              * Don't bother to kickstart the renegotiation when the local is
1282              * asking for it.
1283              */
1284             if (debug != null && Debug.isOn("ssl")) {
1285                 System.out.println(Thread.currentThread().getName() +
1286                         ", request renegotiation " +
1287                         "to avoid sequence number overflow");
1288             }
1289 
1290             startHandshake();
1291         }
1292 
1293         return volume;
1294     }
1295 
1296 
1297     //
1298     // HANDSHAKE RELATED CODE
1299     //
1300 
1301     /**
1302      * Return the AppInputStream. For use by Handshaker only.
1303      */
1304     AppInputStream getAppInputStream() {
1305         return input;
1306     }
1307 
1308     /**
1309      * Return the AppOutputStream. For use by Handshaker only.
1310      */
1311     AppOutputStream getAppOutputStream() {
1312         return output;
1313     }
1314 
1315     /**
1316      * Initialize the handshaker object. This means:
1317      *
1318      *  . if a handshake is already in progress (state is cs_HANDSHAKE
1319      *    or cs_RENEGOTIATE), do nothing and return
1320      *
1321      *  . if the socket is already closed, throw an Exception (internal error)
1322      *
1323      *  . otherwise (cs_START or cs_DATA), create the appropriate handshaker
1324      *    object, and advance the connection state (to cs_HANDSHAKE or
1325      *    cs_RENEGOTIATE, respectively).
1326      *
1327      * This method is called right after a new socket is created, when
1328      * starting renegotiation, or when changing client/ server mode of the
1329      * socket.
1330      */
1331     private void initHandshaker() {
1332         switch (connectionState) {
1333 
1334         //
1335         // Starting a new handshake.
1336         //
1337         case cs_START:
1338         case cs_DATA:
1339             break;
1340 
1341         //
1342         // We're already in the middle of a handshake.
1343         //
1344         case cs_HANDSHAKE:
1345         case cs_RENEGOTIATE:
1346             return;
1347 
1348         //
1349         // Anyone allowed to call this routine is required to
1350         // do so ONLY if the connection state is reasonable...
1351         //
1352         default:
1353             throw new IllegalStateException("Internal error");
1354         }
1355 
1356         // state is either cs_START or cs_DATA
1357         if (connectionState == cs_START) {
1358             connectionState = cs_HANDSHAKE;
1359         } else { // cs_DATA
1360             connectionState = cs_RENEGOTIATE;
1361         }
1362 
1363         if (roleIsServer) {
1364             handshaker = new ServerHandshaker(this, sslContext,
1365                     enabledProtocols, doClientAuth,
1366                     protocolVersion, connectionState == cs_HANDSHAKE,
1367                     secureRenegotiation, clientVerifyData, serverVerifyData);
1368             handshaker.setSNIMatchers(sniMatchers);
1369             handshaker.setUseCipherSuitesOrder(preferLocalCipherSuites);
1370         } else {
1371             handshaker = new ClientHandshaker(this, sslContext,
1372                     enabledProtocols,
1373                     protocolVersion, connectionState == cs_HANDSHAKE,
1374                     secureRenegotiation, clientVerifyData, serverVerifyData);
1375             handshaker.setSNIServerNames(serverNames);
1376         }
1377         handshaker.setMaximumPacketSize(maximumPacketSize);
1378         handshaker.setEnabledCipherSuites(enabledCipherSuites);
1379         handshaker.setEnableSessionCreation(enableSessionCreation);
1380         handshaker.setApplicationProtocols(applicationProtocols);
1381         handshaker.setApplicationProtocolSelectorSSLSocket(
1382             applicationProtocolSelector);
1383     }
1384 
1385     /**
1386      * Synchronously perform the initial handshake.
1387      *
1388      * If the handshake is already in progress, this method blocks until it
1389      * is completed. If the initial handshake has already been completed,
1390      * it returns immediately.
1391      */
1392     private void performInitialHandshake() throws IOException {
1393         // use handshakeLock and the state check to make sure only
1394         // one thread performs the handshake
1395         synchronized (handshakeLock) {
1396             if (getConnectionState() == cs_HANDSHAKE) {
1397                 kickstartHandshake();
1398 
1399                 /*
1400                  * All initial handshaking goes through this operation
1401                  * until we have a valid SSL connection.
1402                  *
1403                  * Handle handshake messages only, need no application data.
1404                  */
1405                 readRecord(false);
1406             }
1407         }
1408     }
1409 
1410     /**
1411      * Starts an SSL handshake on this connection.
1412      */
1413     @Override
1414     public void startHandshake() throws IOException {
1415         // start an ssl handshake that could be resumed from timeout exception
1416         startHandshake(true);
1417     }
1418 
1419     /**
1420      * Starts an ssl handshake on this connection.
1421      *
1422      * @param resumable indicates the handshake process is resumable from a
1423      *          certain exception. If <code>resumable</code>, the socket will
1424      *          be reserved for exceptions like timeout; otherwise, the socket
1425      *          will be closed, no further communications could be done.
1426      */
1427     private void startHandshake(boolean resumable) throws IOException {
1428         checkWrite();
1429         try {
1430             if (getConnectionState() == cs_HANDSHAKE) {
1431                 // do initial handshake
1432                 performInitialHandshake();
1433             } else {
1434                 // start renegotiation
1435                 kickstartHandshake();
1436             }
1437         } catch (Exception e) {
1438             // shutdown and rethrow (wrapped) exception as appropriate
1439             handleException(e, resumable);
1440         }
1441     }
1442 
1443     /**
1444      * Kickstart the handshake if it is not already in progress.
1445      * This means:
1446      *
1447      *  . if handshaking is already underway, do nothing and return
1448      *
1449      *  . if the socket is not connected or already closed, throw an
1450      *    Exception.
1451      *
1452      *  . otherwise, call initHandshake() to initialize the handshaker
1453      *    object and progress the state. Then, send the initial
1454      *    handshaking message if appropriate (always on clients and
1455      *    on servers when renegotiating).
1456      */
1457     private synchronized void kickstartHandshake() throws IOException {
1458 
1459         switch (connectionState) {
1460 
1461         case cs_HANDSHAKE:
1462             // handshaker already setup, proceed
1463             break;
1464 
1465         case cs_DATA:
1466             if (!secureRenegotiation && !Handshaker.allowUnsafeRenegotiation) {
1467                 throw new SSLHandshakeException(
1468                         "Insecure renegotiation is not allowed");
1469             }
1470 
1471             if (!secureRenegotiation) {
1472                 if (debug != null && Debug.isOn("handshake")) {
1473                     System.out.println(
1474                         "Warning: Using insecure renegotiation");
1475                 }
1476             }
1477 
1478             // initialize the handshaker, move to cs_RENEGOTIATE
1479             initHandshaker();
1480             break;
1481 
1482         case cs_RENEGOTIATE:
1483             // handshaking already in progress, return
1484             return;
1485 
1486         /*
1487          * The only way to get a socket in the state is when
1488          * you have an unconnected socket.
1489          */
1490         case cs_START:
1491             throw new SocketException(
1492                 "handshaking attempted on unconnected socket");
1493 
1494         default:
1495             throw new SocketException("connection is closed");
1496         }
1497 
1498         //
1499         // Kickstart handshake state machine if we need to ...
1500         //
1501         // Note that handshaker.kickstart() writes the message
1502         // to its HandshakeOutStream, which calls back into
1503         // SSLSocketImpl.writeRecord() to send it.
1504         //
1505         if (!handshaker.activated()) {
1506              // prior to handshaking, activate the handshake
1507             if (connectionState == cs_RENEGOTIATE) {
1508                 // don't use SSLv2Hello when renegotiating
1509                 handshaker.activate(protocolVersion);
1510             } else {
1511                 handshaker.activate(null);
1512             }
1513 
1514             if (handshaker instanceof ClientHandshaker) {
1515                 // send client hello
1516                 handshaker.kickstart();
1517             } else {
1518                 if (connectionState == cs_HANDSHAKE) {
1519                     // initial handshake, no kickstart message to send
1520                 } else {
1521                     // we want to renegotiate, send hello request
1522                     handshaker.kickstart();
1523                 }
1524             }
1525         }
1526     }
1527 
1528     //
1529     // CLOSURE RELATED CALLS
1530     //
1531 
1532     /**
1533      * Return whether the socket has been explicitly closed by the application.
1534      */
1535     @Override
1536     public boolean isClosed() {
1537         return connectionState == cs_APP_CLOSED;
1538     }
1539 
1540     /**
1541      * Return whether we have reached end-of-file.
1542      *
1543      * If the socket is not connected, has been shutdown because of an error
1544      * or has been closed, throw an Exception.
1545      */
1546     boolean checkEOF() throws IOException {
1547         switch (getConnectionState()) {
1548         case cs_START:
1549             throw new SocketException("Socket is not connected");
1550 
1551         case cs_HANDSHAKE:
1552         case cs_DATA:
1553         case cs_RENEGOTIATE:
1554         case cs_SENT_CLOSE:
1555             return false;
1556 
1557         case cs_APP_CLOSED:
1558             throw new SocketException("Socket is closed");
1559 
1560         case cs_ERROR:
1561         case cs_CLOSED:
1562         default:
1563             // either closed because of error, or normal EOF
1564             if (closeReason == null) {
1565                 return true;
1566             }
1567             IOException e = new SSLException
1568                         ("Connection has been shutdown: " + closeReason);
1569             e.initCause(closeReason);
1570             throw e;
1571 
1572         }
1573     }
1574 
1575     /**
1576      * Check if we can write data to this socket. If not, throw an IOException.
1577      */
1578     void checkWrite() throws IOException {
1579         if (checkEOF() || (getConnectionState() == cs_SENT_CLOSE)) {
1580             // we are at EOF, write must throw Exception
1581             throw new SocketException("Connection closed by remote host");
1582         }
1583     }
1584 
1585     private void closeSocket() throws IOException {
1586 
1587         if ((debug != null) && Debug.isOn("ssl")) {
1588             System.out.println(Thread.currentThread().getName() +
1589                                                 ", called closeSocket()");
1590         }
1591 
1592         super.close();
1593     }
1594 
1595     private void closeSocket(boolean selfInitiated) throws IOException {
1596         if ((debug != null) && Debug.isOn("ssl")) {
1597             System.out.println(Thread.currentThread().getName() +
1598                 ", called closeSocket(" + selfInitiated + ")");
1599         }
1600         if (!isLayered() || autoClose) {
1601             super.close();
1602         } else if (selfInitiated) {
1603             // layered && non-autoclose
1604             // read close_notify alert to clear input stream
1605             waitForClose(false);
1606         }
1607     }
1608 
1609     /*
1610      * Closing the connection is tricky ... we can't officially close the
1611      * connection until we know the other end is ready to go away too,
1612      * and if ever the connection gets aborted we must forget session
1613      * state (it becomes invalid).
1614      */
1615 
1616     /**
1617      * Closes the SSL connection.  SSL includes an application level
1618      * shutdown handshake; you should close SSL sockets explicitly
1619      * rather than leaving it for finalization, so that your remote
1620      * peer does not experience a protocol error.
1621      */
1622     @Override
1623     public void close() throws IOException {
1624         if ((debug != null) && Debug.isOn("ssl")) {
1625             System.out.println(Thread.currentThread().getName() +
1626                                                     ", called close()");
1627         }
1628         closeInternal(true);  // caller is initiating close
1629 
1630         // Clearup the resources.
1631         try {
1632             synchronized (readLock) {
1633                 inputRecord.close();
1634             }
1635 
1636             writeLock.lock();
1637             try {
1638                 outputRecord.close();
1639             } finally {
1640                 writeLock.unlock();
1641             }
1642         } catch (IOException ioe) {
1643            // ignore
1644         }
1645 
1646         setConnectionState(cs_APP_CLOSED);
1647     }
1648 
1649     /**
1650      * Don't synchronize the whole method because waitForClose()
1651      * (which calls readRecord()) might be called.
1652      *
1653      * @param selfInitiated Indicates which party initiated the close.
1654      * If selfInitiated, this side is initiating a close; for layered and
1655      * non-autoclose socket, wait for close_notify response.
1656      * If !selfInitiated, peer sent close_notify; we reciprocate but
1657      * no need to wait for response.
1658      */
1659     private void closeInternal(boolean selfInitiated) throws IOException {
1660         if ((debug != null) && Debug.isOn("ssl")) {
1661             System.out.println(Thread.currentThread().getName() +
1662                         ", called closeInternal(" + selfInitiated + ")");
1663         }
1664 
1665         int state = getConnectionState();
1666         boolean closeSocketCalled = false;
1667         Throwable cachedThrowable = null;
1668         try {
1669             switch (state) {
1670             case cs_START:
1671                 // unconnected socket or handshaking has not been initialized
1672                 closeSocket(selfInitiated);
1673                 break;
1674 
1675             /*
1676              * If we're closing down due to error, we already sent (or else
1677              * received) the fatal alert ... no niceties, blow the connection
1678              * away as quickly as possible (even if we didn't allocate the
1679              * socket ourselves; it's unusable, regardless).
1680              */
1681             case cs_ERROR:
1682                 closeSocket();
1683                 break;
1684 
1685             /*
1686              * Sometimes close() gets called more than once.
1687              */
1688             case cs_CLOSED:
1689             case cs_APP_CLOSED:
1690                  break;
1691 
1692             /*
1693              * Otherwise we indicate clean termination.
1694              */
1695             // case cs_HANDSHAKE:
1696             // case cs_DATA:
1697             // case cs_RENEGOTIATE:
1698             // case cs_SENT_CLOSE:
1699             default:
1700                 synchronized (this) {
1701                     if (((state = getConnectionState()) == cs_CLOSED) ||
1702                        (state == cs_ERROR) || (state == cs_APP_CLOSED)) {
1703                         return;  // connection was closed while we waited
1704                     }
1705                     if (state != cs_SENT_CLOSE) {
1706                         try {
1707                             warning(Alerts.alert_close_notify);
1708                             connectionState = cs_SENT_CLOSE;
1709                         } catch (Throwable th) {
1710                             // we need to ensure socket is closed out
1711                             // if we encounter any errors.
1712                             connectionState = cs_ERROR;
1713                             // cache this for later use
1714                             cachedThrowable = th;
1715                             closeSocketCalled = true;
1716                             closeSocket(selfInitiated);
1717                         }
1718                     }
1719                 }
1720                 // If state was cs_SENT_CLOSE before, we don't do the actual
1721                 // closing since it is already in progress.
1722                 if (state == cs_SENT_CLOSE) {
1723                     if (debug != null && Debug.isOn("ssl")) {
1724                         System.out.println(Thread.currentThread().getName() +
1725                             ", close invoked again; state = " +
1726                             getConnectionState());
1727                     }
1728                     if (selfInitiated == false) {
1729                         // We were called because a close_notify message was
1730                         // received. This may be due to another thread calling
1731                         // read() or due to our call to waitForClose() below.
1732                         // In either case, just return.
1733                         return;
1734                     }
1735                     // Another thread explicitly called close(). We need to
1736                     // wait for the closing to complete before returning.
1737                     synchronized (this) {
1738                         while (connectionState < cs_CLOSED) {
1739                             try {
1740                                 this.wait();
1741                             } catch (InterruptedException e) {
1742                                 // ignore
1743                             }
1744                         }
1745                     }
1746                     if ((debug != null) && Debug.isOn("ssl")) {
1747                         System.out.println(Thread.currentThread().getName() +
1748                             ", after primary close; state = " +
1749                             getConnectionState());
1750                     }
1751                     return;
1752                 }
1753 
1754                 if (!closeSocketCalled)  {
1755                     closeSocketCalled = true;
1756                     closeSocket(selfInitiated);
1757                 }
1758 
1759                 break;
1760             }
1761         } finally {
1762             synchronized (this) {
1763                 // Upon exit from this method, the state is always >= cs_CLOSED
1764                 connectionState = (connectionState == cs_APP_CLOSED)
1765                                 ? cs_APP_CLOSED : cs_CLOSED;
1766                 // notify any threads waiting for the closing to finish
1767                 this.notifyAll();
1768             }
1769 
1770             if (cachedThrowable != null) {
1771                /*
1772                 * Rethrow the error to the calling method
1773                 * The Throwable caught can only be an Error or RuntimeException
1774                 */
1775                 if (cachedThrowable instanceof Error) {
1776                     throw (Error)cachedThrowable;
1777                 } else if (cachedThrowable instanceof RuntimeException) {
1778                     throw (RuntimeException)cachedThrowable;
1779                 }   // Otherwise, unlikely
1780             }
1781         }
1782     }
1783 
1784     /**
1785      * Reads a close_notify or a fatal alert from the input stream.
1786      * Keep reading records until we get a close_notify or until
1787      * the connection is otherwise closed.  The close_notify or alert
1788      * might be read by another reader,
1789      * which will then process the close and set the connection state.
1790      */
1791     void waitForClose(boolean rethrow) throws IOException {
1792         if (debug != null && Debug.isOn("ssl")) {
1793             System.out.println(Thread.currentThread().getName() +
1794                 ", waiting for close_notify or alert: state "
1795                 + getConnectionState());
1796         }
1797 
1798         try {
1799             int state;
1800             int retryCount = 0;
1801 
1802             while (((state = getConnectionState()) != cs_CLOSED) &&
1803                    (state != cs_ERROR) && (state != cs_APP_CLOSED)) {
1804 
1805                 // Ask for app data and then throw it away
1806                 try {
1807                     readRecord(true);
1808                 } catch (SocketTimeoutException e) {
1809                     // if time out, retry as specified by retryCloseAttempts
1810                     if (retryCloseAttempts > 0 && retryCount == retryCloseAttempts) {
1811                         if ((debug != null) && Debug.isOn("ssl")) {
1812                             System.out.println(
1813                                 Thread.currentThread().getName() +
1814                                 ", received Exception: " + e);
1815                         }
1816                         fatal((byte)(-1), "Did not receive close_notify from peer", e);
1817                     }
1818                     retryCount++;
1819                 }
1820             }
1821         } catch (IOException e) {
1822             if (debug != null && Debug.isOn("ssl")) {
1823                 System.out.println(Thread.currentThread().getName() +
1824                     ", Exception while waiting for close " +e);
1825             }
1826             if (rethrow) {
1827                 throw e; // pass exception up
1828             }
1829         }
1830     }
1831 
1832     //
1833     // EXCEPTION AND ALERT HANDLING
1834     //
1835 
1836     /**
1837      * Handle an exception. This method is called by top level exception
1838      * handlers (in read(), write()) to make sure we always shutdown the
1839      * connection correctly and do not pass runtime exception to the
1840      * application.
1841      */
1842     void handleException(Exception e) throws IOException {
1843         handleException(e, true);
1844     }
1845 
1846     /**
1847      * Handle an exception. This method is called by top level exception
1848      * handlers (in read(), write(), startHandshake()) to make sure we
1849      * always shutdown the connection correctly and do not pass runtime
1850      * exception to the application.
1851      *
1852      * This method never returns normally, it always throws an IOException.
1853      *
1854      * We first check if the socket has already been shutdown because of an
1855      * error. If so, we just rethrow the exception. If the socket has not
1856      * been shutdown, we sent a fatal alert and remember the exception.
1857      *
1858      * @param e the Exception
1859      * @param resumable indicates the caller process is resumable from the
1860      *          exception. If <code>resumable</code>, the socket will be
1861      *          reserved for exceptions like timeout; otherwise, the socket
1862      *          will be closed, no further communications could be done.
1863      */
1864     private synchronized void handleException(Exception e, boolean resumable)
1865         throws IOException {
1866         if ((debug != null) && Debug.isOn("ssl")) {
1867             System.out.println(Thread.currentThread().getName() +
1868                         ", handling exception: " + e.toString());
1869         }
1870 
1871         // don't close the Socket in case of timeouts or interrupts if
1872         // the process is resumable.
1873         if (e instanceof InterruptedIOException && resumable) {
1874             throw (IOException)e;
1875         }
1876 
1877         // if we've already shutdown because of an error,
1878         // there is nothing to do except rethrow the exception
1879         if (closeReason != null) {
1880             if (e instanceof IOException) { // includes SSLException
1881                 throw (IOException)e;
1882             } else {
1883                 // this is odd, not an IOException.
1884                 // normally, this should not happen
1885                 // if closeReason has been already been set
1886                 throw Alerts.getSSLException(Alerts.alert_internal_error, e,
1887                                       "Unexpected exception");
1888             }
1889         }
1890 
1891         // need to perform error shutdown
1892         boolean isSSLException = (e instanceof SSLException);
1893         if ((!isSSLException) && (e instanceof IOException)) {
1894             // IOException from the socket
1895             // this means the TCP connection is already dead
1896             // we call fatal just to set the error status
1897             try {
1898                 fatal(Alerts.alert_unexpected_message, e);
1899             } catch (IOException ee) {
1900                 // ignore (IOException wrapped in SSLException)
1901             }
1902             // rethrow original IOException
1903             throw (IOException)e;
1904         }
1905 
1906         // must be SSLException or RuntimeException
1907         byte alertType;
1908         if (isSSLException) {
1909             if (e instanceof SSLHandshakeException) {
1910                 alertType = Alerts.alert_handshake_failure;
1911             } else {
1912                 alertType = Alerts.alert_unexpected_message;
1913             }
1914         } else {
1915             alertType = Alerts.alert_internal_error;
1916         }
1917         fatal(alertType, e);
1918     }
1919 
1920     /*
1921      * Send a warning alert.
1922      */
1923     void warning(byte description) {
1924         sendAlert(Alerts.alert_warning, description);
1925     }
1926 
1927     synchronized void fatal(byte description, String diagnostic)
1928             throws IOException {
1929         fatal(description, diagnostic, null);
1930     }
1931 
1932     synchronized void fatal(byte description, Throwable cause)
1933             throws IOException {
1934         fatal(description, null, cause);
1935     }
1936 
1937     /*
1938      * Send a fatal alert, and throw an exception so that callers will
1939      * need to stand on their heads to accidentally continue processing.
1940      */
1941     synchronized void fatal(byte description, String diagnostic,
1942             Throwable cause) throws IOException {
1943 
1944         // Be care of deadlock. Please don't synchronize readLock.
1945         try {
1946             inputRecord.close();
1947         } catch (IOException ioe) {
1948             // ignore
1949         }
1950 
1951         sess.invalidate();
1952         if (handshakeSession != null) {
1953             handshakeSession.invalidate();
1954         }
1955 
1956         int oldState = connectionState;
1957         if (connectionState < cs_ERROR) {
1958             connectionState = cs_ERROR;
1959         }
1960 
1961         /*
1962          * Has there been an error received yet?  If not, remember it.
1963          * By RFC 2246, we don't bother waiting for a response.
1964          * Fatal errors require immediate shutdown.
1965          */
1966         if (closeReason == null) {
1967             /*
1968              * Try to clear the kernel buffer to avoid TCP connection resets.
1969              */
1970             if (oldState == cs_HANDSHAKE) {
1971                 sockInput.skip(sockInput.available());
1972             }
1973 
1974             // If the description equals -1, the alert won't be sent to peer.
1975             if (description != -1) {
1976                 sendAlert(Alerts.alert_fatal, description);
1977             }
1978             if (cause instanceof SSLException) { // only true if != null
1979                 closeReason = (SSLException)cause;
1980             } else {
1981                 closeReason =
1982                     Alerts.getSSLException(description, cause, diagnostic);
1983             }
1984         }
1985 
1986         /*
1987          * Clean up our side.
1988          */
1989         closeSocket();
1990 
1991         // Be care of deadlock. Please don't synchronize writeLock.
1992         try {
1993             outputRecord.close();
1994         } catch (IOException ioe) {
1995             // ignore
1996         }
1997 
1998         throw closeReason;
1999     }
2000 
2001 
2002     /*
2003      * Process an incoming alert ... caller must already have synchronized
2004      * access to "this".
2005      */
2006     private void recvAlert(ByteBuffer fragment) throws IOException {
2007         byte level = fragment.get();
2008         byte description = fragment.get();
2009 
2010         if (description == -1) { // check for short message
2011             fatal(Alerts.alert_illegal_parameter, "Short alert message");
2012         }
2013 
2014         if (debug != null && (Debug.isOn("record") ||
2015                 Debug.isOn("handshake"))) {
2016             synchronized (System.out) {
2017                 System.out.print(Thread.currentThread().getName());
2018                 System.out.print(", RECV " + protocolVersion + " ALERT:  ");
2019                 if (level == Alerts.alert_fatal) {
2020                     System.out.print("fatal, ");
2021                 } else if (level == Alerts.alert_warning) {
2022                     System.out.print("warning, ");
2023                 } else {
2024                     System.out.print("<level " + (0x0ff & level) + ">, ");
2025                 }
2026                 System.out.println(Alerts.alertDescription(description));
2027             }
2028         }
2029 
2030         if (level == Alerts.alert_warning) {
2031             if (description == Alerts.alert_close_notify) {
2032                 if (connectionState == cs_HANDSHAKE) {
2033                     fatal(Alerts.alert_unexpected_message,
2034                                 "Received close_notify during handshake");
2035                 } else {
2036                     closeInternal(false);  // reply to close
2037                 }
2038             } else {
2039 
2040                 //
2041                 // The other legal warnings relate to certificates,
2042                 // e.g. no_certificate, bad_certificate, etc; these
2043                 // are important to the handshaking code, which can
2044                 // also handle illegal protocol alerts if needed.
2045                 //
2046                 if (handshaker != null) {
2047                     handshaker.handshakeAlert(description);
2048                 }
2049             }
2050         } else { // fatal or unknown level
2051             String reason = "Received fatal alert: "
2052                 + Alerts.alertDescription(description);
2053             if (closeReason == null) {
2054                 closeReason = Alerts.getSSLException(description, reason);
2055             }
2056             fatal(Alerts.alert_unexpected_message, reason);
2057         }
2058     }
2059 
2060 
2061     /*
2062      * Emit alerts.  Caller must have synchronized with "this".
2063      */
2064     private void sendAlert(byte level, byte description) {
2065         // the connectionState cannot be cs_START
2066         if (connectionState >= cs_SENT_CLOSE) {
2067             return;
2068         }
2069 
2070         // For initial handshaking, don't send alert message to peer if
2071         // handshaker has not started.
2072         //
2073         // Shall we send an fatal alter to terminate the connection gracefully?
2074         if (connectionState <= cs_HANDSHAKE &&
2075                 (handshaker == null || !handshaker.started() ||
2076                         !handshaker.activated())) {
2077             return;
2078         }
2079 
2080         boolean useDebug = debug != null && Debug.isOn("ssl");
2081         if (useDebug) {
2082             synchronized (System.out) {
2083                 System.out.print(Thread.currentThread().getName());
2084                 System.out.print(", SEND " + protocolVersion + " ALERT:  ");
2085                 if (level == Alerts.alert_fatal) {
2086                     System.out.print("fatal, ");
2087                 } else if (level == Alerts.alert_warning) {
2088                     System.out.print("warning, ");
2089                 } else {
2090                     System.out.print("<level = " + (0x0ff & level) + ">, ");
2091                 }
2092                 System.out.println("description = "
2093                         + Alerts.alertDescription(description));
2094             }
2095         }
2096 
2097         try {
2098             writeAlert(level, description);
2099         } catch (IOException e) {
2100             if (useDebug) {
2101                 System.out.println(Thread.currentThread().getName() +
2102                     ", Exception sending alert: " + e);
2103             }
2104         }
2105     }
2106 
2107     //
2108     // VARIOUS OTHER METHODS
2109     //
2110 
2111     // used by Handshaker
2112     void changeWriteCiphers() throws IOException {
2113         Authenticator writeAuthenticator;
2114         CipherBox writeCipher;
2115         try {
2116             writeCipher = handshaker.newWriteCipher();
2117             writeAuthenticator = handshaker.newWriteAuthenticator();
2118         } catch (GeneralSecurityException e) {
2119             // "can't happen"
2120             throw new SSLException("Algorithm missing:  ", e);
2121         }
2122         outputRecord.changeWriteCiphers(writeAuthenticator, writeCipher);
2123     }
2124 
2125     /*
2126      * Updates the SSL version associated with this connection.
2127      * Called from Handshaker once it has determined the negotiated version.
2128      */
2129     synchronized void setVersion(ProtocolVersion protocolVersion) {
2130         this.protocolVersion = protocolVersion;
2131         outputRecord.setVersion(protocolVersion);
2132     }
2133 
2134     //
2135     // ONLY used by ClientHandshaker for the server hostname during handshaking
2136     //
2137     synchronized String getHost() {
2138         // Note that the host may be null or empty for localhost.
2139         if (host == null || host.length() == 0) {
2140             useImplicitHost(true);
2141         }
2142 
2143         return host;
2144     }
2145 
2146     /*
2147      * Try to set and use the implicit specified hostname
2148      */
2149     private synchronized void useImplicitHost(boolean noSniUpdate) {
2150 
2151         // Note: If the local name service is not trustworthy, reverse
2152         // host name resolution should not be performed for endpoint
2153         // identification.  Use the application original specified
2154         // hostname or IP address instead.
2155 
2156         // Get the original hostname via jdk.internal.misc.SharedSecrets
2157         InetAddress inetAddress = getInetAddress();
2158         if (inetAddress == null) {      // not connected
2159             return;
2160         }
2161 
2162         JavaNetInetAddressAccess jna =
2163                 SharedSecrets.getJavaNetInetAddressAccess();
2164         String originalHostname = jna.getOriginalHostName(inetAddress);
2165         if ((originalHostname != null) &&
2166                 (originalHostname.length() != 0)) {
2167 
2168             host = originalHostname;
2169             if (!noSniUpdate && serverNames.isEmpty() && !noSniExtension) {
2170                 serverNames =
2171                         Utilities.addToSNIServerNameList(serverNames, host);
2172 
2173                 if (!roleIsServer &&
2174                         (handshaker != null) && !handshaker.activated()) {
2175                     handshaker.setSNIServerNames(serverNames);
2176                 }
2177             }
2178 
2179             return;
2180         }
2181 
2182         // No explicitly specified hostname, no server name indication.
2183         if (!trustNameService) {
2184             // The local name service is not trustworthy, use IP address.
2185             host = inetAddress.getHostAddress();
2186         } else {
2187             // Use the underlying reverse host name resolution service.
2188             host = getInetAddress().getHostName();
2189         }
2190     }
2191 
2192     // ONLY used by HttpsClient to setup the URI specified hostname
2193     //
2194     // Please NOTE that this method MUST be called before calling to
2195     // SSLSocket.setSSLParameters(). Otherwise, the {@code host} parameter
2196     // may override SNIHostName in the customized server name indication.
2197     public synchronized void setHost(String host) {
2198         this.host = host;
2199         this.serverNames =
2200             Utilities.addToSNIServerNameList(this.serverNames, this.host);
2201 
2202         if (!roleIsServer && (handshaker != null) && !handshaker.activated()) {
2203             handshaker.setSNIServerNames(serverNames);
2204         }
2205     }
2206 
2207     /**
2208      * Gets an input stream to read from the peer on the other side.
2209      * Data read from this stream was always integrity protected in
2210      * transit, and will usually have been confidentiality protected.
2211      */
2212     @Override
2213     public synchronized InputStream getInputStream() throws IOException {
2214         if (isClosed()) {
2215             throw new SocketException("Socket is closed");
2216         }
2217 
2218         /*
2219          * Can't call isConnected() here, because the Handshakers
2220          * do some initialization before we actually connect.
2221          */
2222         if (connectionState == cs_START) {
2223             throw new SocketException("Socket is not connected");
2224         }
2225 
2226         return input;
2227     }
2228 
2229     /**
2230      * Gets an output stream to write to the peer on the other side.
2231      * Data written on this stream is always integrity protected, and
2232      * will usually be confidentiality protected.
2233      */
2234     @Override
2235     public synchronized OutputStream getOutputStream() throws IOException {
2236         if (isClosed()) {
2237             throw new SocketException("Socket is closed");
2238         }
2239 
2240         /*
2241          * Can't call isConnected() here, because the Handshakers
2242          * do some initialization before we actually connect.
2243          */
2244         if (connectionState == cs_START) {
2245             throw new SocketException("Socket is not connected");
2246         }
2247 
2248         return output;
2249     }
2250 
2251     /**
2252      * Returns the SSL Session in use by this connection.  These can
2253      * be long lived, and frequently correspond to an entire login session
2254      * for some user.
2255      */
2256     @Override
2257     public SSLSession getSession() {
2258         /*
2259          * Force a synchronous handshake, if appropriate.
2260          */
2261         if (getConnectionState() == cs_HANDSHAKE) {
2262             try {
2263                 // start handshaking, if failed, the connection will be closed.
2264                 startHandshake(false);
2265             } catch (IOException e) {
2266                 // handshake failed. log and return a nullSession
2267                 if (debug != null && Debug.isOn("handshake")) {
2268                       System.out.println(Thread.currentThread().getName() +
2269                           ", IOException in getSession():  " + e);
2270                 }
2271             }
2272         }
2273         synchronized (this) {
2274             return sess;
2275         }
2276     }
2277 
2278     @Override
2279     public synchronized SSLSession getHandshakeSession() {
2280         return handshakeSession;
2281     }
2282 
2283     synchronized void setHandshakeSession(SSLSessionImpl session) {
2284         // update the fragment size, which may be negotiated during handshaking
2285         inputRecord.changeFragmentSize(session.getNegotiatedMaxFragSize());
2286         outputRecord.changeFragmentSize(session.getNegotiatedMaxFragSize());
2287 
2288         handshakeSession = session;
2289     }
2290 
2291     /**
2292      * Controls whether new connections may cause creation of new SSL
2293      * sessions.
2294      *
2295      * As long as handshaking has not started, we can change
2296      * whether we enable session creations.  Otherwise,
2297      * we will need to wait for the next handshake.
2298      */
2299     @Override
2300     public synchronized void setEnableSessionCreation(boolean flag) {
2301         enableSessionCreation = flag;
2302 
2303         if ((handshaker != null) && !handshaker.activated()) {
2304             handshaker.setEnableSessionCreation(enableSessionCreation);
2305         }
2306     }
2307 
2308     /**
2309      * Returns true if new connections may cause creation of new SSL
2310      * sessions.
2311      */
2312     @Override
2313     public synchronized boolean getEnableSessionCreation() {
2314         return enableSessionCreation;
2315     }
2316 
2317 
2318     /**
2319      * Sets the flag controlling whether a server mode socket
2320      * *REQUIRES* SSL client authentication.
2321      *
2322      * As long as handshaking has not started, we can change
2323      * whether client authentication is needed.  Otherwise,
2324      * we will need to wait for the next handshake.
2325      */
2326     @Override
2327     public synchronized void setNeedClientAuth(boolean flag) {
2328         doClientAuth = (flag ? ClientAuthType.CLIENT_AUTH_REQUIRED :
2329                 ClientAuthType.CLIENT_AUTH_NONE);
2330 
2331         if ((handshaker != null) &&
2332                 (handshaker instanceof ServerHandshaker) &&
2333                 !handshaker.activated()) {
2334             ((ServerHandshaker) handshaker).setClientAuth(doClientAuth);
2335         }
2336     }
2337 
2338     @Override
2339     public synchronized boolean getNeedClientAuth() {
2340         return (doClientAuth == ClientAuthType.CLIENT_AUTH_REQUIRED);
2341     }
2342 
2343     /**
2344      * Sets the flag controlling whether a server mode socket
2345      * *REQUESTS* SSL client authentication.
2346      *
2347      * As long as handshaking has not started, we can change
2348      * whether client authentication is requested.  Otherwise,
2349      * we will need to wait for the next handshake.
2350      */
2351     @Override
2352     public synchronized void setWantClientAuth(boolean flag) {
2353         doClientAuth = (flag ? ClientAuthType.CLIENT_AUTH_REQUESTED :
2354                 ClientAuthType.CLIENT_AUTH_NONE);
2355 
2356         if ((handshaker != null) &&
2357                 (handshaker instanceof ServerHandshaker) &&
2358                 !handshaker.activated()) {
2359             ((ServerHandshaker) handshaker).setClientAuth(doClientAuth);
2360         }
2361     }
2362 
2363     @Override
2364     public synchronized boolean getWantClientAuth() {
2365         return (doClientAuth == ClientAuthType.CLIENT_AUTH_REQUESTED);
2366     }
2367 
2368 
2369     /**
2370      * Sets the flag controlling whether the socket is in SSL
2371      * client or server mode.  Must be called before any SSL
2372      * traffic has started.
2373      */
2374     @Override
2375     @SuppressWarnings("fallthrough")
2376     public synchronized void setUseClientMode(boolean flag) {
2377         switch (connectionState) {
2378 
2379         case cs_START:
2380             /*
2381              * If we need to change the socket mode and the enabled
2382              * protocols and cipher suites haven't specifically been
2383              * set by the user, change them to the corresponding
2384              * default ones.
2385              */
2386             if (roleIsServer != (!flag)) {
2387                 if (sslContext.isDefaultProtocolList(enabledProtocols)) {
2388                     enabledProtocols =
2389                             sslContext.getDefaultProtocolList(!flag);
2390                 }
2391 
2392                 if (sslContext.isDefaultCipherSuiteList(enabledCipherSuites)) {
2393                     enabledCipherSuites =
2394                             sslContext.getDefaultCipherSuiteList(!flag);
2395                 }
2396             }
2397 
2398             roleIsServer = !flag;
2399             break;
2400 
2401         case cs_HANDSHAKE:
2402             /*
2403              * If we have a handshaker, but haven't started
2404              * SSL traffic, we can throw away our current
2405              * handshaker, and start from scratch.  Don't
2406              * need to call doneConnect() again, we already
2407              * have the streams.
2408              */
2409             assert(handshaker != null);
2410             if (!handshaker.activated()) {
2411                 /*
2412                  * If we need to change the socket mode and the enabled
2413                  * protocols and cipher suites haven't specifically been
2414                  * set by the user, change them to the corresponding
2415                  * default ones.
2416                  */
2417                 if (roleIsServer != (!flag)) {
2418                     if (sslContext.isDefaultProtocolList(enabledProtocols)) {
2419                         enabledProtocols =
2420                                 sslContext.getDefaultProtocolList(!flag);
2421                     }
2422 
2423                     if (sslContext.isDefaultCipherSuiteList(
2424                                                     enabledCipherSuites)) {
2425                         enabledCipherSuites =
2426                             sslContext.getDefaultCipherSuiteList(!flag);
2427                     }
2428                 }
2429 
2430                 roleIsServer = !flag;
2431                 connectionState = cs_START;
2432                 initHandshaker();
2433                 break;
2434             }
2435 
2436             // If handshake has started, that's an error.  Fall through...
2437 
2438         default:
2439             if (debug != null && Debug.isOn("ssl")) {
2440                 System.out.println(Thread.currentThread().getName() +
2441                     ", setUseClientMode() invoked in state = " +
2442                     connectionState);
2443             }
2444             throw new IllegalArgumentException(
2445                 "Cannot change mode after SSL traffic has started");
2446         }
2447     }
2448 
2449     @Override
2450     public synchronized boolean getUseClientMode() {
2451         return !roleIsServer;
2452     }
2453 
2454 
2455     /**
2456      * Returns the names of the cipher suites which could be enabled for use
2457      * on an SSL connection.  Normally, only a subset of these will actually
2458      * be enabled by default, since this list may include cipher suites which
2459      * do not support the mutual authentication of servers and clients, or
2460      * which do not protect data confidentiality.  Servers may also need
2461      * certain kinds of certificates to use certain cipher suites.
2462      *
2463      * @return an array of cipher suite names
2464      */
2465     @Override
2466     public String[] getSupportedCipherSuites() {
2467         return sslContext.getSupportedCipherSuiteList().toStringArray();
2468     }
2469 
2470     /**
2471      * Controls which particular cipher suites are enabled for use on
2472      * this connection.  The cipher suites must have been listed by
2473      * getCipherSuites() as being supported.  Even if a suite has been
2474      * enabled, it might never be used if no peer supports it or the
2475      * requisite certificates (and private keys) are not available.
2476      *
2477      * @param suites Names of all the cipher suites to enable.
2478      */
2479     @Override
2480     public synchronized void setEnabledCipherSuites(String[] suites) {
2481         enabledCipherSuites = new CipherSuiteList(suites);
2482         if ((handshaker != null) && !handshaker.activated()) {
2483             handshaker.setEnabledCipherSuites(enabledCipherSuites);
2484         }
2485     }
2486 
2487     /**
2488      * Returns the names of the SSL cipher suites which are currently enabled
2489      * for use on this connection.  When an SSL socket is first created,
2490      * all enabled cipher suites <em>(a)</em> protect data confidentiality,
2491      * by traffic encryption, and <em>(b)</em> can mutually authenticate
2492      * both clients and servers.  Thus, in some environments, this value
2493      * might be empty.
2494      *
2495      * @return an array of cipher suite names
2496      */
2497     @Override
2498     public synchronized String[] getEnabledCipherSuites() {
2499         return enabledCipherSuites.toStringArray();
2500     }
2501 
2502 
2503     /**
2504      * Returns the protocols that are supported by this implementation.
2505      * A subset of the supported protocols may be enabled for this connection
2506      * @return an array of protocol names.
2507      */
2508     @Override
2509     public String[] getSupportedProtocols() {
2510         return sslContext.getSuportedProtocolList().toStringArray();
2511     }
2512 
2513     /**
2514      * Controls which protocols are enabled for use on
2515      * this connection.  The protocols must have been listed by
2516      * getSupportedProtocols() as being supported.
2517      *
2518      * @param protocols protocols to enable.
2519      * @exception IllegalArgumentException when one of the protocols
2520      *  named by the parameter is not supported.
2521      */
2522     @Override
2523     public synchronized void setEnabledProtocols(String[] protocols) {
2524         enabledProtocols = new ProtocolList(protocols);
2525         if ((handshaker != null) && !handshaker.activated()) {
2526             handshaker.setEnabledProtocols(enabledProtocols);
2527         }
2528     }
2529 
2530     @Override
2531     public synchronized String[] getEnabledProtocols() {
2532         return enabledProtocols.toStringArray();
2533     }
2534 
2535     /**
2536      * Assigns the socket timeout.
2537      * @see java.net.Socket#setSoTimeout
2538      */
2539     @Override
2540     public void setSoTimeout(int timeout) throws SocketException {
2541         if ((debug != null) && Debug.isOn("ssl")) {
2542             System.out.println(Thread.currentThread().getName() +
2543                 ", setSoTimeout(" + timeout + ") called");
2544         }
2545 
2546         super.setSoTimeout(timeout);
2547     }
2548 
2549     /**
2550      * Registers an event listener to receive notifications that an
2551      * SSL handshake has completed on this connection.
2552      */
2553     @Override
2554     public synchronized void addHandshakeCompletedListener(
2555             HandshakeCompletedListener listener) {
2556         if (listener == null) {
2557             throw new IllegalArgumentException("listener is null");
2558         }
2559         if (handshakeListeners == null) {
2560             handshakeListeners = new
2561                 HashMap<HandshakeCompletedListener, AccessControlContext>(4);
2562         }
2563         handshakeListeners.put(listener, AccessController.getContext());
2564     }
2565 
2566 
2567     /**
2568      * Removes a previously registered handshake completion listener.
2569      */
2570     @Override
2571     public synchronized void removeHandshakeCompletedListener(
2572             HandshakeCompletedListener listener) {
2573         if (handshakeListeners == null) {
2574             throw new IllegalArgumentException("no listeners");
2575         }
2576         if (handshakeListeners.remove(listener) == null) {
2577             throw new IllegalArgumentException("listener not registered");
2578         }
2579         if (handshakeListeners.isEmpty()) {
2580             handshakeListeners = null;
2581         }
2582     }
2583 
2584     /**
2585      * Returns the SSLParameters in effect for this SSLSocket.
2586      */
2587     @Override
2588     public synchronized SSLParameters getSSLParameters() {
2589         SSLParameters params = super.getSSLParameters();
2590 
2591         // the super implementation does not handle the following parameters
2592         params.setEndpointIdentificationAlgorithm(identificationProtocol);
2593         params.setAlgorithmConstraints(algorithmConstraints);
2594 
2595         if (sniMatchers.isEmpty() && !noSniMatcher) {
2596             // 'null' indicates none has been set
2597             params.setSNIMatchers(null);
2598         } else {
2599             params.setSNIMatchers(sniMatchers);
2600         }
2601 
2602         if (serverNames.isEmpty() && !noSniExtension) {
2603             // 'null' indicates none has been set
2604             params.setServerNames(null);
2605         } else {
2606             params.setServerNames(serverNames);
2607         }
2608 
2609         params.setUseCipherSuitesOrder(preferLocalCipherSuites);
2610         params.setMaximumPacketSize(maximumPacketSize);
2611         params.setApplicationProtocols(applicationProtocols);
2612 
2613         // DTLS handshake retransmissions parameter does not apply here.
2614 
2615         return params;
2616     }
2617 
2618     /**
2619      * Applies SSLParameters to this socket.
2620      */
2621     @Override
2622     public synchronized void setSSLParameters(SSLParameters params) {
2623         super.setSSLParameters(params);
2624 
2625         // the super implementation does not handle the following parameters
2626         identificationProtocol = params.getEndpointIdentificationAlgorithm();
2627         algorithmConstraints = params.getAlgorithmConstraints();
2628         preferLocalCipherSuites = params.getUseCipherSuitesOrder();
2629         maximumPacketSize = params.getMaximumPacketSize();
2630 
2631         // DTLS handshake retransmissions parameter does not apply here.
2632 
2633         if (maximumPacketSize != 0) {
2634             outputRecord.changePacketSize(maximumPacketSize);
2635         } else {
2636             // use the implicit maximum packet size.
2637             maximumPacketSize = outputRecord.getMaxPacketSize();
2638         }
2639 
2640         List<SNIServerName> sniNames = params.getServerNames();
2641         if (sniNames != null) {
2642             noSniExtension = sniNames.isEmpty();
2643             serverNames = sniNames;
2644         }
2645 
2646         Collection<SNIMatcher> matchers = params.getSNIMatchers();
2647         if (matchers != null) {
2648             noSniMatcher = matchers.isEmpty();
2649             sniMatchers = matchers;
2650         }
2651 
2652         applicationProtocols = params.getApplicationProtocols();
2653 
2654         if ((handshaker != null) && !handshaker.activated()) {
2655             handshaker.setIdentificationProtocol(identificationProtocol);
2656             handshaker.setAlgorithmConstraints(algorithmConstraints);
2657             handshaker.setMaximumPacketSize(maximumPacketSize);
2658             handshaker.setApplicationProtocols(applicationProtocols);
2659             if (roleIsServer) {
2660                 handshaker.setSNIMatchers(sniMatchers);
2661                 handshaker.setUseCipherSuitesOrder(preferLocalCipherSuites);
2662             } else {
2663                 handshaker.setSNIServerNames(serverNames);
2664             }
2665         }
2666     }
2667 
2668     @Override
2669     public synchronized String getApplicationProtocol() {
2670         return applicationProtocol;
2671     }
2672 
2673     @Override
2674     public synchronized String getHandshakeApplicationProtocol() {
2675         if ((handshaker != null) && handshaker.started()) {
2676             return handshaker.getHandshakeApplicationProtocol();
2677         }
2678         return null;
2679     }
2680 
2681     @Override
2682     public synchronized void setHandshakeApplicationProtocolSelector(
2683         BiFunction<SSLSocket, List<String>, String> selector) {
2684         applicationProtocolSelector = selector;
2685         if ((handshaker != null) && !handshaker.activated()) {
2686             handshaker.setApplicationProtocolSelectorSSLSocket(selector);
2687         }
2688     }
2689 
2690     @Override
2691     public synchronized BiFunction<SSLSocket, List<String>, String>
2692         getHandshakeApplicationProtocolSelector() {
2693         return this.applicationProtocolSelector;
2694     }
2695 
2696     //
2697     // We allocate a separate thread to deliver handshake completion
2698     // events.  This ensures that the notifications don't block the
2699     // protocol state machine.
2700     //
2701     private static class NotifyHandshake implements Runnable {
2702 
2703         private Set<Map.Entry<HandshakeCompletedListener,AccessControlContext>>
2704                 targets;        // who gets notified
2705         private HandshakeCompletedEvent event;          // the notification
2706 
2707         NotifyHandshake(
2708             Set<Map.Entry<HandshakeCompletedListener,AccessControlContext>>
2709             entrySet, HandshakeCompletedEvent e) {
2710 
2711             targets = new HashSet<>(entrySet);          // clone the entry set
2712             event = e;
2713         }
2714 
2715         @Override
2716         public void run() {
2717             // Don't need to synchronize, as it only runs in one thread.
2718             for (Map.Entry<HandshakeCompletedListener,AccessControlContext>
2719                 entry : targets) {
2720 
2721                 final HandshakeCompletedListener l = entry.getKey();
2722                 AccessControlContext acc = entry.getValue();
2723                 AccessController.doPrivileged(new PrivilegedAction<Void>() {
2724                     @Override
2725                     public Void run() {
2726                         l.handshakeCompleted(event);
2727                         return null;
2728                     }
2729                 }, acc);
2730             }
2731         }
2732     }
2733 
2734     /**
2735      * Returns a printable representation of this end of the connection.
2736      */
2737     @Override
2738     public String toString() {
2739         StringBuilder retval = new StringBuilder(80);
2740 
2741         retval.append(Integer.toHexString(hashCode()));
2742         retval.append("[");
2743         retval.append(sess.getCipherSuite());
2744         retval.append(": ");
2745 
2746         retval.append(super.toString());
2747         retval.append("]");
2748 
2749         return retval.toString();
2750     }
2751 }