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