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