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             IOException ioe = null;
 770             byte description = 0;    // 0: never used, make the compiler happy
 771             writeLock.lock();
 772             try {
 773                 outputRecord.deliver(source, offset, length);
 774             } catch (SSLHandshakeException she) {
 775                 // may be record sequence number overflow
 776                 description = Alerts.alert_handshake_failure;
 777                 ioe = she;
 778             } catch (IOException e) {
 779                 description = Alerts.alert_unexpected_message;
 780                 ioe = e;
 781             } finally {
 782                 writeLock.unlock();
 783             }
 784 
 785             // Be care of deadlock. Please don't place the call to fatal()
 786             // into the writeLock locked block.
 787             if (ioe != null) {
 788                 fatal(description, ioe);
 789             }
 790         }
 791 
 792         /*
 793          * Check the sequence number state
 794          *
 795          * Note that in order to maintain the connection I/O
 796          * properly, we check the sequence number after the last
 797          * record writing process. As we request renegotiation
 798          * or close the connection for wrapped sequence number
 799          * when there is enough sequence number space left to
 800          * handle a few more records, so the sequence number
 801          * of the last record cannot be wrapped.
 802          *
 803          * Don't bother to kickstart the renegotiation when the
 804          * local is asking for it.
 805          */
 806         if ((connectionState == cs_DATA) && outputRecord.seqNumIsHuge()) {
 807             /*
 808              * Ask for renegotiation when need to renew sequence number.
 809              *
 810              * Don't bother to kickstart the renegotiation when the local is
 811              * asking for it.
 812              */
 813             if (debug != null && Debug.isOn("ssl")) {
 814                 System.out.println(Thread.currentThread().getName() +
 815                         ", request renegotiation " +
 816                         "to avoid sequence number overflow");
 817             }
 818 
 819             startHandshake();
 820         }
 821     }
 822 
 823     /*
 824      * Alert record output.
 825      */
 826     void writeAlert(byte level, byte description) throws IOException {
 827 
 828         // If the record is a close notify alert, we need to honor
 829         // socket option SO_LINGER. Note that we will try to send
 830         // the close notify even if the SO_LINGER set to zero.
 831         if ((description == Alerts.alert_close_notify) && getSoLinger() >= 0) {
 832 
 833             // keep and clear the current thread interruption status.
 834             boolean interrupted = Thread.interrupted();
 835             try {
 836                 if (writeLock.tryLock(getSoLinger(), TimeUnit.SECONDS)) {
 837                     try {
 838                         outputRecord.encodeAlert(level, description);
 839                     } finally {
 840                         writeLock.unlock();
 841                     }
 842                 } else {
 843                     SSLException ssle = new SSLException(
 844                             "SO_LINGER timeout," +
 845                             " close_notify message cannot be sent.");
 846 
 847 
 848                     // For layered, non-autoclose sockets, we are not
 849                     // able to bring them into a usable state, so we
 850                     // treat it as fatal error.
 851                     if (isLayered() && !autoClose) {
 852                         // Note that the alert description is
 853                         // specified as -1, so no message will be send
 854                         // to peer anymore.
 855                         fatal((byte)(-1), ssle);
 856                     } else if ((debug != null) && Debug.isOn("ssl")) {
 857                         System.out.println(
 858                             Thread.currentThread().getName() +
 859                             ", received Exception: " + ssle);
 860                     }
 861 
 862                     // RFC2246 requires that the session becomes
 863                     // unresumable if any connection is terminated
 864                     // without proper close_notify messages with
 865                     // level equal to warning.
 866                     //
 867                     // RFC4346 no longer requires that a session not be
 868                     // resumed if failure to properly close a connection.
 869                     //
 870                     // We choose to make the session unresumable if
 871                     // failed to send the close_notify message.
 872                     //
 873                     sess.invalidate();
 874                 }
 875             } catch (InterruptedException ie) {
 876                 // keep interrupted status
 877                 interrupted = true;
 878             }
 879 
 880             // restore the interrupted status
 881             if (interrupted) {
 882                 Thread.currentThread().interrupt();
 883             }
 884         } else {
 885             writeLock.lock();
 886             try {
 887                 outputRecord.encodeAlert(level, description);
 888             } finally {
 889                 writeLock.unlock();
 890             }
 891         }
 892 
 893         // Don't bother to check sequence number overlap here.  If sequence
 894         // number is huge, there should be enough sequence number space to
 895         // request renegotiation in next application data read and write.
 896     }
 897 
 898 
 899     int bytesInCompletePacket() throws IOException {
 900         if (getConnectionState() == cs_HANDSHAKE) {
 901             performInitialHandshake();
 902         }
 903 
 904         synchronized (readLock) {
 905             int state = getConnectionState();
 906             if ((state == cs_CLOSED) ||
 907                     (state == cs_ERROR) || (state == cs_APP_CLOSED)) {
 908                 return -1;
 909             }
 910 
 911             try {
 912                 return inputRecord.bytesInCompletePacket(sockInput);
 913             } catch (EOFException eofe) {
 914                 boolean handshaking = (connectionState <= cs_HANDSHAKE);
 915                 boolean rethrow = requireCloseNotify || handshaking;
 916                 if ((debug != null) && Debug.isOn("ssl")) {
 917                     System.out.println(Thread.currentThread().getName() +
 918                         ", received EOFException: "
 919                         + (rethrow ? "error" : "ignored"));
 920                 }
 921 
 922                 if (!rethrow) {
 923                     // treat as if we had received a close_notify
 924                     closeInternal(false);
 925                 } else {
 926                     SSLException e;
 927                     if (handshaking) {
 928                         e = new SSLHandshakeException(
 929                             "Remote host terminated the handshake");
 930                     } else {
 931                         e = new SSLProtocolException(
 932                             "Remote host terminated the handshake");
 933                     }
 934                     e.initCause(eofe);
 935                     throw e;
 936                 }
 937             }
 938 
 939             return -1;
 940         }
 941     }
 942 
 943     // the caller have synchronized readLock
 944     void expectingFinishFlight() {
 945         inputRecord.expectingFinishFlight();
 946     }
 947 
 948     /*
 949      * Read an application data record.
 950      *
 951      * Alerts and handshake messages are internally handled directly.
 952      */
 953     int readRecord(ByteBuffer buffer) throws IOException {
 954         if (getConnectionState() == cs_HANDSHAKE) {
 955             performInitialHandshake();
 956         }
 957 
 958         return readRecord(buffer, true);
 959     }
 960 
 961     /*
 962      * Read a record, no application data input required.
 963      *
 964      * Alerts and handshake messages are internally handled directly.
 965      */
 966     int readRecord(boolean needAppData) throws IOException {
 967         return readRecord(null, needAppData);
 968     }
 969 
 970     /*
 971      * Clear the pipeline of records from the peer, optionally returning
 972      * application data.   Caller is responsible for knowing that it's
 973      * possible to do this kind of clearing, if they don't want app
 974      * data -- e.g. since it's the initial SSL handshake.
 975      *
 976      * Don't synchronize (this) during a blocking read() since it
 977      * protects data which is accessed on the write side as well.
 978      */
 979     private int readRecord(ByteBuffer buffer, boolean needAppData)
 980             throws IOException {
 981         int state;
 982 
 983         // readLock protects reading and processing of an SSLInputRecord.
 984         // It keeps the reading from sockInput and processing of the record
 985         // atomic so that no two threads can be blocked on the
 986         // read from the same input stream at the same time.
 987         // This is required for example when a reader thread is
 988         // blocked on the read and another thread is trying to
 989         // close the socket. For a non-autoclose, layered socket,
 990         // the thread performing the close needs to read the close_notify.
 991         //
 992         // Use readLock instead of 'this' for locking because
 993         // 'this' also protects data accessed during writing.
 994         synchronized (readLock) {
 995             /*
 996              * Read and handle records ... return application data
 997              * ONLY if it's needed.
 998              */
 999             Plaintext plainText = null;
1000             while (((state = getConnectionState()) != cs_CLOSED) &&
1001                     (state != cs_ERROR) && (state != cs_APP_CLOSED)) {
1002                 // clean the buffer
1003                 if (buffer != null) {
1004                     buffer.clear();
1005                 }
1006 
1007                 /*
1008                  * Read a record ... maybe emitting an alert if we get a
1009                  * comprehensible but unsupported "hello" message during
1010                  * format checking (e.g. V2).
1011                  */
1012                 try {
1013                     plainText = inputRecord.decode(sockInput, buffer);
1014                 } catch (BadPaddingException bpe) {
1015                     byte alertType = (state != cs_DATA) ?
1016                             Alerts.alert_handshake_failure :
1017                             Alerts.alert_bad_record_mac;
1018                     fatal(alertType, bpe.getMessage(), bpe);
1019                 } catch (SSLProtocolException spe) {
1020                     try {
1021                         fatal(Alerts.alert_unexpected_message, spe);
1022                     } catch (IOException x) {
1023                         // discard this exception, throw the original exception
1024                     }
1025                     throw spe;
1026                 } catch (SSLHandshakeException she) {
1027                     // may be record sequence number overflow
1028                     fatal(Alerts.alert_handshake_failure, she);
1029                 } catch (EOFException eof) {
1030                     boolean handshaking = (connectionState <= cs_HANDSHAKE);
1031                     boolean rethrow = requireCloseNotify || handshaking;
1032                     if ((debug != null) && Debug.isOn("ssl")) {
1033                         System.out.println(Thread.currentThread().getName() +
1034                             ", received EOFException: "
1035                             + (rethrow ? "error" : "ignored"));
1036                     }
1037                     if (rethrow) {
1038                         SSLException e;
1039                         if (handshaking) {
1040                             e = new SSLHandshakeException(
1041                                     "Remote host terminated the handshake");
1042                         } else {
1043                             e = new SSLProtocolException(
1044                                     "Remote host terminated the connection");
1045                         }
1046                         e.initCause(eof);
1047                         throw e;
1048                     } else {
1049                         // treat as if we had received a close_notify
1050                         closeInternal(false);
1051                         continue;
1052                     }
1053                 }
1054 
1055                 // PlainText should never be null. Process input record.
1056                 int volume = processInputRecord(plainText, needAppData);
1057 
1058                 if (plainText.contentType == Record.ct_application_data) {
1059                     return volume;
1060                 }
1061 
1062                 if (plainText.contentType == Record.ct_handshake) {
1063                     if (!needAppData && connectionState == cs_DATA) {
1064                         return volume;
1065                     }   // otherwise, need to read more for app data.
1066                 }
1067 
1068                 // continue to read more net data
1069             }   // while
1070 
1071             //
1072             // couldn't read, due to some kind of error
1073             //
1074             return -1;
1075         }  // readLock synchronization
1076     }
1077 
1078     /*
1079      * Process the plainText input record.
1080      */
1081     private synchronized int processInputRecord(
1082             Plaintext plainText, boolean needAppData) throws IOException {
1083 
1084         /*
1085          * Process the record.
1086          */
1087         int volume = 0;    // no application data
1088         switch (plainText.contentType) {
1089             case Record.ct_handshake:
1090                 /*
1091                  * Handshake messages always go to a pending session
1092                  * handshaker ... if there isn't one, create one.  This
1093                  * must work asynchronously, for renegotiation.
1094                  *
1095                  * NOTE that handshaking will either resume a session
1096                  * which was in the cache (and which might have other
1097                  * connections in it already), or else will start a new
1098                  * session (new keys exchanged) with just this connection
1099                  * in it.
1100                  */
1101                 initHandshaker();
1102                 if (!handshaker.activated()) {
1103                     // prior to handshaking, activate the handshake
1104                     if (connectionState == cs_RENEGOTIATE) {
1105                         // don't use SSLv2Hello when renegotiating
1106                         handshaker.activate(protocolVersion);
1107                     } else {
1108                         handshaker.activate(null);
1109                     }
1110                 }
1111 
1112                 /*
1113                  * process the handshake record ... may contain just
1114                  * a partial handshake message or multiple messages.
1115                  *
1116                  * The handshaker state machine will ensure that it's
1117                  * a finished message.
1118                  */
1119                 handshaker.processRecord(plainText.fragment, expectingFinished);
1120                 expectingFinished = false;
1121 
1122                 if (handshaker.invalidated) {
1123                     handshaker = null;
1124                     inputRecord.setHandshakeHash(null);
1125                     outputRecord.setHandshakeHash(null);
1126 
1127                     // if state is cs_RENEGOTIATE, revert it to cs_DATA
1128                     if (connectionState == cs_RENEGOTIATE) {
1129                         connectionState = cs_DATA;
1130                     }
1131                 } else if (handshaker.isDone()) {
1132                     // reset the parameters for secure renegotiation.
1133                     secureRenegotiation =
1134                                     handshaker.isSecureRenegotiation();
1135                     clientVerifyData = handshaker.getClientVerifyData();
1136                     serverVerifyData = handshaker.getServerVerifyData();
1137                     // set connection ALPN value
1138                     applicationProtocol =
1139                         handshaker.getHandshakeApplicationProtocol();
1140 
1141                     sess = handshaker.getSession();
1142                     handshakeSession = null;
1143                     handshaker = null;
1144                     inputRecord.setHandshakeHash(null);
1145                     outputRecord.setHandshakeHash(null);
1146                     connectionState = cs_DATA;
1147 
1148                     //
1149                     // Tell folk about handshake completion, but do
1150                     // it in a separate thread.
1151                     //
1152                     if (handshakeListeners != null) {
1153                         HandshakeCompletedEvent event =
1154                             new HandshakeCompletedEvent(this, sess);
1155 
1156                         Thread thread = new ManagedLocalsThread(
1157                             new NotifyHandshake(
1158                                 handshakeListeners.entrySet(), event),
1159                             "HandshakeCompletedNotify-Thread");
1160                         thread.start();
1161                     }
1162                 }
1163 
1164                 break;
1165 
1166             case Record.ct_application_data:
1167                 if (connectionState != cs_DATA
1168                         && connectionState != cs_RENEGOTIATE
1169                         && connectionState != cs_SENT_CLOSE) {
1170                     throw new SSLProtocolException(
1171                         "Data received in non-data state: " +
1172                         connectionState);
1173                 }
1174                 if (expectingFinished) {
1175                     throw new SSLProtocolException
1176                             ("Expecting finished message, received data");
1177                 }
1178                 if (!needAppData) {
1179                     throw new SSLException("Discarding app data");
1180                 }
1181 
1182                 volume = plainText.fragment.remaining();
1183                 break;
1184 
1185             case Record.ct_alert:
1186                 recvAlert(plainText.fragment);
1187                 break;
1188 
1189             case Record.ct_change_cipher_spec:
1190                 if ((connectionState != cs_HANDSHAKE
1191                         && connectionState != cs_RENEGOTIATE)) {
1192                     // For the CCS message arriving in the wrong state
1193                     fatal(Alerts.alert_unexpected_message,
1194                             "illegal change cipher spec msg, conn state = "
1195                             + connectionState);
1196                 } else if (plainText.fragment.remaining() != 1
1197                         || plainText.fragment.get() != 1) {
1198                     // For structural/content issues with the CCS
1199                     fatal(Alerts.alert_unexpected_message,
1200                             "Malformed change cipher spec msg");
1201                 }
1202 
1203                 //
1204                 // The first message after a change_cipher_spec
1205                 // record MUST be a "Finished" handshake record,
1206                 // else it's a protocol violation.  We force this
1207                 // to be checked by a minor tweak to the state
1208                 // machine.
1209                 //
1210                 handshaker.receiveChangeCipherSpec();
1211 
1212                 CipherBox readCipher;
1213                 Authenticator readAuthenticator;
1214                 try {
1215                     readCipher = handshaker.newReadCipher();
1216                     readAuthenticator = handshaker.newReadAuthenticator();
1217                 } catch (GeneralSecurityException e) {
1218                     // can't happen
1219                     throw new SSLException("Algorithm missing:  ", e);
1220                 }
1221                 inputRecord.changeReadCiphers(readAuthenticator, readCipher);
1222 
1223                 // next message MUST be a finished message
1224                 expectingFinished = true;
1225 
1226                 break;
1227 
1228             default:
1229                 //
1230                 // TLS requires that unrecognized records be ignored.
1231                 //
1232                 if (debug != null && Debug.isOn("ssl")) {
1233                     System.out.println(Thread.currentThread().getName() +
1234                         ", Received record type: " + plainText.contentType);
1235                 }
1236                 break;
1237         }
1238 
1239         /*
1240          * Check the sequence number state
1241          *
1242          * Note that in order to maintain the connection I/O
1243          * properly, we check the sequence number after the last
1244          * record reading process. As we request renegotiation
1245          * or close the connection for wrapped sequence number
1246          * when there is enough sequence number space left to
1247          * handle a few more records, so the sequence number
1248          * of the last record cannot be wrapped.
1249          *
1250          * Don't bother to kickstart the renegotiation when the
1251          * local is asking for it.
1252          */
1253         if ((connectionState == cs_DATA) && inputRecord.seqNumIsHuge()) {
1254             /*
1255              * Ask for renegotiation when need to renew sequence number.
1256              *
1257              * Don't bother to kickstart the renegotiation when the local is
1258              * asking for it.
1259              */
1260             if (debug != null && Debug.isOn("ssl")) {
1261                 System.out.println(Thread.currentThread().getName() +
1262                         ", request renegotiation " +
1263                         "to avoid sequence number overflow");
1264             }
1265 
1266             startHandshake();
1267         }
1268 
1269         return volume;
1270     }
1271 
1272 
1273     //
1274     // HANDSHAKE RELATED CODE
1275     //
1276 
1277     /**
1278      * Return the AppInputStream. For use by Handshaker only.
1279      */
1280     AppInputStream getAppInputStream() {
1281         return input;
1282     }
1283 
1284     /**
1285      * Return the AppOutputStream. For use by Handshaker only.
1286      */
1287     AppOutputStream getAppOutputStream() {
1288         return output;
1289     }
1290 
1291     /**
1292      * Initialize the handshaker object. This means:
1293      *
1294      *  . if a handshake is already in progress (state is cs_HANDSHAKE
1295      *    or cs_RENEGOTIATE), do nothing and return
1296      *
1297      *  . if the socket is already closed, throw an Exception (internal error)
1298      *
1299      *  . otherwise (cs_START or cs_DATA), create the appropriate handshaker
1300      *    object, and advance the connection state (to cs_HANDSHAKE or
1301      *    cs_RENEGOTIATE, respectively).
1302      *
1303      * This method is called right after a new socket is created, when
1304      * starting renegotiation, or when changing client/ server mode of the
1305      * socket.
1306      */
1307     private void initHandshaker() {
1308         switch (connectionState) {
1309 
1310         //
1311         // Starting a new handshake.
1312         //
1313         case cs_START:
1314         case cs_DATA:
1315             break;
1316 
1317         //
1318         // We're already in the middle of a handshake.
1319         //
1320         case cs_HANDSHAKE:
1321         case cs_RENEGOTIATE:
1322             return;
1323 
1324         //
1325         // Anyone allowed to call this routine is required to
1326         // do so ONLY if the connection state is reasonable...
1327         //
1328         default:
1329             throw new IllegalStateException("Internal error");
1330         }
1331 
1332         // state is either cs_START or cs_DATA
1333         if (connectionState == cs_START) {
1334             connectionState = cs_HANDSHAKE;
1335         } else { // cs_DATA
1336             connectionState = cs_RENEGOTIATE;
1337         }
1338 
1339         if (roleIsServer) {
1340             handshaker = new ServerHandshaker(this, sslContext,
1341                     enabledProtocols, doClientAuth,
1342                     protocolVersion, connectionState == cs_HANDSHAKE,
1343                     secureRenegotiation, clientVerifyData, serverVerifyData);
1344             handshaker.setSNIMatchers(sniMatchers);
1345             handshaker.setUseCipherSuitesOrder(preferLocalCipherSuites);
1346         } else {
1347             handshaker = new ClientHandshaker(this, sslContext,
1348                     enabledProtocols,
1349                     protocolVersion, connectionState == cs_HANDSHAKE,
1350                     secureRenegotiation, clientVerifyData, serverVerifyData);
1351             handshaker.setSNIServerNames(serverNames);
1352         }
1353         handshaker.setMaximumPacketSize(maximumPacketSize);
1354         handshaker.setEnabledCipherSuites(enabledCipherSuites);
1355         handshaker.setEnableSessionCreation(enableSessionCreation);
1356         handshaker.setApplicationProtocols(applicationProtocols);
1357     }
1358 
1359     /**
1360      * Synchronously perform the initial handshake.
1361      *
1362      * If the handshake is already in progress, this method blocks until it
1363      * is completed. If the initial handshake has already been completed,
1364      * it returns immediately.
1365      */
1366     private void performInitialHandshake() throws IOException {
1367         // use handshakeLock and the state check to make sure only
1368         // one thread performs the handshake
1369         synchronized (handshakeLock) {
1370             if (getConnectionState() == cs_HANDSHAKE) {
1371                 kickstartHandshake();
1372 
1373                 /*
1374                  * All initial handshaking goes through this operation
1375                  * until we have a valid SSL connection.
1376                  *
1377                  * Handle handshake messages only, need no application data.
1378                  */
1379                 readRecord(false);
1380             }
1381         }
1382     }
1383 
1384     /**
1385      * Starts an SSL handshake on this connection.
1386      */
1387     @Override
1388     public void startHandshake() throws IOException {
1389         // start an ssl handshake that could be resumed from timeout exception
1390         startHandshake(true);
1391     }
1392 
1393     /**
1394      * Starts an ssl handshake on this connection.
1395      *
1396      * @param resumable indicates the handshake process is resumable from a
1397      *          certain exception. If <code>resumable</code>, the socket will
1398      *          be reserved for exceptions like timeout; otherwise, the socket
1399      *          will be closed, no further communications could be done.
1400      */
1401     private void startHandshake(boolean resumable) throws IOException {
1402         checkWrite();
1403         try {
1404             if (getConnectionState() == cs_HANDSHAKE) {
1405                 // do initial handshake
1406                 performInitialHandshake();
1407             } else {
1408                 // start renegotiation
1409                 kickstartHandshake();
1410             }
1411         } catch (Exception e) {
1412             // shutdown and rethrow (wrapped) exception as appropriate
1413             handleException(e, resumable);
1414         }
1415     }
1416 
1417     /**
1418      * Kickstart the handshake if it is not already in progress.
1419      * This means:
1420      *
1421      *  . if handshaking is already underway, do nothing and return
1422      *
1423      *  . if the socket is not connected or already closed, throw an
1424      *    Exception.
1425      *
1426      *  . otherwise, call initHandshake() to initialize the handshaker
1427      *    object and progress the state. Then, send the initial
1428      *    handshaking message if appropriate (always on clients and
1429      *    on servers when renegotiating).
1430      */
1431     private synchronized void kickstartHandshake() throws IOException {
1432 
1433         switch (connectionState) {
1434 
1435         case cs_HANDSHAKE:
1436             // handshaker already setup, proceed
1437             break;
1438 
1439         case cs_DATA:
1440             if (!secureRenegotiation && !Handshaker.allowUnsafeRenegotiation) {
1441                 throw new SSLHandshakeException(
1442                         "Insecure renegotiation is not allowed");
1443             }
1444 
1445             if (!secureRenegotiation) {
1446                 if (debug != null && Debug.isOn("handshake")) {
1447                     System.out.println(
1448                         "Warning: Using insecure renegotiation");
1449                 }
1450             }
1451 
1452             // initialize the handshaker, move to cs_RENEGOTIATE
1453             initHandshaker();
1454             break;
1455 
1456         case cs_RENEGOTIATE:
1457             // handshaking already in progress, return
1458             return;
1459 
1460         /*
1461          * The only way to get a socket in the state is when
1462          * you have an unconnected socket.
1463          */
1464         case cs_START:
1465             throw new SocketException(
1466                 "handshaking attempted on unconnected socket");
1467 
1468         default:
1469             throw new SocketException("connection is closed");
1470         }
1471 
1472         //
1473         // Kickstart handshake state machine if we need to ...
1474         //
1475         // Note that handshaker.kickstart() writes the message
1476         // to its HandshakeOutStream, which calls back into
1477         // SSLSocketImpl.writeRecord() to send it.
1478         //
1479         if (!handshaker.activated()) {
1480              // prior to handshaking, activate the handshake
1481             if (connectionState == cs_RENEGOTIATE) {
1482                 // don't use SSLv2Hello when renegotiating
1483                 handshaker.activate(protocolVersion);
1484             } else {
1485                 handshaker.activate(null);
1486             }
1487 
1488             if (handshaker instanceof ClientHandshaker) {
1489                 // send client hello
1490                 handshaker.kickstart();
1491             } else {
1492                 if (connectionState == cs_HANDSHAKE) {
1493                     // initial handshake, no kickstart message to send
1494                 } else {
1495                     // we want to renegotiate, send hello request
1496                     handshaker.kickstart();
1497                 }
1498             }
1499         }
1500     }
1501 
1502     //
1503     // CLOSURE RELATED CALLS
1504     //
1505 
1506     /**
1507      * Return whether the socket has been explicitly closed by the application.
1508      */
1509     @Override
1510     public boolean isClosed() {
1511         return connectionState == cs_APP_CLOSED;
1512     }
1513 
1514     /**
1515      * Return whether we have reached end-of-file.
1516      *
1517      * If the socket is not connected, has been shutdown because of an error
1518      * or has been closed, throw an Exception.
1519      */
1520     boolean checkEOF() throws IOException {
1521         switch (getConnectionState()) {
1522         case cs_START:
1523             throw new SocketException("Socket is not connected");
1524 
1525         case cs_HANDSHAKE:
1526         case cs_DATA:
1527         case cs_RENEGOTIATE:
1528         case cs_SENT_CLOSE:
1529             return false;
1530 
1531         case cs_APP_CLOSED:
1532             throw new SocketException("Socket is closed");
1533 
1534         case cs_ERROR:
1535         case cs_CLOSED:
1536         default:
1537             // either closed because of error, or normal EOF
1538             if (closeReason == null) {
1539                 return true;
1540             }
1541             IOException e = new SSLException
1542                         ("Connection has been shutdown: " + closeReason);
1543             e.initCause(closeReason);
1544             throw e;
1545 
1546         }
1547     }
1548 
1549     /**
1550      * Check if we can write data to this socket. If not, throw an IOException.
1551      */
1552     void checkWrite() throws IOException {
1553         if (checkEOF() || (getConnectionState() == cs_SENT_CLOSE)) {
1554             // we are at EOF, write must throw Exception
1555             throw new SocketException("Connection closed by remote host");
1556         }
1557     }
1558 
1559     private void closeSocket() throws IOException {
1560 
1561         if ((debug != null) && Debug.isOn("ssl")) {
1562             System.out.println(Thread.currentThread().getName() +
1563                                                 ", called closeSocket()");
1564         }
1565 
1566         super.close();
1567     }
1568 
1569     private void closeSocket(boolean selfInitiated) throws IOException {
1570         if ((debug != null) && Debug.isOn("ssl")) {
1571             System.out.println(Thread.currentThread().getName() +
1572                 ", called closeSocket(" + selfInitiated + ")");
1573         }
1574         if (!isLayered() || autoClose) {
1575             super.close();
1576         } else if (selfInitiated) {
1577             // layered && non-autoclose
1578             // read close_notify alert to clear input stream
1579             waitForClose(false);
1580         }
1581     }
1582 
1583     /*
1584      * Closing the connection is tricky ... we can't officially close the
1585      * connection until we know the other end is ready to go away too,
1586      * and if ever the connection gets aborted we must forget session
1587      * state (it becomes invalid).
1588      */
1589 
1590     /**
1591      * Closes the SSL connection.  SSL includes an application level
1592      * shutdown handshake; you should close SSL sockets explicitly
1593      * rather than leaving it for finalization, so that your remote
1594      * peer does not experience a protocol error.
1595      */
1596     @Override
1597     public void close() throws IOException {
1598         if ((debug != null) && Debug.isOn("ssl")) {
1599             System.out.println(Thread.currentThread().getName() +
1600                                                     ", called close()");
1601         }
1602         closeInternal(true);  // caller is initiating close
1603 
1604         // Clearup the resources.
1605         try {
1606             synchronized (readLock) {
1607                 inputRecord.close();
1608             }
1609 
1610             writeLock.lock();
1611             try {
1612                 outputRecord.close();
1613             } finally {
1614                 writeLock.unlock();
1615             }
1616         } catch (IOException ioe) {
1617            // ignore
1618         }
1619 
1620         setConnectionState(cs_APP_CLOSED);
1621     }
1622 
1623     /**
1624      * Don't synchronize the whole method because waitForClose()
1625      * (which calls readRecord()) might be called.
1626      *
1627      * @param selfInitiated Indicates which party initiated the close.
1628      * If selfInitiated, this side is initiating a close; for layered and
1629      * non-autoclose socket, wait for close_notify response.
1630      * If !selfInitiated, peer sent close_notify; we reciprocate but
1631      * no need to wait for response.
1632      */
1633     private void closeInternal(boolean selfInitiated) throws IOException {
1634         if ((debug != null) && Debug.isOn("ssl")) {
1635             System.out.println(Thread.currentThread().getName() +
1636                         ", called closeInternal(" + selfInitiated + ")");
1637         }
1638 
1639         int state = getConnectionState();
1640         boolean closeSocketCalled = false;
1641         Throwable cachedThrowable = null;
1642         try {
1643             switch (state) {
1644             case cs_START:
1645                 // unconnected socket or handshaking has not been initialized
1646                 closeSocket(selfInitiated);
1647                 break;
1648 
1649             /*
1650              * If we're closing down due to error, we already sent (or else
1651              * received) the fatal alert ... no niceties, blow the connection
1652              * away as quickly as possible (even if we didn't allocate the
1653              * socket ourselves; it's unusable, regardless).
1654              */
1655             case cs_ERROR:
1656                 closeSocket();
1657                 break;
1658 
1659             /*
1660              * Sometimes close() gets called more than once.
1661              */
1662             case cs_CLOSED:
1663             case cs_APP_CLOSED:
1664                  break;
1665 
1666             /*
1667              * Otherwise we indicate clean termination.
1668              */
1669             // case cs_HANDSHAKE:
1670             // case cs_DATA:
1671             // case cs_RENEGOTIATE:
1672             // case cs_SENT_CLOSE:
1673             default:
1674                 synchronized (this) {
1675                     if (((state = getConnectionState()) == cs_CLOSED) ||
1676                        (state == cs_ERROR) || (state == cs_APP_CLOSED)) {
1677                         return;  // connection was closed while we waited
1678                     }
1679                     if (state != cs_SENT_CLOSE) {
1680                         try {
1681                             warning(Alerts.alert_close_notify);
1682                             connectionState = cs_SENT_CLOSE;
1683                         } catch (Throwable th) {
1684                             // we need to ensure socket is closed out
1685                             // if we encounter any errors.
1686                             connectionState = cs_ERROR;
1687                             // cache this for later use
1688                             cachedThrowable = th;
1689                             closeSocketCalled = true;
1690                             closeSocket(selfInitiated);
1691                         }
1692                     }
1693                 }
1694                 // If state was cs_SENT_CLOSE before, we don't do the actual
1695                 // closing since it is already in progress.
1696                 if (state == cs_SENT_CLOSE) {
1697                     if (debug != null && Debug.isOn("ssl")) {
1698                         System.out.println(Thread.currentThread().getName() +
1699                             ", close invoked again; state = " +
1700                             getConnectionState());
1701                     }
1702                     if (selfInitiated == false) {
1703                         // We were called because a close_notify message was
1704                         // received. This may be due to another thread calling
1705                         // read() or due to our call to waitForClose() below.
1706                         // In either case, just return.
1707                         return;
1708                     }
1709                     // Another thread explicitly called close(). We need to
1710                     // wait for the closing to complete before returning.
1711                     synchronized (this) {
1712                         while (connectionState < cs_CLOSED) {
1713                             try {
1714                                 this.wait();
1715                             } catch (InterruptedException e) {
1716                                 // ignore
1717                             }
1718                         }
1719                     }
1720                     if ((debug != null) && Debug.isOn("ssl")) {
1721                         System.out.println(Thread.currentThread().getName() +
1722                             ", after primary close; state = " +
1723                             getConnectionState());
1724                     }
1725                     return;
1726                 }
1727 
1728                 if (!closeSocketCalled)  {
1729                     closeSocketCalled = true;
1730                     closeSocket(selfInitiated);
1731                 }
1732 
1733                 break;
1734             }
1735         } finally {
1736             synchronized (this) {
1737                 // Upon exit from this method, the state is always >= cs_CLOSED
1738                 connectionState = (connectionState == cs_APP_CLOSED)
1739                                 ? cs_APP_CLOSED : cs_CLOSED;
1740                 // notify any threads waiting for the closing to finish
1741                 this.notifyAll();
1742             }
1743 
1744             if (cachedThrowable != null) {
1745                /*
1746                 * Rethrow the error to the calling method
1747                 * The Throwable caught can only be an Error or RuntimeException
1748                 */
1749                 if (cachedThrowable instanceof Error) {
1750                     throw (Error)cachedThrowable;
1751                 } else if (cachedThrowable instanceof RuntimeException) {
1752                     throw (RuntimeException)cachedThrowable;
1753                 }   // Otherwise, unlikely
1754             }
1755         }
1756     }
1757 
1758     /**
1759      * Reads a close_notify or a fatal alert from the input stream.
1760      * Keep reading records until we get a close_notify or until
1761      * the connection is otherwise closed.  The close_notify or alert
1762      * might be read by another reader,
1763      * which will then process the close and set the connection state.
1764      */
1765     void waitForClose(boolean rethrow) throws IOException {
1766         if (debug != null && Debug.isOn("ssl")) {
1767             System.out.println(Thread.currentThread().getName() +
1768                 ", waiting for close_notify or alert: state "
1769                 + getConnectionState());
1770         }
1771 
1772         try {
1773             int state;
1774 
1775             while (((state = getConnectionState()) != cs_CLOSED) &&
1776                    (state != cs_ERROR) && (state != cs_APP_CLOSED)) {
1777 
1778                 // Ask for app data and then throw it away
1779                 try {
1780                     readRecord(true);
1781                 } catch (SocketTimeoutException e) {
1782                     // if time out, ignore the exception and continue
1783                 }
1784             }
1785         } catch (IOException e) {
1786             if (debug != null && Debug.isOn("ssl")) {
1787                 System.out.println(Thread.currentThread().getName() +
1788                     ", Exception while waiting for close " +e);
1789             }
1790             if (rethrow) {
1791                 throw e; // pass exception up
1792             }
1793         }
1794     }
1795 
1796     //
1797     // EXCEPTION AND ALERT HANDLING
1798     //
1799 
1800     /**
1801      * Handle an exception. This method is called by top level exception
1802      * handlers (in read(), write()) to make sure we always shutdown the
1803      * connection correctly and do not pass runtime exception to the
1804      * application.
1805      */
1806     void handleException(Exception e) throws IOException {
1807         handleException(e, true);
1808     }
1809 
1810     /**
1811      * Handle an exception. This method is called by top level exception
1812      * handlers (in read(), write(), startHandshake()) to make sure we
1813      * always shutdown the connection correctly and do not pass runtime
1814      * exception to the application.
1815      *
1816      * This method never returns normally, it always throws an IOException.
1817      *
1818      * We first check if the socket has already been shutdown because of an
1819      * error. If so, we just rethrow the exception. If the socket has not
1820      * been shutdown, we sent a fatal alert and remember the exception.
1821      *
1822      * @param e the Exception
1823      * @param resumable indicates the caller process is resumable from the
1824      *          exception. If <code>resumable</code>, the socket will be
1825      *          reserved for exceptions like timeout; otherwise, the socket
1826      *          will be closed, no further communications could be done.
1827      */
1828     private synchronized void handleException(Exception e, boolean resumable)
1829         throws IOException {
1830         if ((debug != null) && Debug.isOn("ssl")) {
1831             System.out.println(Thread.currentThread().getName() +
1832                         ", handling exception: " + e.toString());
1833         }
1834 
1835         // don't close the Socket in case of timeouts or interrupts if
1836         // the process is resumable.
1837         if (e instanceof InterruptedIOException && resumable) {
1838             throw (IOException)e;
1839         }
1840 
1841         // if we've already shutdown because of an error,
1842         // there is nothing to do except rethrow the exception
1843         if (closeReason != null) {
1844             if (e instanceof IOException) { // includes SSLException
1845                 throw (IOException)e;
1846             } else {
1847                 // this is odd, not an IOException.
1848                 // normally, this should not happen
1849                 // if closeReason has been already been set
1850                 throw Alerts.getSSLException(Alerts.alert_internal_error, e,
1851                                       "Unexpected exception");
1852             }
1853         }
1854 
1855         // need to perform error shutdown
1856         boolean isSSLException = (e instanceof SSLException);
1857         if ((!isSSLException) && (e instanceof IOException)) {
1858             // IOException from the socket
1859             // this means the TCP connection is already dead
1860             // we call fatal just to set the error status
1861             try {
1862                 fatal(Alerts.alert_unexpected_message, e);
1863             } catch (IOException ee) {
1864                 // ignore (IOException wrapped in SSLException)
1865             }
1866             // rethrow original IOException
1867             throw (IOException)e;
1868         }
1869 
1870         // must be SSLException or RuntimeException
1871         byte alertType;
1872         if (isSSLException) {
1873             if (e instanceof SSLHandshakeException) {
1874                 alertType = Alerts.alert_handshake_failure;
1875             } else {
1876                 alertType = Alerts.alert_unexpected_message;
1877             }
1878         } else {
1879             alertType = Alerts.alert_internal_error;
1880         }
1881         fatal(alertType, e);
1882     }
1883 
1884     /*
1885      * Send a warning alert.
1886      */
1887     void warning(byte description) {
1888         sendAlert(Alerts.alert_warning, description);
1889     }
1890 
1891     synchronized void fatal(byte description, String diagnostic)
1892             throws IOException {
1893         fatal(description, diagnostic, null);
1894     }
1895 
1896     synchronized void fatal(byte description, Throwable cause)
1897             throws IOException {
1898         fatal(description, null, cause);
1899     }
1900 
1901     /*
1902      * Send a fatal alert, and throw an exception so that callers will
1903      * need to stand on their heads to accidentally continue processing.
1904      */
1905     synchronized void fatal(byte description, String diagnostic,
1906             Throwable cause) throws IOException {
1907 
1908         // Be care of deadlock. Please don't synchronize readLock.
1909         try {
1910             inputRecord.close();
1911         } catch (IOException ioe) {
1912             // ignore
1913         }
1914 
1915         sess.invalidate();
1916         if (handshakeSession != null) {
1917             handshakeSession.invalidate();
1918         }
1919 
1920         int oldState = connectionState;
1921         if (connectionState < cs_ERROR) {
1922             connectionState = cs_ERROR;
1923         }
1924 
1925         /*
1926          * Has there been an error received yet?  If not, remember it.
1927          * By RFC 2246, we don't bother waiting for a response.
1928          * Fatal errors require immediate shutdown.
1929          */
1930         if (closeReason == null) {
1931             /*
1932              * Try to clear the kernel buffer to avoid TCP connection resets.
1933              */
1934             if (oldState == cs_HANDSHAKE) {
1935                 sockInput.skip(sockInput.available());
1936             }
1937 
1938             // If the description equals -1, the alert won't be sent to peer.
1939             if (description != -1) {
1940                 sendAlert(Alerts.alert_fatal, description);
1941             }
1942             if (cause instanceof SSLException) { // only true if != null
1943                 closeReason = (SSLException)cause;
1944             } else {
1945                 closeReason =
1946                     Alerts.getSSLException(description, cause, diagnostic);
1947             }
1948         }
1949 
1950         /*
1951          * Clean up our side.
1952          */
1953         closeSocket();
1954 
1955         // Be care of deadlock. Please don't synchronize writeLock.
1956         try {
1957             outputRecord.close();
1958         } catch (IOException ioe) {
1959             // ignore
1960         }
1961 
1962         throw closeReason;
1963     }
1964 
1965 
1966     /*
1967      * Process an incoming alert ... caller must already have synchronized
1968      * access to "this".
1969      */
1970     private void recvAlert(ByteBuffer fragment) throws IOException {
1971         byte level = fragment.get();
1972         byte description = fragment.get();
1973 
1974         if (description == -1) { // check for short message
1975             fatal(Alerts.alert_illegal_parameter, "Short alert message");
1976         }
1977 
1978         if (debug != null && (Debug.isOn("record") ||
1979                 Debug.isOn("handshake"))) {
1980             synchronized (System.out) {
1981                 System.out.print(Thread.currentThread().getName());
1982                 System.out.print(", RECV " + protocolVersion + " ALERT:  ");
1983                 if (level == Alerts.alert_fatal) {
1984                     System.out.print("fatal, ");
1985                 } else if (level == Alerts.alert_warning) {
1986                     System.out.print("warning, ");
1987                 } else {
1988                     System.out.print("<level " + (0x0ff & level) + ">, ");
1989                 }
1990                 System.out.println(Alerts.alertDescription(description));
1991             }
1992         }
1993 
1994         if (level == Alerts.alert_warning) {
1995             if (description == Alerts.alert_close_notify) {
1996                 if (connectionState == cs_HANDSHAKE) {
1997                     fatal(Alerts.alert_unexpected_message,
1998                                 "Received close_notify during handshake");
1999                 } else {
2000                     closeInternal(false);  // reply to close
2001                 }
2002             } else {
2003 
2004                 //
2005                 // The other legal warnings relate to certificates,
2006                 // e.g. no_certificate, bad_certificate, etc; these
2007                 // are important to the handshaking code, which can
2008                 // also handle illegal protocol alerts if needed.
2009                 //
2010                 if (handshaker != null) {
2011                     handshaker.handshakeAlert(description);
2012                 }
2013             }
2014         } else { // fatal or unknown level
2015             String reason = "Received fatal alert: "
2016                 + Alerts.alertDescription(description);
2017             if (closeReason == null) {
2018                 closeReason = Alerts.getSSLException(description, reason);
2019             }
2020             fatal(Alerts.alert_unexpected_message, reason);
2021         }
2022     }
2023 
2024 
2025     /*
2026      * Emit alerts.  Caller must have synchronized with "this".
2027      */
2028     private void sendAlert(byte level, byte description) {
2029         // the connectionState cannot be cs_START
2030         if (connectionState >= cs_SENT_CLOSE) {
2031             return;
2032         }
2033 
2034         // For initial handshaking, don't send alert message to peer if
2035         // handshaker has not started.
2036         //
2037         // Shall we send an fatal alter to terminate the connection gracefully?
2038         if (connectionState <= cs_HANDSHAKE &&
2039                 (handshaker == null || !handshaker.started() ||
2040                         !handshaker.activated())) {
2041             return;
2042         }
2043 
2044         boolean useDebug = debug != null && Debug.isOn("ssl");
2045         if (useDebug) {
2046             synchronized (System.out) {
2047                 System.out.print(Thread.currentThread().getName());
2048                 System.out.print(", SEND " + protocolVersion + " ALERT:  ");
2049                 if (level == Alerts.alert_fatal) {
2050                     System.out.print("fatal, ");
2051                 } else if (level == Alerts.alert_warning) {
2052                     System.out.print("warning, ");
2053                 } else {
2054                     System.out.print("<level = " + (0x0ff & level) + ">, ");
2055                 }
2056                 System.out.println("description = "
2057                         + Alerts.alertDescription(description));
2058             }
2059         }
2060 
2061         try {
2062             writeAlert(level, description);
2063         } catch (IOException e) {
2064             if (useDebug) {
2065                 System.out.println(Thread.currentThread().getName() +
2066                     ", Exception sending alert: " + e);
2067             }
2068         }
2069     }
2070 
2071     //
2072     // VARIOUS OTHER METHODS
2073     //
2074 
2075     // used by Handshaker
2076     void changeWriteCiphers() throws IOException {
2077         Authenticator writeAuthenticator;
2078         CipherBox writeCipher;
2079         try {
2080             writeCipher = handshaker.newWriteCipher();
2081             writeAuthenticator = handshaker.newWriteAuthenticator();
2082         } catch (GeneralSecurityException e) {
2083             // "can't happen"
2084             throw new SSLException("Algorithm missing:  ", e);
2085         }
2086         outputRecord.changeWriteCiphers(writeAuthenticator, writeCipher);
2087     }
2088 
2089     /*
2090      * Updates the SSL version associated with this connection.
2091      * Called from Handshaker once it has determined the negotiated version.
2092      */
2093     synchronized void setVersion(ProtocolVersion protocolVersion) {
2094         this.protocolVersion = protocolVersion;
2095         outputRecord.setVersion(protocolVersion);
2096     }
2097 
2098     synchronized String getHost() {
2099         // Note that the host may be null or empty for localhost.
2100         if (host == null || host.length() == 0) {
2101             if (!trustNameService) {
2102                 // If the local name service is not trustworthy, reverse host
2103                 // name resolution should not be performed for endpoint
2104                 // identification.  Use the application original specified
2105                 // hostname or IP address instead.
2106                 host = getOriginalHostname(getInetAddress());
2107             } else {
2108                 host = getInetAddress().getHostName();
2109             }
2110         }
2111 
2112         return host;
2113     }
2114 
2115     /*
2116      * Get the original application specified hostname.
2117      */
2118     private static String getOriginalHostname(InetAddress inetAddress) {
2119         /*
2120          * Get the original hostname via jdk.internal.misc.SharedSecrets.
2121          */
2122         JavaNetInetAddressAccess jna = SharedSecrets.getJavaNetInetAddressAccess();
2123         String originalHostname = jna.getOriginalHostName(inetAddress);
2124 
2125         /*
2126          * If no application specified hostname, use the IP address.
2127          */
2128         if (originalHostname == null || originalHostname.length() == 0) {
2129             originalHostname = inetAddress.getHostAddress();
2130         }
2131 
2132         return originalHostname;
2133     }
2134 
2135     // ONLY used by HttpsClient to setup the URI specified hostname
2136     //
2137     // Please NOTE that this method MUST be called before calling to
2138     // SSLSocket.setSSLParameters(). Otherwise, the {@code host} parameter
2139     // may override SNIHostName in the customized server name indication.
2140     public synchronized void setHost(String host) {
2141         this.host = host;
2142         this.serverNames =
2143             Utilities.addToSNIServerNameList(this.serverNames, this.host);
2144     }
2145 
2146     /**
2147      * Gets an input stream to read from the peer on the other side.
2148      * Data read from this stream was always integrity protected in
2149      * transit, and will usually have been confidentiality protected.
2150      */
2151     @Override
2152     public synchronized InputStream getInputStream() throws IOException {
2153         if (isClosed()) {
2154             throw new SocketException("Socket is closed");
2155         }
2156 
2157         /*
2158          * Can't call isConnected() here, because the Handshakers
2159          * do some initialization before we actually connect.
2160          */
2161         if (connectionState == cs_START) {
2162             throw new SocketException("Socket is not connected");
2163         }
2164 
2165         return input;
2166     }
2167 
2168     /**
2169      * Gets an output stream to write to the peer on the other side.
2170      * Data written on this stream is always integrity protected, and
2171      * will usually be confidentiality protected.
2172      */
2173     @Override
2174     public synchronized OutputStream getOutputStream() throws IOException {
2175         if (isClosed()) {
2176             throw new SocketException("Socket is closed");
2177         }
2178 
2179         /*
2180          * Can't call isConnected() here, because the Handshakers
2181          * do some initialization before we actually connect.
2182          */
2183         if (connectionState == cs_START) {
2184             throw new SocketException("Socket is not connected");
2185         }
2186 
2187         return output;
2188     }
2189 
2190     /**
2191      * Returns the SSL Session in use by this connection.  These can
2192      * be long lived, and frequently correspond to an entire login session
2193      * for some user.
2194      */
2195     @Override
2196     public SSLSession getSession() {
2197         /*
2198          * Force a synchronous handshake, if appropriate.
2199          */
2200         if (getConnectionState() == cs_HANDSHAKE) {
2201             try {
2202                 // start handshaking, if failed, the connection will be closed.
2203                 startHandshake(false);
2204             } catch (IOException e) {
2205                 // handshake failed. log and return a nullSession
2206                 if (debug != null && Debug.isOn("handshake")) {
2207                       System.out.println(Thread.currentThread().getName() +
2208                           ", IOException in getSession():  " + e);
2209                 }
2210             }
2211         }
2212         synchronized (this) {
2213             return sess;
2214         }
2215     }
2216 
2217     @Override
2218     public synchronized SSLSession getHandshakeSession() {
2219         return handshakeSession;
2220     }
2221 
2222     synchronized void setHandshakeSession(SSLSessionImpl session) {
2223         // update the fragment size, which may be negotiated during handshaking
2224         inputRecord.changeFragmentSize(session.getNegotiatedMaxFragSize());
2225         outputRecord.changeFragmentSize(session.getNegotiatedMaxFragSize());
2226 
2227         handshakeSession = session;
2228     }
2229 
2230     /**
2231      * Controls whether new connections may cause creation of new SSL
2232      * sessions.
2233      *
2234      * As long as handshaking has not started, we can change
2235      * whether we enable session creations.  Otherwise,
2236      * we will need to wait for the next handshake.
2237      */
2238     @Override
2239     public synchronized void setEnableSessionCreation(boolean flag) {
2240         enableSessionCreation = flag;
2241 
2242         if ((handshaker != null) && !handshaker.activated()) {
2243             handshaker.setEnableSessionCreation(enableSessionCreation);
2244         }
2245     }
2246 
2247     /**
2248      * Returns true if new connections may cause creation of new SSL
2249      * sessions.
2250      */
2251     @Override
2252     public synchronized boolean getEnableSessionCreation() {
2253         return enableSessionCreation;
2254     }
2255 
2256 
2257     /**
2258      * Sets the flag controlling whether a server mode socket
2259      * *REQUIRES* SSL client authentication.
2260      *
2261      * As long as handshaking has not started, we can change
2262      * whether client authentication is needed.  Otherwise,
2263      * we will need to wait for the next handshake.
2264      */
2265     @Override
2266     public synchronized void setNeedClientAuth(boolean flag) {
2267         doClientAuth = (flag ? ClientAuthType.CLIENT_AUTH_REQUIRED :
2268                 ClientAuthType.CLIENT_AUTH_NONE);
2269 
2270         if ((handshaker != null) &&
2271                 (handshaker instanceof ServerHandshaker) &&
2272                 !handshaker.activated()) {
2273             ((ServerHandshaker) handshaker).setClientAuth(doClientAuth);
2274         }
2275     }
2276 
2277     @Override
2278     public synchronized boolean getNeedClientAuth() {
2279         return (doClientAuth == ClientAuthType.CLIENT_AUTH_REQUIRED);
2280     }
2281 
2282     /**
2283      * Sets the flag controlling whether a server mode socket
2284      * *REQUESTS* SSL client authentication.
2285      *
2286      * As long as handshaking has not started, we can change
2287      * whether client authentication is requested.  Otherwise,
2288      * we will need to wait for the next handshake.
2289      */
2290     @Override
2291     public synchronized void setWantClientAuth(boolean flag) {
2292         doClientAuth = (flag ? ClientAuthType.CLIENT_AUTH_REQUESTED :
2293                 ClientAuthType.CLIENT_AUTH_NONE);
2294 
2295         if ((handshaker != null) &&
2296                 (handshaker instanceof ServerHandshaker) &&
2297                 !handshaker.activated()) {
2298             ((ServerHandshaker) handshaker).setClientAuth(doClientAuth);
2299         }
2300     }
2301 
2302     @Override
2303     public synchronized boolean getWantClientAuth() {
2304         return (doClientAuth == ClientAuthType.CLIENT_AUTH_REQUESTED);
2305     }
2306 
2307 
2308     /**
2309      * Sets the flag controlling whether the socket is in SSL
2310      * client or server mode.  Must be called before any SSL
2311      * traffic has started.
2312      */
2313     @Override
2314     @SuppressWarnings("fallthrough")
2315     public synchronized void setUseClientMode(boolean flag) {
2316         switch (connectionState) {
2317 
2318         case cs_START:
2319             /*
2320              * If we need to change the socket mode and the enabled
2321              * protocols and cipher suites haven't specifically been
2322              * set by the user, change them to the corresponding
2323              * default ones.
2324              */
2325             if (roleIsServer != (!flag)) {
2326                 if (sslContext.isDefaultProtocolList(enabledProtocols)) {
2327                     enabledProtocols =
2328                             sslContext.getDefaultProtocolList(!flag);
2329                 }
2330 
2331                 if (sslContext.isDefaultCipherSuiteList(enabledCipherSuites)) {
2332                     enabledCipherSuites =
2333                             sslContext.getDefaultCipherSuiteList(!flag);
2334                 }
2335             }
2336 
2337             roleIsServer = !flag;
2338             break;
2339 
2340         case cs_HANDSHAKE:
2341             /*
2342              * If we have a handshaker, but haven't started
2343              * SSL traffic, we can throw away our current
2344              * handshaker, and start from scratch.  Don't
2345              * need to call doneConnect() again, we already
2346              * have the streams.
2347              */
2348             assert(handshaker != null);
2349             if (!handshaker.activated()) {
2350                 /*
2351                  * If we need to change the socket mode and the enabled
2352                  * protocols and cipher suites haven't specifically been
2353                  * set by the user, change them to the corresponding
2354                  * default ones.
2355                  */
2356                 if (roleIsServer != (!flag)) {
2357                     if (sslContext.isDefaultProtocolList(enabledProtocols)) {
2358                         enabledProtocols =
2359                                 sslContext.getDefaultProtocolList(!flag);
2360                     }
2361 
2362                     if (sslContext.isDefaultCipherSuiteList(
2363                                                     enabledCipherSuites)) {
2364                         enabledCipherSuites =
2365                             sslContext.getDefaultCipherSuiteList(!flag);
2366                     }
2367                 }
2368 
2369                 roleIsServer = !flag;
2370                 connectionState = cs_START;
2371                 initHandshaker();
2372                 break;
2373             }
2374 
2375             // If handshake has started, that's an error.  Fall through...
2376 
2377         default:
2378             if (debug != null && Debug.isOn("ssl")) {
2379                 System.out.println(Thread.currentThread().getName() +
2380                     ", setUseClientMode() invoked in state = " +
2381                     connectionState);
2382             }
2383             throw new IllegalArgumentException(
2384                 "Cannot change mode after SSL traffic has started");
2385         }
2386     }
2387 
2388     @Override
2389     public synchronized boolean getUseClientMode() {
2390         return !roleIsServer;
2391     }
2392 
2393 
2394     /**
2395      * Returns the names of the cipher suites which could be enabled for use
2396      * on an SSL connection.  Normally, only a subset of these will actually
2397      * be enabled by default, since this list may include cipher suites which
2398      * do not support the mutual authentication of servers and clients, or
2399      * which do not protect data confidentiality.  Servers may also need
2400      * certain kinds of certificates to use certain cipher suites.
2401      *
2402      * @return an array of cipher suite names
2403      */
2404     @Override
2405     public String[] getSupportedCipherSuites() {
2406         return sslContext.getSupportedCipherSuiteList().toStringArray();
2407     }
2408 
2409     /**
2410      * Controls which particular cipher suites are enabled for use on
2411      * this connection.  The cipher suites must have been listed by
2412      * getCipherSuites() as being supported.  Even if a suite has been
2413      * enabled, it might never be used if no peer supports it or the
2414      * requisite certificates (and private keys) are not available.
2415      *
2416      * @param suites Names of all the cipher suites to enable.
2417      */
2418     @Override
2419     public synchronized void setEnabledCipherSuites(String[] suites) {
2420         enabledCipherSuites = new CipherSuiteList(suites);
2421         if ((handshaker != null) && !handshaker.activated()) {
2422             handshaker.setEnabledCipherSuites(enabledCipherSuites);
2423         }
2424     }
2425 
2426     /**
2427      * Returns the names of the SSL cipher suites which are currently enabled
2428      * for use on this connection.  When an SSL socket is first created,
2429      * all enabled cipher suites <em>(a)</em> protect data confidentiality,
2430      * by traffic encryption, and <em>(b)</em> can mutually authenticate
2431      * both clients and servers.  Thus, in some environments, this value
2432      * might be empty.
2433      *
2434      * @return an array of cipher suite names
2435      */
2436     @Override
2437     public synchronized String[] getEnabledCipherSuites() {
2438         return enabledCipherSuites.toStringArray();
2439     }
2440 
2441 
2442     /**
2443      * Returns the protocols that are supported by this implementation.
2444      * A subset of the supported protocols may be enabled for this connection
2445      * @return an array of protocol names.
2446      */
2447     @Override
2448     public String[] getSupportedProtocols() {
2449         return sslContext.getSuportedProtocolList().toStringArray();
2450     }
2451 
2452     /**
2453      * Controls which protocols are enabled for use on
2454      * this connection.  The protocols must have been listed by
2455      * getSupportedProtocols() as being supported.
2456      *
2457      * @param protocols protocols to enable.
2458      * @exception IllegalArgumentException when one of the protocols
2459      *  named by the parameter is not supported.
2460      */
2461     @Override
2462     public synchronized void setEnabledProtocols(String[] protocols) {
2463         enabledProtocols = new ProtocolList(protocols);
2464         if ((handshaker != null) && !handshaker.activated()) {
2465             handshaker.setEnabledProtocols(enabledProtocols);
2466         }
2467     }
2468 
2469     @Override
2470     public synchronized String[] getEnabledProtocols() {
2471         return enabledProtocols.toStringArray();
2472     }
2473 
2474     /**
2475      * Assigns the socket timeout.
2476      * @see java.net.Socket#setSoTimeout
2477      */
2478     @Override
2479     public void setSoTimeout(int timeout) throws SocketException {
2480         if ((debug != null) && Debug.isOn("ssl")) {
2481             System.out.println(Thread.currentThread().getName() +
2482                 ", setSoTimeout(" + timeout + ") called");
2483         }
2484 
2485         super.setSoTimeout(timeout);
2486     }
2487 
2488     /**
2489      * Registers an event listener to receive notifications that an
2490      * SSL handshake has completed on this connection.
2491      */
2492     @Override
2493     public synchronized void addHandshakeCompletedListener(
2494             HandshakeCompletedListener listener) {
2495         if (listener == null) {
2496             throw new IllegalArgumentException("listener is null");
2497         }
2498         if (handshakeListeners == null) {
2499             handshakeListeners = new
2500                 HashMap<HandshakeCompletedListener, AccessControlContext>(4);
2501         }
2502         handshakeListeners.put(listener, AccessController.getContext());
2503     }
2504 
2505 
2506     /**
2507      * Removes a previously registered handshake completion listener.
2508      */
2509     @Override
2510     public synchronized void removeHandshakeCompletedListener(
2511             HandshakeCompletedListener listener) {
2512         if (handshakeListeners == null) {
2513             throw new IllegalArgumentException("no listeners");
2514         }
2515         if (handshakeListeners.remove(listener) == null) {
2516             throw new IllegalArgumentException("listener not registered");
2517         }
2518         if (handshakeListeners.isEmpty()) {
2519             handshakeListeners = null;
2520         }
2521     }
2522 
2523     /**
2524      * Returns the SSLParameters in effect for this SSLSocket.
2525      */
2526     @Override
2527     public synchronized SSLParameters getSSLParameters() {
2528         SSLParameters params = super.getSSLParameters();
2529 
2530         // the super implementation does not handle the following parameters
2531         params.setEndpointIdentificationAlgorithm(identificationProtocol);
2532         params.setAlgorithmConstraints(algorithmConstraints);
2533         params.setSNIMatchers(sniMatchers);
2534         params.setServerNames(serverNames);
2535         params.setUseCipherSuitesOrder(preferLocalCipherSuites);
2536         params.setMaximumPacketSize(maximumPacketSize);
2537         params.setApplicationProtocols(applicationProtocols);
2538 
2539         // DTLS handshake retransmissions parameter does not apply here.
2540 
2541         return params;
2542     }
2543 
2544     /**
2545      * Applies SSLParameters to this socket.
2546      */
2547     @Override
2548     public synchronized void setSSLParameters(SSLParameters params) {
2549         super.setSSLParameters(params);
2550 
2551         // the super implementation does not handle the following parameters
2552         identificationProtocol = params.getEndpointIdentificationAlgorithm();
2553         algorithmConstraints = params.getAlgorithmConstraints();
2554         preferLocalCipherSuites = params.getUseCipherSuitesOrder();
2555         maximumPacketSize = params.getMaximumPacketSize();
2556 
2557         // DTLS handshake retransmissions parameter does not apply here.
2558 
2559         if (maximumPacketSize != 0) {
2560             outputRecord.changePacketSize(maximumPacketSize);
2561         } else {
2562             // use the implicit maximum packet size.
2563             maximumPacketSize = outputRecord.getMaxPacketSize();
2564         }
2565 
2566         List<SNIServerName> sniNames = params.getServerNames();
2567         if (sniNames != null) {
2568             serverNames = sniNames;
2569         }
2570 
2571         Collection<SNIMatcher> matchers = params.getSNIMatchers();
2572         if (matchers != null) {
2573             sniMatchers = matchers;
2574         }
2575 
2576         applicationProtocols = params.getApplicationProtocols();
2577 
2578         if ((handshaker != null) && !handshaker.started()) {
2579             handshaker.setIdentificationProtocol(identificationProtocol);
2580             handshaker.setAlgorithmConstraints(algorithmConstraints);
2581             handshaker.setMaximumPacketSize(maximumPacketSize);
2582             handshaker.setApplicationProtocols(applicationProtocols);
2583             if (roleIsServer) {
2584                 handshaker.setSNIMatchers(sniMatchers);
2585                 handshaker.setUseCipherSuitesOrder(preferLocalCipherSuites);
2586             } else {
2587                 handshaker.setSNIServerNames(serverNames);
2588             }
2589         }
2590     }
2591 
2592     @Override
2593     public synchronized String getApplicationProtocol() {
2594         return applicationProtocol;
2595     }
2596 
2597     @Override
2598     public synchronized String getHandshakeApplicationProtocol() {
2599         if ((handshaker != null) && !handshaker.started()) {
2600             return handshaker.getHandshakeApplicationProtocol();
2601         }
2602         return null;
2603     }
2604 
2605     //
2606     // We allocate a separate thread to deliver handshake completion
2607     // events.  This ensures that the notifications don't block the
2608     // protocol state machine.
2609     //
2610     private static class NotifyHandshake implements Runnable {
2611 
2612         private Set<Map.Entry<HandshakeCompletedListener,AccessControlContext>>
2613                 targets;        // who gets notified
2614         private HandshakeCompletedEvent event;          // the notification
2615 
2616         NotifyHandshake(
2617             Set<Map.Entry<HandshakeCompletedListener,AccessControlContext>>
2618             entrySet, HandshakeCompletedEvent e) {
2619 
2620             targets = new HashSet<>(entrySet);          // clone the entry set
2621             event = e;
2622         }
2623 
2624         @Override
2625         public void run() {
2626             // Don't need to synchronize, as it only runs in one thread.
2627             for (Map.Entry<HandshakeCompletedListener,AccessControlContext>
2628                 entry : targets) {
2629 
2630                 final HandshakeCompletedListener l = entry.getKey();
2631                 AccessControlContext acc = entry.getValue();
2632                 AccessController.doPrivileged(new PrivilegedAction<Void>() {
2633                     @Override
2634                     public Void run() {
2635                         l.handshakeCompleted(event);
2636                         return null;
2637                     }
2638                 }, acc);
2639             }
2640         }
2641     }
2642 
2643     /**
2644      * Returns a printable representation of this end of the connection.
2645      */
2646     @Override
2647     public String toString() {
2648         StringBuilder retval = new StringBuilder(80);
2649 
2650         retval.append(Integer.toHexString(hashCode()));
2651         retval.append("[");
2652         retval.append(sess.getCipherSuite());
2653         retval.append(": ");
2654 
2655         retval.append(super.toString());
2656         retval.append("]");
2657 
2658         return retval.toString();
2659     }
2660 }