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