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