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     @Override
1483     boolean isLayered() {
1484         return super.isLayered();
1485     }
1486 
1487     /**
1488      * Return whether we have reached end-of-file.
1489      *
1490      * If the socket is not connected, has been shutdown because of an error
1491      * or has been closed, throw an Exception.
1492      */
1493     boolean checkEOF() throws IOException {
1494         switch (getConnectionState()) {
1495         case cs_START:
1496             throw new SocketException("Socket is not connected");
1497 
1498         case cs_HANDSHAKE:
1499         case cs_DATA:
1500         case cs_RENEGOTIATE:
1501         case cs_SENT_CLOSE:
1502             return false;
1503 
1504         case cs_APP_CLOSED:
1505             throw new SocketException("Socket is closed");
1506 
1507         case cs_ERROR:
1508         case cs_CLOSED:
1509         default:
1510             // either closed because of error, or normal EOF
1511             if (closeReason == null) {
1512                 return true;
1513             }
1514             IOException e = new SSLException
1515                         ("Connection has been shutdown: " + closeReason);
1516             e.initCause(closeReason);
1517             throw e;
1518 
1519         }
1520     }
1521 
1522     /**
1523      * Check if we can write data to this socket. If not, throw an IOException.
1524      */
1525     void checkWrite() throws IOException {
1526         if (checkEOF() || (getConnectionState() == cs_SENT_CLOSE)) {
1527             // we are at EOF, write must throw Exception
1528             throw new SocketException("Connection closed by remote host");
1529         }
1530     }
1531 
1532     protected void closeSocket() throws IOException {
1533 
1534         if ((debug != null) && Debug.isOn("ssl")) {
1535             System.out.println(Thread.currentThread().getName() +
1536                                                 ", called closeSocket()");
1537         }
1538 
1539         super.close();
1540     }
1541 
1542     private void closeSocket(boolean selfInitiated) throws IOException {
1543         if ((debug != null) && Debug.isOn("ssl")) {
1544             System.out.println(Thread.currentThread().getName() +
1545                 ", called closeSocket(" + selfInitiated + ")");
1546         }
1547         if (!isLayered() || autoClose) {
1548             super.close();
1549         } else if (selfInitiated) {
1550             // layered && non-autoclose
1551             // read close_notify alert to clear input stream
1552             waitForClose(false);
1553         }
1554     }
1555 
1556     /*
1557      * Closing the connection is tricky ... we can't officially close the
1558      * connection until we know the other end is ready to go away too,
1559      * and if ever the connection gets aborted we must forget session
1560      * state (it becomes invalid).
1561      */
1562 
1563     /**
1564      * Closes the SSL connection.  SSL includes an application level
1565      * shutdown handshake; you should close SSL sockets explicitly
1566      * rather than leaving it for finalization, so that your remote
1567      * peer does not experience a protocol error.
1568      */
1569     @Override
1570     public void close() throws IOException {
1571         if ((debug != null) && Debug.isOn("ssl")) {
1572             System.out.println(Thread.currentThread().getName() +
1573                                                     ", called close()");
1574         }
1575         closeInternal(true);  // caller is initiating close
1576         setConnectionState(cs_APP_CLOSED);
1577     }
1578 
1579     /**
1580      * Don't synchronize the whole method because waitForClose()
1581      * (which calls readRecord()) might be called.
1582      *
1583      * @param selfInitiated Indicates which party initiated the close.
1584      * If selfInitiated, this side is initiating a close; for layered and
1585      * non-autoclose socket, wait for close_notify response.
1586      * If !selfInitiated, peer sent close_notify; we reciprocate but
1587      * no need to wait for response.
1588      */
1589     private void closeInternal(boolean selfInitiated) throws IOException {
1590         if ((debug != null) && Debug.isOn("ssl")) {
1591             System.out.println(Thread.currentThread().getName() +
1592                         ", called closeInternal(" + selfInitiated + ")");
1593         }
1594 
1595         int state = getConnectionState();
1596         boolean closeSocketCalled = false;
1597         Throwable cachedThrowable = null;
1598         try {
1599             switch (state) {
1600             case cs_START:
1601                 // unconnected socket or handshaking has not been initialized
1602                 closeSocket(selfInitiated);
1603                 break;
1604 
1605             /*
1606              * If we're closing down due to error, we already sent (or else
1607              * received) the fatal alert ... no niceties, blow the connection
1608              * away as quickly as possible (even if we didn't allocate the
1609              * socket ourselves; it's unusable, regardless).
1610              */
1611             case cs_ERROR:
1612                 closeSocket();
1613                 break;
1614 
1615             /*
1616              * Sometimes close() gets called more than once.
1617              */
1618             case cs_CLOSED:
1619             case cs_APP_CLOSED:
1620                  break;
1621 
1622             /*
1623              * Otherwise we indicate clean termination.
1624              */
1625             // case cs_HANDSHAKE:
1626             // case cs_DATA:
1627             // case cs_RENEGOTIATE:
1628             // case cs_SENT_CLOSE:
1629             default:
1630                 synchronized (this) {
1631                     if (((state = getConnectionState()) == cs_CLOSED) ||
1632                        (state == cs_ERROR) || (state == cs_APP_CLOSED)) {
1633                         return;  // connection was closed while we waited
1634                     }
1635                     if (state != cs_SENT_CLOSE) {
1636                         try {
1637                             warning(Alerts.alert_close_notify);
1638                             connectionState = cs_SENT_CLOSE;
1639                         } catch (Throwable th) {
1640                             // we need to ensure socket is closed out
1641                             // if we encounter any errors.
1642                             connectionState = cs_ERROR;
1643                             // cache this for later use
1644                             cachedThrowable = th;
1645                             closeSocketCalled = true;
1646                             closeSocket(selfInitiated);
1647                         }
1648                     }
1649                 }
1650                 // If state was cs_SENT_CLOSE before, we don't do the actual
1651                 // closing since it is already in progress.
1652                 if (state == cs_SENT_CLOSE) {
1653                     if (debug != null && Debug.isOn("ssl")) {
1654                         System.out.println(Thread.currentThread().getName() +
1655                             ", close invoked again; state = " +
1656                             getConnectionState());
1657                     }
1658                     if (selfInitiated == false) {
1659                         // We were called because a close_notify message was
1660                         // received. This may be due to another thread calling
1661                         // read() or due to our call to waitForClose() below.
1662                         // In either case, just return.
1663                         return;
1664                     }
1665                     // Another thread explicitly called close(). We need to
1666                     // wait for the closing to complete before returning.
1667                     synchronized (this) {
1668                         while (connectionState < cs_CLOSED) {
1669                             try {
1670                                 this.wait();
1671                             } catch (InterruptedException e) {
1672                                 // ignore
1673                             }
1674                         }
1675                     }
1676                     if ((debug != null) && Debug.isOn("ssl")) {
1677                         System.out.println(Thread.currentThread().getName() +
1678                             ", after primary close; state = " +
1679                             getConnectionState());
1680                     }
1681                     return;
1682                 }
1683 
1684                 if (!closeSocketCalled)  {
1685                     closeSocketCalled = true;
1686                     closeSocket(selfInitiated);
1687                 }
1688 
1689                 break;
1690             }
1691         } finally {
1692             synchronized (this) {
1693                 // Upon exit from this method, the state is always >= cs_CLOSED
1694                 connectionState = (connectionState == cs_APP_CLOSED)
1695                                 ? cs_APP_CLOSED : cs_CLOSED;
1696                 // notify any threads waiting for the closing to finish
1697                 this.notifyAll();
1698             }
1699             if (closeSocketCalled) {
1700                 // Dispose of ciphers since we've closed socket
1701                 disposeCiphers();
1702             }
1703             if (cachedThrowable != null) {
1704                /*
1705                 * Rethrow the error to the calling method
1706                 * The Throwable caught can only be an Error or RuntimeException
1707                 */
1708                 if (cachedThrowable instanceof Error)
1709                     throw (Error) cachedThrowable;
1710                 if (cachedThrowable instanceof RuntimeException)
1711                     throw (RuntimeException) cachedThrowable;
1712             }
1713         }
1714     }
1715 
1716     /**
1717      * Reads a close_notify or a fatal alert from the input stream.
1718      * Keep reading records until we get a close_notify or until
1719      * the connection is otherwise closed.  The close_notify or alert
1720      * might be read by another reader,
1721      * which will then process the close and set the connection state.
1722      */
1723     void waitForClose(boolean rethrow) throws IOException {
1724         if (debug != null && Debug.isOn("ssl")) {
1725             System.out.println(Thread.currentThread().getName() +
1726                 ", waiting for close_notify or alert: state "
1727                 + getConnectionState());
1728         }
1729 
1730         try {
1731             int state;
1732 
1733             while (((state = getConnectionState()) != cs_CLOSED) &&
1734                    (state != cs_ERROR) && (state != cs_APP_CLOSED)) {
1735                 // create the InputRecord if it isn't initialized.
1736                 if (inrec == null) {
1737                     inrec = new InputRecord();
1738                 }
1739 
1740                 // Ask for app data and then throw it away
1741                 try {
1742                     readRecord(inrec, true);
1743                 } catch (SocketTimeoutException e) {
1744                     // if time out, ignore the exception and continue
1745                 }
1746             }
1747             inrec = null;
1748         } catch (IOException e) {
1749             if (debug != null && Debug.isOn("ssl")) {
1750                 System.out.println(Thread.currentThread().getName() +
1751                     ", Exception while waiting for close " +e);
1752             }
1753             if (rethrow) {
1754                 throw e; // pass exception up
1755             }
1756         }
1757     }
1758 
1759     /**
1760      * Called by closeInternal() only. Be sure to consider the
1761      * synchronization locks carefully before calling it elsewhere.
1762      */
1763     private void disposeCiphers() {
1764         // See comment in changeReadCiphers()
1765         synchronized (readLock) {
1766             readCipher.dispose();
1767         }
1768         // See comment in changeReadCiphers()
1769         writeLock.lock();
1770         try {
1771             writeCipher.dispose();
1772         } finally {
1773             writeLock.unlock();
1774         }
1775     }
1776 
1777     //
1778     // EXCEPTION AND ALERT HANDLING
1779     //
1780 
1781     /**
1782      * Handle an exception. This method is called by top level exception
1783      * handlers (in read(), write()) to make sure we always shutdown the
1784      * connection correctly and do not pass runtime exception to the
1785      * application.
1786      */
1787     void handleException(Exception e) throws IOException {
1788         handleException(e, true);
1789     }
1790 
1791     /**
1792      * Handle an exception. This method is called by top level exception
1793      * handlers (in read(), write(), startHandshake()) to make sure we
1794      * always shutdown the connection correctly and do not pass runtime
1795      * exception to the application.
1796      *
1797      * This method never returns normally, it always throws an IOException.
1798      *
1799      * We first check if the socket has already been shutdown because of an
1800      * error. If so, we just rethrow the exception. If the socket has not
1801      * been shutdown, we sent a fatal alert and remember the exception.
1802      *
1803      * @param e the Exception
1804      * @param resumable indicates the caller process is resumable from the
1805      *          exception. If <code>resumable</code>, the socket will be
1806      *          reserved for exceptions like timeout; otherwise, the socket
1807      *          will be closed, no further communications could be done.
1808      */
1809     synchronized private void handleException(Exception e, boolean resumable)
1810         throws IOException {
1811         if ((debug != null) && Debug.isOn("ssl")) {
1812             System.out.println(Thread.currentThread().getName() +
1813                         ", handling exception: " + e.toString());
1814         }
1815 
1816         // don't close the Socket in case of timeouts or interrupts if
1817         // the process is resumable.
1818         if (e instanceof InterruptedIOException && resumable) {
1819             throw (IOException)e;
1820         }
1821 
1822         // if we've already shutdown because of an error,
1823         // there is nothing to do except rethrow the exception
1824         if (closeReason != null) {
1825             if (e instanceof IOException) { // includes SSLException
1826                 throw (IOException)e;
1827             } else {
1828                 // this is odd, not an IOException.
1829                 // normally, this should not happen
1830                 // if closeReason has been already been set
1831                 throw Alerts.getSSLException(Alerts.alert_internal_error, e,
1832                                       "Unexpected exception");
1833             }
1834         }
1835 
1836         // need to perform error shutdown
1837         boolean isSSLException = (e instanceof SSLException);
1838         if ((isSSLException == false) && (e instanceof IOException)) {
1839             // IOException from the socket
1840             // this means the TCP connection is already dead
1841             // we call fatal just to set the error status
1842             try {
1843                 fatal(Alerts.alert_unexpected_message, e);
1844             } catch (IOException ee) {
1845                 // ignore (IOException wrapped in SSLException)
1846             }
1847             // rethrow original IOException
1848             throw (IOException)e;
1849         }
1850 
1851         // must be SSLException or RuntimeException
1852         byte alertType;
1853         if (isSSLException) {
1854             if (e instanceof SSLHandshakeException) {
1855                 alertType = Alerts.alert_handshake_failure;
1856             } else {
1857                 alertType = Alerts.alert_unexpected_message;
1858             }
1859         } else {
1860             alertType = Alerts.alert_internal_error;
1861         }
1862         fatal(alertType, e);
1863     }
1864 
1865     /*
1866      * Send a warning alert.
1867      */
1868     void warning(byte description) {
1869         sendAlert(Alerts.alert_warning, description);
1870     }
1871 
1872     synchronized void fatal(byte description, String diagnostic)
1873             throws IOException {
1874         fatal(description, diagnostic, null);
1875     }
1876 
1877     synchronized void fatal(byte description, Throwable cause)
1878             throws IOException {
1879         fatal(description, null, cause);
1880     }
1881 
1882     /*
1883      * Send a fatal alert, and throw an exception so that callers will
1884      * need to stand on their heads to accidentally continue processing.
1885      */
1886     synchronized void fatal(byte description, String diagnostic,
1887             Throwable cause) throws IOException {
1888         if ((input != null) && (input.r != null)) {
1889             input.r.close();
1890         }
1891         sess.invalidate();
1892         if (handshakeSession != null) {
1893             handshakeSession.invalidate();
1894         }
1895 
1896         int oldState = connectionState;
1897         if (connectionState < cs_ERROR) {
1898             connectionState = cs_ERROR;
1899         }
1900 
1901         /*
1902          * Has there been an error received yet?  If not, remember it.
1903          * By RFC 2246, we don't bother waiting for a response.
1904          * Fatal errors require immediate shutdown.
1905          */
1906         if (closeReason == null) {
1907             /*
1908              * Try to clear the kernel buffer to avoid TCP connection resets.
1909              */
1910             if (oldState == cs_HANDSHAKE) {
1911                 sockInput.skip(sockInput.available());
1912             }
1913 
1914             // If the description equals -1, the alert won't be sent to peer.
1915             if (description != -1) {
1916                 sendAlert(Alerts.alert_fatal, description);
1917             }
1918             if (cause instanceof SSLException) { // only true if != null
1919                 closeReason = (SSLException)cause;
1920             } else {
1921                 closeReason =
1922                     Alerts.getSSLException(description, cause, diagnostic);
1923             }
1924         }
1925 
1926         /*
1927          * Clean up our side.
1928          */
1929         closeSocket();
1930         // Another thread may have disposed the ciphers during closing
1931         if (connectionState < cs_CLOSED) {
1932             connectionState = (oldState == cs_APP_CLOSED) ? cs_APP_CLOSED
1933                                                               : cs_CLOSED;
1934 
1935             // We should lock readLock and writeLock if no deadlock risks.
1936             // See comment in changeReadCiphers()
1937             readCipher.dispose();
1938             writeCipher.dispose();
1939         }
1940 
1941         throw closeReason;
1942     }
1943 
1944 
1945     /*
1946      * Process an incoming alert ... caller must already have synchronized
1947      * access to "this".
1948      */
1949     private void recvAlert(InputRecord r) throws IOException {
1950         byte level = (byte)r.read();
1951         byte description = (byte)r.read();
1952         if (description == -1) { // check for short message
1953             fatal(Alerts.alert_illegal_parameter, "Short alert message");
1954         }
1955 
1956         if (debug != null && (Debug.isOn("record") ||
1957                 Debug.isOn("handshake"))) {
1958             synchronized (System.out) {
1959                 System.out.print(Thread.currentThread().getName());
1960                 System.out.print(", RECV " + protocolVersion + " ALERT:  ");
1961                 if (level == Alerts.alert_fatal) {
1962                     System.out.print("fatal, ");
1963                 } else if (level == Alerts.alert_warning) {
1964                     System.out.print("warning, ");
1965                 } else {
1966                     System.out.print("<level " + (0x0ff & level) + ">, ");
1967                 }
1968                 System.out.println(Alerts.alertDescription(description));
1969             }
1970         }
1971 
1972         if (level == Alerts.alert_warning) {
1973             if (description == Alerts.alert_close_notify) {
1974                 if (connectionState == cs_HANDSHAKE) {
1975                     fatal(Alerts.alert_unexpected_message,
1976                                 "Received close_notify during handshake");
1977                 } else {
1978                     closeInternal(false);  // reply to close
1979                 }
1980             } else {
1981 
1982                 //
1983                 // The other legal warnings relate to certificates,
1984                 // e.g. no_certificate, bad_certificate, etc; these
1985                 // are important to the handshaking code, which can
1986                 // also handle illegal protocol alerts if needed.
1987                 //
1988                 if (handshaker != null) {
1989                     handshaker.handshakeAlert(description);
1990                 }
1991             }
1992         } else { // fatal or unknown level
1993             String reason = "Received fatal alert: "
1994                 + Alerts.alertDescription(description);
1995             if (closeReason == null) {
1996                 closeReason = Alerts.getSSLException(description, reason);
1997             }
1998             fatal(Alerts.alert_unexpected_message, reason);
1999         }
2000     }
2001 
2002 
2003     /*
2004      * Emit alerts.  Caller must have synchronized with "this".
2005      */
2006     private void sendAlert(byte level, byte description) {
2007         // the connectionState cannot be cs_START
2008         if (connectionState >= cs_SENT_CLOSE) {
2009             return;
2010         }
2011 
2012         // For initial handshaking, don't send alert message to peer if
2013         // handshaker has not started.
2014         if (connectionState == cs_HANDSHAKE &&
2015             (handshaker == null || !handshaker.started())) {
2016             return;
2017         }
2018 
2019         OutputRecord r = new OutputRecord(Record.ct_alert);
2020         r.setVersion(protocolVersion);
2021 
2022         boolean useDebug = debug != null && Debug.isOn("ssl");
2023         if (useDebug) {
2024             synchronized (System.out) {
2025                 System.out.print(Thread.currentThread().getName());
2026                 System.out.print(", SEND " + protocolVersion + " ALERT:  ");
2027                 if (level == Alerts.alert_fatal) {
2028                     System.out.print("fatal, ");
2029                 } else if (level == Alerts.alert_warning) {
2030                     System.out.print("warning, ");
2031                 } else {
2032                     System.out.print("<level = " + (0x0ff & level) + ">, ");
2033                 }
2034                 System.out.println("description = "
2035                         + Alerts.alertDescription(description));
2036             }
2037         }
2038 
2039         r.write(level);
2040         r.write(description);
2041         try {
2042             writeRecord(r);
2043         } catch (IOException e) {
2044             if (useDebug) {
2045                 System.out.println(Thread.currentThread().getName() +
2046                     ", Exception sending alert: " + e);
2047             }
2048         }
2049     }
2050 
2051     //
2052     // VARIOUS OTHER METHODS
2053     //
2054 
2055     /*
2056      * When a connection finishes handshaking by enabling use of a newly
2057      * negotiated session, each end learns about it in two halves (read,
2058      * and write).  When both read and write ciphers have changed, and the
2059      * last handshake message has been read, the connection has joined
2060      * (rejoined) the new session.
2061      *
2062      * NOTE:  The SSLv3 spec is rather unclear on the concepts here.
2063      * Sessions don't change once they're established (including cipher
2064      * suite and master secret) but connections can join them (and leave
2065      * them).  They're created by handshaking, though sometime handshaking
2066      * causes connections to join up with pre-established sessions.
2067      */
2068     private void changeReadCiphers() throws SSLException {
2069         if (connectionState != cs_HANDSHAKE
2070                 && connectionState != cs_RENEGOTIATE) {
2071             throw new SSLProtocolException(
2072                 "State error, change cipher specs");
2073         }
2074 
2075         // ... create decompressor
2076 
2077         CipherBox oldCipher = readCipher;
2078 
2079         try {
2080             readCipher = handshaker.newReadCipher();
2081             readAuthenticator = handshaker.newReadAuthenticator();
2082         } catch (GeneralSecurityException e) {
2083             // "can't happen"
2084             throw new SSLException("Algorithm missing:  ", e);
2085         }
2086 
2087         /*
2088          * Dispose of any intermediate state in the underlying cipher.
2089          * For PKCS11 ciphers, this will release any attached sessions,
2090          * and thus make finalization faster.
2091          *
2092          * Since MAC's doFinal() is called for every SSL/TLS packet, it's
2093          * not necessary to do the same with MAC's.
2094          */
2095         oldCipher.dispose();
2096     }
2097 
2098     // used by Handshaker
2099     void changeWriteCiphers() throws SSLException {
2100         if (connectionState != cs_HANDSHAKE
2101                 && connectionState != cs_RENEGOTIATE) {
2102             throw new SSLProtocolException(
2103                 "State error, change cipher specs");
2104         }
2105 
2106         // ... create compressor
2107 
2108         CipherBox oldCipher = writeCipher;
2109 
2110         try {
2111             writeCipher = handshaker.newWriteCipher();
2112             writeAuthenticator = handshaker.newWriteAuthenticator();
2113         } catch (GeneralSecurityException e) {
2114             // "can't happen"
2115             throw new SSLException("Algorithm missing:  ", e);
2116         }
2117 
2118         // See comment above.
2119         oldCipher.dispose();
2120 
2121         // reset the flag of the first application record
2122         isFirstAppOutputRecord = true;
2123     }
2124 
2125     /*
2126      * Updates the SSL version associated with this connection.
2127      * Called from Handshaker once it has determined the negotiated version.
2128      */
2129     synchronized void setVersion(ProtocolVersion protocolVersion) {
2130         this.protocolVersion = protocolVersion;
2131         output.r.setVersion(protocolVersion);
2132     }
2133 
2134     synchronized String getHost() {
2135         // Note that the host may be null or empty for localhost.
2136         if (host == null || host.length() == 0) {
2137             host = getInetAddress().getHostName();
2138         }
2139         return host;
2140     }
2141 
2142     // ONLY used by HttpsClient to setup the URI specified hostname
2143     //
2144     // Please NOTE that this method MUST be called before calling to
2145     // SSLSocket.setSSLParameters(). Otherwise, the {@code host} parameter
2146     // may override SNIHostName in the customized server name indication.
2147     synchronized public void setHost(String host) {
2148         this.host = host;
2149         this.serverNames =
2150             Utilities.addToSNIServerNameList(this.serverNames, this.host);
2151     }
2152 
2153     /**
2154      * Gets an input stream to read from the peer on the other side.
2155      * Data read from this stream was always integrity protected in
2156      * transit, and will usually have been confidentiality protected.
2157      */
2158     @Override
2159     synchronized public InputStream getInputStream() throws IOException {
2160         if (isClosed()) {
2161             throw new SocketException("Socket is closed");
2162         }
2163 
2164         /*
2165          * Can't call isConnected() here, because the Handshakers
2166          * do some initialization before we actually connect.
2167          */
2168         if (connectionState == cs_START) {
2169             throw new SocketException("Socket is not connected");
2170         }
2171 
2172         return input;
2173     }
2174 
2175     /**
2176      * Gets an output stream to write to the peer on the other side.
2177      * Data written on this stream is always integrity protected, and
2178      * will usually be confidentiality protected.
2179      */
2180     @Override
2181     synchronized public OutputStream getOutputStream() throws IOException {
2182         if (isClosed()) {
2183             throw new SocketException("Socket is closed");
2184         }
2185 
2186         /*
2187          * Can't call isConnected() here, because the Handshakers
2188          * do some initialization before we actually connect.
2189          */
2190         if (connectionState == cs_START) {
2191             throw new SocketException("Socket is not connected");
2192         }
2193 
2194         return output;
2195     }
2196 
2197     /**
2198      * Returns the the SSL Session in use by this connection.  These can
2199      * be long lived, and frequently correspond to an entire login session
2200      * for some user.
2201      */
2202     @Override
2203     public SSLSession getSession() {
2204         /*
2205          * Force a synchronous handshake, if appropriate.
2206          */
2207         if (getConnectionState() == cs_HANDSHAKE) {
2208             try {
2209                 // start handshaking, if failed, the connection will be closed.
2210                 startHandshake(false);
2211             } catch (IOException e) {
2212                 // handshake failed. log and return a nullSession
2213                 if (debug != null && Debug.isOn("handshake")) {
2214                       System.out.println(Thread.currentThread().getName() +
2215                           ", IOException in getSession():  " + e);
2216                 }
2217             }
2218         }
2219         synchronized (this) {
2220             return sess;
2221         }
2222     }
2223 
2224     @Override
2225     synchronized public SSLSession getHandshakeSession() {
2226         return handshakeSession;
2227     }
2228 
2229     synchronized void setHandshakeSession(SSLSessionImpl session) {
2230         handshakeSession = session;
2231     }
2232 
2233     /**
2234      * Controls whether new connections may cause creation of new SSL
2235      * sessions.
2236      *
2237      * As long as handshaking has not started, we can change
2238      * whether we enable session creations.  Otherwise,
2239      * we will need to wait for the next handshake.
2240      */
2241     @Override
2242     synchronized public void setEnableSessionCreation(boolean flag) {
2243         enableSessionCreation = flag;
2244 
2245         if ((handshaker != null) && !handshaker.activated()) {
2246             handshaker.setEnableSessionCreation(enableSessionCreation);
2247         }
2248     }
2249 
2250     /**
2251      * Returns true if new connections may cause creation of new SSL
2252      * sessions.
2253      */
2254     @Override
2255     synchronized public boolean getEnableSessionCreation() {
2256         return enableSessionCreation;
2257     }
2258 
2259 
2260     /**
2261      * Sets the flag controlling whether a server mode socket
2262      * *REQUIRES* SSL client authentication.
2263      *
2264      * As long as handshaking has not started, we can change
2265      * whether client authentication is needed.  Otherwise,
2266      * we will need to wait for the next handshake.
2267      */
2268     @Override
2269     synchronized public void setNeedClientAuth(boolean flag) {
2270         doClientAuth = (flag ?
2271             SSLEngineImpl.clauth_required : SSLEngineImpl.clauth_none);
2272 
2273         if ((handshaker != null) &&
2274                 (handshaker instanceof ServerHandshaker) &&
2275                 !handshaker.activated()) {
2276             ((ServerHandshaker) handshaker).setClientAuth(doClientAuth);
2277         }
2278     }
2279 
2280     @Override
2281     synchronized public boolean getNeedClientAuth() {
2282         return (doClientAuth == SSLEngineImpl.clauth_required);
2283     }
2284 
2285     /**
2286      * Sets the flag controlling whether a server mode socket
2287      * *REQUESTS* SSL client authentication.
2288      *
2289      * As long as handshaking has not started, we can change
2290      * whether client authentication is requested.  Otherwise,
2291      * we will need to wait for the next handshake.
2292      */
2293     @Override
2294     synchronized public void setWantClientAuth(boolean flag) {
2295         doClientAuth = (flag ?
2296             SSLEngineImpl.clauth_requested : SSLEngineImpl.clauth_none);
2297 
2298         if ((handshaker != null) &&
2299                 (handshaker instanceof ServerHandshaker) &&
2300                 !handshaker.activated()) {
2301             ((ServerHandshaker) handshaker).setClientAuth(doClientAuth);
2302         }
2303     }
2304 
2305     @Override
2306     synchronized public boolean getWantClientAuth() {
2307         return (doClientAuth == SSLEngineImpl.clauth_requested);
2308     }
2309 
2310 
2311     /**
2312      * Sets the flag controlling whether the socket is in SSL
2313      * client or server mode.  Must be called before any SSL
2314      * traffic has started.
2315      */
2316     @Override
2317     @SuppressWarnings("fallthrough")
2318     synchronized public void setUseClientMode(boolean flag) {
2319         switch (connectionState) {
2320 
2321         case cs_START:
2322             /*
2323              * If we need to change the socket mode and the enabled
2324              * protocols haven't specifically been set by the user,
2325              * change them to the corresponding default ones.
2326              */
2327             if (roleIsServer != (!flag) &&
2328                     sslContext.isDefaultProtocolList(enabledProtocols)) {
2329                 enabledProtocols = sslContext.getDefaultProtocolList(!flag);
2330             }
2331             roleIsServer = !flag;
2332             break;
2333 
2334         case cs_HANDSHAKE:
2335             /*
2336              * If we have a handshaker, but haven't started
2337              * SSL traffic, we can throw away our current
2338              * handshaker, and start from scratch.  Don't
2339              * need to call doneConnect() again, we already
2340              * have the streams.
2341              */
2342             assert(handshaker != null);
2343             if (!handshaker.activated()) {
2344                 /*
2345                  * If we need to change the socket mode and the enabled
2346                  * protocols haven't specifically been set by the user,
2347                  * change them to the corresponding default ones.
2348                  */
2349                 if (roleIsServer != (!flag) &&
2350                         sslContext.isDefaultProtocolList(enabledProtocols)) {
2351                     enabledProtocols = sslContext.getDefaultProtocolList(!flag);
2352                 }
2353                 roleIsServer = !flag;
2354                 connectionState = cs_START;
2355                 initHandshaker();
2356                 break;
2357             }
2358 
2359             // If handshake has started, that's an error.  Fall through...
2360 
2361         default:
2362             if (debug != null && Debug.isOn("ssl")) {
2363                 System.out.println(Thread.currentThread().getName() +
2364                     ", setUseClientMode() invoked in state = " +
2365                     connectionState);
2366             }
2367             throw new IllegalArgumentException(
2368                 "Cannot change mode after SSL traffic has started");
2369         }
2370     }
2371 
2372     @Override
2373     synchronized public boolean getUseClientMode() {
2374         return !roleIsServer;
2375     }
2376 
2377 
2378     /**
2379      * Returns the names of the cipher suites which could be enabled for use
2380      * on an SSL connection.  Normally, only a subset of these will actually
2381      * be enabled by default, since this list may include cipher suites which
2382      * do not support the mutual authentication of servers and clients, or
2383      * which do not protect data confidentiality.  Servers may also need
2384      * certain kinds of certificates to use certain cipher suites.
2385      *
2386      * @return an array of cipher suite names
2387      */
2388     @Override
2389     public String[] getSupportedCipherSuites() {
2390         return sslContext.getSupportedCipherSuiteList().toStringArray();
2391     }
2392 
2393     /**
2394      * Controls which particular cipher suites are enabled for use on
2395      * this connection.  The cipher suites must have been listed by
2396      * getCipherSuites() as being supported.  Even if a suite has been
2397      * enabled, it might never be used if no peer supports it or the
2398      * requisite certificates (and private keys) are not available.
2399      *
2400      * @param suites Names of all the cipher suites to enable.
2401      */
2402     @Override
2403     synchronized public void setEnabledCipherSuites(String[] suites) {
2404         enabledCipherSuites = new CipherSuiteList(suites);
2405         if ((handshaker != null) && !handshaker.activated()) {
2406             handshaker.setEnabledCipherSuites(enabledCipherSuites);
2407         }
2408     }
2409 
2410     /**
2411      * Returns the names of the SSL cipher suites which are currently enabled
2412      * for use on this connection.  When an SSL socket is first created,
2413      * all enabled cipher suites <em>(a)</em> protect data confidentiality,
2414      * by traffic encryption, and <em>(b)</em> can mutually authenticate
2415      * both clients and servers.  Thus, in some environments, this value
2416      * might be empty.
2417      *
2418      * @return an array of cipher suite names
2419      */
2420     @Override
2421     synchronized public String[] getEnabledCipherSuites() {
2422         return enabledCipherSuites.toStringArray();
2423     }
2424 
2425 
2426     /**
2427      * Returns the protocols that are supported by this implementation.
2428      * A subset of the supported protocols may be enabled for this connection
2429      * @return an array of protocol names.
2430      */
2431     @Override
2432     public String[] getSupportedProtocols() {
2433         return sslContext.getSuportedProtocolList().toStringArray();
2434     }
2435 
2436     /**
2437      * Controls which protocols are enabled for use on
2438      * this connection.  The protocols must have been listed by
2439      * getSupportedProtocols() as being supported.
2440      *
2441      * @param protocols protocols to enable.
2442      * @exception IllegalArgumentException when one of the protocols
2443      *  named by the parameter is not supported.
2444      */
2445     @Override
2446     synchronized public void setEnabledProtocols(String[] protocols) {
2447         enabledProtocols = new ProtocolList(protocols);
2448         if ((handshaker != null) && !handshaker.activated()) {
2449             handshaker.setEnabledProtocols(enabledProtocols);
2450         }
2451     }
2452 
2453     @Override
2454     synchronized public String[] getEnabledProtocols() {
2455         return enabledProtocols.toStringArray();
2456     }
2457 
2458     /**
2459      * Assigns the socket timeout.
2460      * @see java.net.Socket#setSoTimeout
2461      */
2462     @Override
2463     public void setSoTimeout(int timeout) throws SocketException {
2464         if ((debug != null) && Debug.isOn("ssl")) {
2465             System.out.println(Thread.currentThread().getName() +
2466                 ", setSoTimeout(" + timeout + ") called");
2467         }
2468 
2469         super.setSoTimeout(timeout);
2470     }
2471 
2472     /**
2473      * Registers an event listener to receive notifications that an
2474      * SSL handshake has completed on this connection.
2475      */
2476     @Override
2477     public synchronized void addHandshakeCompletedListener(
2478             HandshakeCompletedListener listener) {
2479         if (listener == null) {
2480             throw new IllegalArgumentException("listener is null");
2481         }
2482         if (handshakeListeners == null) {
2483             handshakeListeners = new
2484                 HashMap<HandshakeCompletedListener, AccessControlContext>(4);
2485         }
2486         handshakeListeners.put(listener, AccessController.getContext());
2487     }
2488 
2489 
2490     /**
2491      * Removes a previously registered handshake completion listener.
2492      */
2493     @Override
2494     public synchronized void removeHandshakeCompletedListener(
2495             HandshakeCompletedListener listener) {
2496         if (handshakeListeners == null) {
2497             throw new IllegalArgumentException("no listeners");
2498         }
2499         if (handshakeListeners.remove(listener) == null) {
2500             throw new IllegalArgumentException("listener not registered");
2501         }
2502         if (handshakeListeners.isEmpty()) {
2503             handshakeListeners = null;
2504         }
2505     }
2506 
2507     /**
2508      * Returns the SSLParameters in effect for this SSLSocket.
2509      */
2510     @Override
2511     synchronized public SSLParameters getSSLParameters() {
2512         SSLParameters params = super.getSSLParameters();
2513 
2514         // the super implementation does not handle the following parameters
2515         params.setEndpointIdentificationAlgorithm(identificationProtocol);
2516         params.setAlgorithmConstraints(algorithmConstraints);
2517         params.setSNIMatchers(sniMatchers);
2518         params.setServerNames(serverNames);
2519         params.setUseCipherSuitesOrder(preferLocalCipherSuites);
2520 
2521         return params;
2522     }
2523 
2524     /**
2525      * Applies SSLParameters to this socket.
2526      */
2527     @Override
2528     synchronized public void setSSLParameters(SSLParameters params) {
2529         super.setSSLParameters(params);
2530 
2531         // the super implementation does not handle the following parameters
2532         identificationProtocol = params.getEndpointIdentificationAlgorithm();
2533         algorithmConstraints = params.getAlgorithmConstraints();
2534         preferLocalCipherSuites = params.getUseCipherSuitesOrder();
2535 
2536         List<SNIServerName> sniNames = params.getServerNames();
2537         if (sniNames != null) {
2538             serverNames = sniNames;
2539         }
2540 
2541         Collection<SNIMatcher> matchers = params.getSNIMatchers();
2542         if (matchers != null) {
2543             sniMatchers = matchers;
2544         }
2545 
2546         if ((handshaker != null) && !handshaker.started()) {
2547             handshaker.setIdentificationProtocol(identificationProtocol);
2548             handshaker.setAlgorithmConstraints(algorithmConstraints);
2549             if (roleIsServer) {
2550                 handshaker.setSNIMatchers(sniMatchers);
2551                 handshaker.setUseCipherSuitesOrder(preferLocalCipherSuites);
2552             } else {
2553                 handshaker.setSNIServerNames(serverNames);
2554             }
2555         }
2556     }
2557 
2558     //
2559     // We allocate a separate thread to deliver handshake completion
2560     // events.  This ensures that the notifications don't block the
2561     // protocol state machine.
2562     //
2563     private static class NotifyHandshakeThread extends Thread {
2564 
2565         private Set<Map.Entry<HandshakeCompletedListener,AccessControlContext>>
2566                 targets;        // who gets notified
2567         private HandshakeCompletedEvent event;          // the notification
2568 
2569         NotifyHandshakeThread(
2570             Set<Map.Entry<HandshakeCompletedListener,AccessControlContext>>
2571             entrySet, HandshakeCompletedEvent e) {
2572 
2573             super("HandshakeCompletedNotify-Thread");
2574             targets = new HashSet<>(entrySet);          // clone the entry set
2575             event = e;
2576         }
2577 
2578         @Override
2579         public void run() {
2580             // Don't need to synchronize, as it only runs in one thread.
2581             for (Map.Entry<HandshakeCompletedListener,AccessControlContext>
2582                 entry : targets) {
2583 
2584                 final HandshakeCompletedListener l = entry.getKey();
2585                 AccessControlContext acc = entry.getValue();
2586                 AccessController.doPrivileged(new PrivilegedAction<Void>() {
2587                     @Override
2588                     public Void run() {
2589                         l.handshakeCompleted(event);
2590                         return null;
2591                     }
2592                 }, acc);
2593             }
2594         }
2595     }
2596 
2597     /**
2598      * Returns a printable representation of this end of the connection.
2599      */
2600     @Override
2601     public String toString() {
2602         StringBuilder retval = new StringBuilder(80);
2603 
2604         retval.append(Integer.toHexString(hashCode()));
2605         retval.append("[");
2606         retval.append(sess.getCipherSuite());
2607         retval.append(": ");
2608 
2609         retval.append(super.toString());
2610         retval.append("]");
2611 
2612         return retval.toString();
2613     }
2614 }