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