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