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