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