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