SSLSocketImpl.java revision 904
904N/A * Copyright 1996-2009 Sun Microsystems, Inc. All Rights Reserved. 0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 0N/A * This code is free software; you can redistribute it and/or modify it 0N/A * under the terms of the GNU General Public License version 2 only, as 0N/A * published by the Free Software Foundation. Sun designates this 0N/A * particular file as subject to the "Classpath" exception as provided 0N/A * by Sun in the LICENSE file that accompanied this code. 0N/A * This code is distributed in the hope that it will be useful, but WITHOUT 0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 0N/A * version 2 for more details (a copy is included in the LICENSE file that 0N/A * accompanied this code). 0N/A * You should have received a copy of the GNU General Public License version 0N/A * 2 along with this work; if not, write to the Free Software Foundation, 0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 0N/A * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, 0N/A * CA 95054 USA or visit www.sun.com if you need additional information or 0N/A * have any questions. 0N/A * Implementation of an SSL socket. This is a normal connection type 0N/A * socket, implementing SSL over some lower level socket, such as TCP. 0N/A * Because it is layered over some lower level socket, it MUST override 0N/A * all default socket methods. 0N/A * <P> This API offers a non-traditional option for establishing SSL 0N/A * connections. You may first establish the connection directly, then pass 0N/A * that connection to the SSL socket constructor with a flag saying which 0N/A * role should be taken in the handshake protocol. (The two ends of the 0N/A * connection must not choose the same role!) This allows setup of SSL 0N/A * proxying or tunneling, and also allows the kind of "role reversal" 0N/A * that is required for most FTP data transfers. 0N/A * @see javax.net.ssl.SSLSocket 0N/A * @see SSLServerSocket 0N/A * @author David Brownell 0N/A * ERROR HANDLING GUIDELINES 0N/A * (which exceptions to throw and catch and which not to throw and catch) 0N/A * . if there is an IOException (SocketException) when accessing the 0N/A * underlying Socket, pass it through 0N/A * . do not throw IOExceptions, throw SSLExceptions (or a subclass) 0N/A * . for internal errors (things that indicate a bug in JSSE or a 0N/A * grossly misconfigured J2RE), throw either an SSLException or 0N/A * a RuntimeException at your convenience. 0N/A * . handshaking code (Handshaker or HandshakeMessage) should generally 0N/A * pass through exceptions, but can handle them if they know what to 0N/A * . exception chaining should be used for all new code. If you happen 0N/A * to touch old code that does not use chaining, you should change it. 0N/A * . there is a top level exception handler that sits at all entry 0N/A * points from application code to SSLSocket read/write code. It 0N/A * makes sure that all errors are handled (see handleException()). 0N/A * . JSSE internal code should generally not call close(), call 0N/A * There's a state machine associated with each connection, which 0N/A * among other roles serves to negotiate session changes. 0N/A * - START with constructor, until the TCP connection's around. 0N/A * - HANDSHAKE picks session parameters before allowing traffic. 0N/A * There are many substates due to sequencing requirements 0N/A * for handshake messages. 0N/A * - DATA may be transmitted. 0N/A * - RENEGOTIATE state allows concurrent data and handshaking 0N/A * traffic ("same" substates as HANDSHAKE), and terminates 0N/A * in selection of new session (and connection) parameters 0N/A * - ERROR state immediately precedes abortive disconnect. 0N/A * - SENT_CLOSE sent a close_notify to the peer. For layered, 0N/A * non-autoclose socket, must now read close_notify 0N/A * from peer before closing the connection. For nonlayered or 0N/A * non-autoclose socket, close connection and go onto 0N/A * - CLOSED after sending close_notify alert, & socket is closed. 0N/A * SSL connection objects are not reused. 0N/A * - APP_CLOSED once the application calls close(). Then it behaves like 0N/A * a closed socket, e.g.. getInputStream() throws an Exception. 0N/A * State affects what SSL record types may legally be sent: 0N/A * - Handshake ... only in HANDSHAKE and RENEGOTIATE states 0N/A * - App Data ... only in DATA and RENEGOTIATE states 0N/A * - Alert ... in HANDSHAKE, DATA, RENEGOTIATE 0N/A * Re what may be received: same as what may be sent, except that 0N/A * HandshakeRequest handshaking messages can come from servers even 0N/A * in the application data state, to request entry to RENEGOTIATE. 0N/A * The state machine within HANDSHAKE and RENEGOTIATE states controls 0N/A * the pending session, not the connection state, until the change 0N/A * cipher spec and "Finished" handshake messages are processed and 0N/A * make the "new" session become the current one. 0N/A * NOTE: details of the SMs always need to be nailed down better. 0N/A * The text above illustrates the core ideas. 0N/A * +---->-------+------>--------->-------+ 0N/A * <-----< ^ ^ <-----< v 0N/A *START>----->HANDSHAKE>----->DATA>----->RENEGOTIATE SENT_CLOSE 0N/A * +------------+---------------+ v ERROR 0N/A * ERROR>------>----->CLOSED<--------<----+-- + 0N/A * ALSO, note that the the purpose of handshaking (renegotiation is 0N/A * included) is to assign a different, and perhaps new, session to 0N/A * the connection. The SSLv3 spec is a bit confusing on that new 0N/A * Client authentication be off, requested, or required. 0N/A * Migrated to SSLEngineImpl: 0N/A * Drives the protocol state machine. 0N/A * Flag indicating if the next record we receive MUST be a Finished 0N/A * message. Temporarily set during the handshake to ensure that 0N/A * a change cipher spec message is followed by a finished message. 0N/A * For improved diagnostics, we detail connection closure 0N/A * If the socket is closed (connectionState >= cs_ERROR), 0N/A * closeReason != null indicates if the socket was closed 0N/A * because of an error or because or normal shutdown. 0N/A * Per-connection private state that doesn't change when the 0N/A * session is changed. 0N/A // hostname identification algorithm, the hostname identification is 0N/A // disabled by default. 0N/A * READ ME * READ ME * READ ME * READ ME * READ ME * READ ME * 0N/A * IMPORTANT STUFF TO UNDERSTANDING THE SYNCHRONIZATION ISSUES. 0N/A * READ ME * READ ME * READ ME * READ ME * READ ME * READ ME * 0N/A * There are several locks here. 0N/A * The primary lock is the per-instance lock used by 0N/A * synchronized(this) and the synchronized methods. It controls all 0N/A * access to things such as the connection state and variables which 0N/A * affect handshaking. If we are inside a synchronized method, we 0N/A * can access the state directly, otherwise, we must use the 0N/A * synchronized equivalents. 0N/A * The handshakeLock is used to ensure that only one thread performs 0N/A * the *complete initial* handshake. If someone is handshaking, any 0N/A * stray application or startHandshake() requests who find the 0N/A * connection state is cs_HANDSHAKE will stall on handshakeLock 0N/A * until handshaking is done. Once the handshake is done, we either 0N/A * succeeded or failed, but we can never go back to the cs_HANDSHAKE 0N/A * or cs_START state again. 0N/A * Note that the read/write() calls here in SSLSocketImpl are not 0N/A * obviously synchronized. In fact, it's very nonintuitive, and 0N/A * requires careful examination of code paths. Grab some coffee, 0N/A * and be careful with any code changes. 0N/A * There can be only three threads active at a time in the I/O 0N/A * subsection of this class. 0N/A * 3. AppOutputStream 0N/A * One thread could call startHandshake(). 0N/A * synchronized on 'this' in their respective classes, so only one 0N/A * app. thread will be doing a SSLSocketImpl.read() or .write()'s at 0N/A * If handshaking is required (state cs_HANDSHAKE), and 0N/A * getConnectionState() for some/all threads returns cs_HANDSHAKE, 0N/A * only one can grab the handshakeLock, and the rest will stall 0N/A * either on getConnectionState(), or on the handshakeLock if they 0N/A * happen to successfully race through the getConnectionState(). 0N/A * If a writer is doing the initial handshaking, it must create a 0N/A * temporary reader to read the responses from the other side. As a 0N/A * side-effect, the writer's reader will have priority over any 0N/A * other reader. However, the writer's reader is not allowed to 0N/A * consume any application data. When handshakeLock is finally 0N/A * released, we either have a cs_DATA connection, or a 0N/A * The writeLock is held while writing on a socket connection and 0N/A * also to protect the MAC and cipher for their direction. The 0N/A * writeLock is package private for Handshaker which holds it while 0N/A * writing the ChangeCipherSpec message. 0N/A * To avoid the problem of a thread trying to change operational 0N/A * modes on a socket while handshaking is going on, we synchronize 0N/A * on 'this'. If handshaking has not started yet, we tell the 0N/A * handshaker to change its mode. If handshaking has started, 0N/A * we simply store that request until the next pending session 0N/A * is created, at which time the new handshaker's state is set. 0N/A * The readLock is held during readRecord(), which is responsible 0N/A * for reading an InputRecord, decrypting it, and processing it. 0N/A * The readLock ensures that these three steps are done atomically 0N/A * and that once started, no other thread can block on InputRecord.read. 0N/A * This is necessary so that processing of close_notify alerts 0N/A * from the peer are handled properly. 0N/A * Crypto state that's reinitialized when the session changes. 0N/A // NOTE: compression state would be saved here 0N/A * The authentication context holds all information used to establish 0N/A * who this end of the connection is (certificate chains, private keys, 0N/A * etc) and who is trusted (e.g. as CAs or websites). 0N/A * This connection is one of (potentially) many associated with 0N/A * any given session. The output of the handshake protocol is a 0N/A * new session ... although all the protocol description talks 0N/A * about changing the cipher spec (and it does change), in fact 0N/A * that's incidental since it's done by changing everything that 0N/A * is associated with a session at the same time. (TLS/IETF may 0N/A * change that to add client authentication w/o new key exchg.) 0N/A * If anyone wants to get notified about handshake completions, 0N/A * they'll show up on this list. 0N/A * These input and output streams block their data in SSL records, 0N/A * and usually arrange integrity and privacy protection for those 0N/A * records. The guts of the SSL protocol are wrapped up in these 0N/A * streams, and in the handshaking that establishes the details of 0N/A * that integrity and privacy protection. 0N/A * The protocols we support are SSL Version 3.0) and 0N/A * TLS (version 3.1). 0N/A * In addition we support a pseudo protocol called 0N/A * SSLv2Hello which when set will result in an SSL v2 Hello 0N/A * being sent with SSLv3 or TLSv1 version info. 0N/A * The SSL version associated with this connection. 0N/A /* Class and subclass dynamic debugging support */ 0N/A // CONSTRUCTORS AND INITIALIZATION CODE 0N/A * Constructs an SSL connection to a named host at a specified port, 0N/A * using the authentication context provided. This endpoint acts as 0N/A * the client, and may rejoin an existing SSL session if appropriate. 0N/A * @param context authentication context to use 0N/A * @param host name of the host with which to connect 0N/A * @param port number of the server's port 0N/A * Constructs an SSL connection to a server at a specified address. 0N/A * and TCP port, using the authentication context provided. This 0N/A * endpoint acts as the client, and may rejoin an existing SSL session 0N/A * @param context authentication context to use 0N/A * @param address the server's host 0N/A * @param port its port 0N/A * Constructs an SSL connection to a named host at a specified port, 0N/A * using the authentication context provided. This endpoint acts as 0N/A * the client, and may rejoin an existing SSL session if appropriate. 0N/A * @param context authentication context to use 0N/A * @param host name of the host with which to connect 0N/A * @param port number of the server's port 0N/A * @param localAddr the local address the socket is bound to 0N/A * @param localPort the local port the socket is bound to 0N/A * Constructs an SSL connection to a server at a specified address. 0N/A * and TCP port, using the authentication context provided. This 0N/A * endpoint acts as the client, and may rejoin an existing SSL session 0N/A * @param context authentication context to use 0N/A * @param address the server's host 0N/A * @param port its port 0N/A * @param localAddr the local address the socket is bound to 0N/A * @param localPort the local port the socket is bound to 0N/A * Package-private constructor used ONLY by SSLServerSocket. The 0N/A * java.net package accepts the TCP connection after this call is 0N/A * made. This just initializes handshake state to use "server mode", 0N/A * giving control over the use of SSL client authentication. 0N/A * Override what was picked out for us. 0N/A * Package-private constructor used to instantiate an unconnected 0N/A * socket. The java.net package will connect it, either when the 0N/A * connect() call is made by the application. This instance is 0N/A * meant to set handshake state to use "client mode". 0N/A * Layer SSL traffic over an existing connection, rather than creating 0N/A * a new connection. The existing connection may be used only for SSL 0N/A * traffic (using this SSLSocket) until the SSLSocket.close() call 0N/A * returns. However, if a protocol error is detected, that existing 0N/A * connection is automatically closed. 0N/A * <P> This particular constructor always uses the socket in the 0N/A * role of an SSL client. It may be useful in cases which start 0N/A * using SSL after some initial data transfers, for example in some 0N/A * SSL tunneling applications or as part of some kinds of application 0N/A * protocols which negotiate use of a SSL based security. 0N/A * @param sock the existing connection 0N/A * @param context the authentication context to use 0N/A // We always layer over a connected socket 0N/A * Initializes the client socket. 0N/A * role is as specified, state is START until after 0N/A * the low level connection's established. 0N/A * default read and write side cipher and MAC support 0N/A * Note: compression support would go here too 0N/A * Connects this socket to the server with a specified timeout 0N/A * This method is either called on an unconnected SSLSocketImpl by the 0N/A * application, or it is called in the constructor of a regular 0N/A * SSLSocketImpl. If we are layering on top on another socket, then 0N/A * this method should not be called, because we assume that the 0N/A * underlying socket is already connected by the time it is passed to 0N/A * @param endpoint the <code>SocketAddress</code> 0N/A * @param timeout the timeout value to be used, 0 is no timeout 0N/A * @throws IOException if an error occurs during the connection 0N/A * @throws SocketTimeoutException if timeout expires before connecting 0N/A "Cannot handle non-Inet socket addresses.");
0N/A * Initialize the handshaker and socket streams. 0N/A * Called by connect, the layered constructor, and SSLServerSocket. 0N/A * Save the input and output streams. May be done only after 0N/A * java.net actually connects using the socket "self", else 0N/A * we get some pretty bizarre failure modes. 0N/A * Move to handshaking state, with pending session initialized 0N/A * to defaults and the appropriate kind of handshaker set up. 0N/A // READING AND WRITING RECORDS 0N/A * Record Output. Application data can't be sent until the first 0N/A * handshake establishes a session. 0N/A * NOTE: we let empty records be written as a hook to force some 0N/A * TCP-level activity, notably handshaking, to occur. 0N/A * The loop is in case of HANDSHAKE --> ERROR transitions, etc 0N/A * Not all states support passing application data. We 0N/A * synchronize access to the connection state, so that 0N/A * synchronous handshakes can complete cleanly. 0N/A * We've deferred the initial handshaking till just now, 0N/A * when presumably a thread's decided it's OK to block for 0N/A * longish periods of time for I/O purposes (as well as 0N/A * configured the cipher suites it wants to use). 0N/A "error while writing to socket");
0N/A // we should never get here (check in AppOutputStream) 0N/A // this is just a fallback 0N/A * Else something's goofy in this state machine's use. 0N/A // Don't bother to really write empty records. We went this 0N/A // far to drive the handshake machinery, for correctness; not 0N/A // writing empty records improves performance by cutting CPU 0N/A // time and network resource usage. However, some protocol 0N/A // implementations are fragile and don't like to see empty 0N/A // records, so this also increases robustness. 77N/A // If the record is a close notify alert, we need to honor 77N/A // socket option SO_LINGER. Note that we will try to send 77N/A // the close notify even if the SO_LINGER set to zero. 77N/A // keep and clear the current thread interruption status. 77N/A "SO_LINGER timeout," +
77N/A " close_notify message cannot be sent.");
77N/A // For layered, non-autoclose sockets, we are not 77N/A // able to bring them into a usable state, so we 77N/A // treat it as fatal error. 77N/A // Note that the alert description is 77N/A // specified as -1, so no message will be send 77N/A // to peer anymore. 77N/A // RFC2246 requires that the session becomes 77N/A // unresumable if any connection is terminated 77N/A // without proper close_notify messages with 77N/A // level equal to warning. 77N/A // RFC4346 no longer requires that a session not be 77N/A // resumed if failure to properly close a connection. 77N/A // We choose to make the session unresumable if 77N/A // failed to send the close_notify message. 77N/A // keep interrupted status 77N/A // restore the interrupted status 0N/A * Read an application data record. Alerts and handshake 0N/A * messages are handled directly. 0N/A * Clear the pipeline of records from the peer, optionally returning 0N/A * application data. Caller is responsible for knowing that it's 0N/A * possible to do this kind of clearing, if they don't want app 0N/A * data -- e.g. since it's the initial SSL handshake. 0N/A * Don't synchronize (this) during a blocking read() since it 0N/A * protects data which is accessed on the write side as well. 0N/A // readLock protects reading and processing of an InputRecord. 0N/A // It keeps the reading from sockInput and processing of the record 0N/A // atomic so that no two threads can be blocked on the 0N/A // read from the same input stream at the same time. 0N/A // This is required for example when a reader thread is 0N/A // blocked on the read and another thread is trying to 0N/A // close the socket. For a non-autoclose, layered socket, 0N/A // the thread performing the close needs to read the close_notify. 0N/A // Use readLock instead of 'this' for locking because 0N/A // 'this' also protects data accessed during writing. 0N/A * Read and handle records ... return application data 0N/A * ONLY if it's needed. 0N/A * Read a record ... maybe emitting an alert if we get a 0N/A * comprehensible but unsupported "hello" message during 0N/A * format checking (e.g. V2). 0N/A // discard this exception 0N/A ", received EOFException: " 0N/A (
"Remote host closed connection during handshake");
0N/A (
"Remote host closed connection incorrectly");
0N/A // treat as if we had received a close_notify 0N/A * The basic SSLv3 record protection involves (optional) 0N/A * encryption for privacy, and an integrity check ensuring 0N/A * data origin authentication. We do them both here, and 0N/A * throw a fatal alert if the integrity check fails. 0N/A // RFC 2246 states that decryption_failed should be used 0N/A // for this purpose. However, that allows certain attacks, 0N/A // so we just send bad record MAC. We also need to make 0N/A // sure to always check the MAC to avoid a timing attack 0N/A // for the same issue. See paper by Vaudenay et al. 0N/A // use the same alert types as for MAC failure below 0N/A "bad handshake record MAC");
0N/A // if (!r.decompress(c)) 0N/A // fatal(Alerts.alert_decompression_failure, 0N/A // "decompression failure"); 0N/A * Process the record. 0N/A synchronized (
this) {
0N/A * Handshake messages always go to a pending session 0N/A * handshaker ... if there isn't one, create one. This 0N/A * must work asynchronously, for renegotiation. 0N/A * NOTE that handshaking will either resume a session 0N/A * which was in the cache (and which might have other 0N/A * connections in it already), or else will start a new 0N/A * session (new keys exchanged) with just this connection 0N/A * process the handshake record ... may contain just 0N/A * a partial handshake message or multiple messages. 0N/A * The handshaker state machine will ensure that it's 0N/A * a finished message. 0N/A // Tell folk about handshake completion, but do 0N/A // it in a separate thread. 0N/A // Pass this right back up to the application. 0N/A "Data received in non-data state: " +
0N/A (
"Expecting finished message, received data");
0N/A "illegal change cipher spec msg, state = " 0N/A // The first message after a change_cipher_spec 0N/A // record MUST be a "Finished" handshake record, 0N/A // else it's a protocol violation. We force this 0N/A // to be checked by a minor tweak to the state 0N/A // next message MUST be a finished message 0N/A // TLS requires that unrecognized records be ignored. 0N/A ", Received record type: " 0N/A }
// synchronized (this) 0N/A // couldn't read, due to some kind of error 0N/A }
// synchronized (readLock) 0N/A // HANDSHAKE RELATED CODE 0N/A * Return the AppInputStream. For use by Handshaker only. 0N/A * Initialize and get the server handshaker. Used by SSLServerSocketImpl 0N/A * for the ciphersuite availability test *only*. 709N/A // The connection state would have been set to cs_HANDSHAKE during the 709N/A // handshaking initializing, however the caller may not have the 709N/A // the low level connection's established, which is not consistent with 709N/A // the HANDSHAKE state. As if it is unconnected, we need to reset the 709N/A // connection state to cs_START. 709N/A // Make sure that we get a ServerHandshaker. 709N/A // This should never happen. 0N/A * Initialize the handshaker object. This means: 0N/A * . if a handshake is already in progress (state is cs_HANDSHAKE 0N/A * or cs_RENEGOTIATE), do nothing and return 0N/A * . if the socket is already closed, throw an Exception (internal error) 0N/A * . otherwise (cs_START or cs_DATA), create the appropriate handshaker 0N/A * object, initialize it, and advance the connection state (to 0N/A * cs_HANDSHAKE or cs_RENEGOTIATE, respectively). 0N/A * This method is called right after a new socket is created, when 0N/A * starting renegotiation, or when changing client/ server mode of the 0N/A // Starting a new handshake. 0N/A // We're already in the middle of a handshake. 0N/A // Anyone allowed to call this routine is required to 0N/A // do so ONLY if the connection state is reasonable... 0N/A // state is either cs_START or cs_DATA 0N/A // don't use SSLv2Hello when renegotiating 0N/A * Synchronously perform the initial handshake. 0N/A * If the handshake is already in progress, this method blocks until it 0N/A * is completed. If the initial handshake has already been completed, 0N/A * it returns immediately. 0N/A // use handshakeLock and the state check to make sure only 0N/A // one thread performs the handshake 0N/A * All initial handshaking goes through this 0N/A * InputRecord until we have a valid SSL connection. 0N/A * Once initial handshaking is finished, AppInputStream's 0N/A * InputRecord can handle any future renegotiation. 0N/A * Keep this local so that it goes out of scope and is 0N/A * Grab the characteristics already assigned to 0N/A * AppInputStream's InputRecord. Enable checking for 0N/A * SSLv2 hellos on this first handshake. 0N/A * Starts an SSL handshake on this connection. 0N/A // start an ssl handshake that could be resumed from timeout exception 0N/A * Starts an ssl handshake on this connection. 0N/A * @param resumable indicates the handshake process is resumable from a 0N/A * certain exception. If <code>resumable</code>, the socket will 0N/A * be reserved for exceptions like timeout; otherwise, the socket 0N/A * will be closed, no further communications could be done. 0N/A // do initial handshake 0N/A // start renegotiation 0N/A // shutdown and rethrow (wrapped) exception as appropriate 0N/A * Kickstart the handshake if it is not already in progress. 0N/A * . if handshaking is already underway, do nothing and return 0N/A * . if the socket is not connected or already closed, throw an 0N/A * . otherwise, call initHandshake() to initialize the handshaker 0N/A * object and progress the state. Then, send the initial 0N/A * handshaking message if appropriate (always on clients and 0N/A * on servers when renegotiating). 0N/A // handshaker already setup, proceed 0N/A // initialize the handshaker, move to cs_RENEGOTIATE 0N/A // handshaking already in progress, return 0N/A * The only way to get a socket in the state is when 0N/A * you have an unconnected socket. 0N/A "handshaking attempted on unconnected socket");
0N/A // Kickstart handshake state machine if we need to ... 0N/A // Note that handshaker.kickstart() writes the message 0N/A // to its HandshakeOutStream, which calls back into 0N/A // SSLSocketImpl.writeRecord() to send it. 0N/A // send client hello 0N/A // initial handshake, no kickstart message to send 0N/A // we want to renegotiate, send hello request 0N/A // hello request is not included in the handshake 0N/A // hashes, reset them 0N/A // CLOSURE RELATED CALLS 0N/A * Return whether the socket has been explicitly closed by the application. 0N/A * Return whether we have reached end-of-file. 0N/A * If the socket is not connected, has been shutdown because of an error 0N/A * or has been closed, throw an Exception. 0N/A // either closed because of error, or normal EOF 0N/A * Check if we can write data to this socket. If not, throw an IOException. 0N/A // we are at EOF, write must throw Exception 0N/A * Closing the connection is tricky ... we can't officially close the 0N/A * connection until we know the other end is ready to go away too, 0N/A * and if ever the connection gets aborted we must forget session 0N/A * state (it becomes invalid). 0N/A * Closes the SSL connection. SSL includes an application level 0N/A * shutdown handshake; you should close SSL sockets explicitly 0N/A * rather than leaving it for finalization, so that your remote 0N/A * peer does not experience a protocol error. 0N/A * Don't synchronize the whole method because waitForClose() 0N/A * (which calls readRecord()) might be called. 0N/A * @param selfInitiated Indicates which party initiated the close. 0N/A * If selfInitiated, this side is initiating a close; for layered and 0N/A * non-autoclose socket, wait for close_notify response. 0N/A * If !selfInitiated, peer sent close_notify; we reciprocate but 0N/A * no need to wait for response. 0N/A * java.net code sometimes closes sockets "early", when 0N/A * we can't actually do I/O on them. 0N/A * If we're closing down due to error, we already sent (or else 0N/A * received) the fatal alert ... no niceties, blow the connection 0N/A * away as quickly as possible (even if we didn't allocate the 0N/A * socket ourselves; it's unusable, regardless). 0N/A * Sometimes close() gets called more than once. 0N/A * Otherwise we indicate clean termination. 0N/A // case cs_HANDSHAKE: 0N/A // case cs_RENEGOTIATE: 0N/A // case cs_SENT_CLOSE: 0N/A synchronized (
this) {
0N/A return;
// connection was closed while we waited 0N/A // If state was cs_SENT_CLOSE before, we don't do the actual 0N/A // closing since it is already in progress. 0N/A ", close invoked again; state = " +
0N/A // We were called because a close_notify message was 0N/A // received. This may be due to another thread calling 0N/A // read() or due to our call to waitForClose() below. 0N/A // In either case, just return. 0N/A // Another thread explicitly called close(). We need to 0N/A // wait for the closing to complete before returning. 0N/A synchronized (
this) {
0N/A ", after primary close; state = " +
0N/A // layered && non-autoclose 0N/A // read close_notify alert to clear input stream 782N/A // See comment in changeReadCiphers() 0N/A // state will be set to cs_CLOSED in the finally block below 0N/A synchronized (
this) {
0N/A // Upon exit from this method, the state is always >= cs_CLOSED 0N/A // notify any threads waiting for the closing to finish 0N/A * Reads a close_notify or a fatal alert from the input stream. 0N/A * Keep reading records until we get a close_notify or until 0N/A * the connection is otherwise closed. The close_notify or alert 0N/A * might be read by another reader, 0N/A * which will then process the close and set the connection state. 0N/A ", waiting for close_notify or alert: state " 0N/A // create the InputRecord if it isn't intialized. 0N/A // Ask for app data and then throw it away 0N/A // if time out, ignore the exception and continue 0N/A ", Exception while waiting for close " +e);
0N/A throw e;
// pass exception up 0N/A // EXCEPTION AND ALERT HANDLING 0N/A * Handle an exception. This method is called by top level exception 0N/A * handlers (in read(), write()) to make sure we always shutdown the 0N/A * connection correctly and do not pass runtime exception to the 0N/A * Handle an exception. This method is called by top level exception 0N/A * handlers (in read(), write(), startHandshake()) to make sure we 0N/A * always shutdown the connection correctly and do not pass runtime 0N/A * exception to the application. 0N/A * This method never returns normally, it always throws an IOException. 0N/A * We first check if the socket has already been shutdown because of an 0N/A * error. If so, we just rethrow the exception. If the socket has not 0N/A * been shutdown, we sent a fatal alert and remember the exception. 0N/A * @param e the Exception 0N/A * @param resumable indicates the caller process is resumable from the 0N/A * exception. If <code>resumable</code>, the socket will be 0N/A * reserved for exceptions like timeout; otherwise, the socket 0N/A * will be closed, no further communications could be done. 0N/A // don't close the Socket in case of timeouts or interrupts if 0N/A // the process is resumable. 0N/A // if we've already shutdown because of an error, 0N/A // there is nothing to do except rethrow the exception 0N/A // this is odd, not an IOException. 0N/A // normally, this should not happen 0N/A // if closeReason has been already been set 0N/A "Unexpected exception");
0N/A // need to perform error shutdown 0N/A // IOException from the socket 0N/A // this means the TCP connection is already dead 0N/A // we call fatal just to set the error status 0N/A // ignore (IOException wrapped in SSLException) 0N/A // rethrow original IOException 0N/A // must be SSLException or RuntimeException 0N/A * Send a warning alert. 0N/A * Send a fatal alert, and throw an exception so that callers will 0N/A * need to stand on their heads to accidentally continue processing. 0N/A * Has there been an error received yet? If not, remember it. 0N/A * By RFC 2246, we don't bother waiting for a response. 0N/A * Fatal errors require immediate shutdown. 0N/A * Try to clear the kernel buffer to avoid TCP connection resets. 77N/A // If the description equals -1, the alert won't be sent to peer. 0N/A * Clean up our side. 782N/A // See comment in changeReadCiphers() 0N/A * Process an incoming alert ... caller must already have synchronized 0N/A "Received close_notify during handshake");
0N/A // The other legal warnings relate to certificates, 0N/A // e.g. no_certificate, bad_certificate, etc; these 0N/A // are important to the handshaking code, which can 0N/A // also handle illegal protocol alerts if needed. 0N/A }
else {
// fatal or unknown level 0N/A * Emit alerts. Caller must have synchronized with "this". 0N/A ", Exception sending alert: " + e);
0N/A // VARIOUS OTHER METHODS 0N/A * When a connection finishes handshaking by enabling use of a newly 0N/A * negotiated session, each end learns about it in two halves (read, 0N/A * and write). When both read and write ciphers have changed, and the 0N/A * last handshake message has been read, the connection has joined 0N/A * (rejoined) the new session. 0N/A * NOTE: The SSLv3 spec is rather unclear on the concepts here. 0N/A * Sessions don't change once they're established (including cipher 0N/A * suite and master secret) but connections can join them (and leave 0N/A * them). They're created by handshaking, though sometime handshaking 0N/A * causes connections to join up with pre-established sessions. 0N/A "State error, change cipher specs");
0N/A // ... create decompressor 782N/A * Dispose of any intermediate state in the underlying cipher. 782N/A * For PKCS11 ciphers, this will release any attached sessions, 782N/A * and thus make finalization faster. 782N/A * Since MAC's doFinal() is called for every SSL/TLS packet, it's 782N/A * not necessary to do the same with MAC's. 0N/A // used by Handshaker 0N/A "State error, change cipher specs");
0N/A // ... create compressor 0N/A * Updates the SSL version associated with this connection. 0N/A * Called from Handshaker once it has determined the negotiated version. 904N/A // Note that the host may be null or empty for localhost. 0N/A * Gets an input stream to read from the peer on the other side. 0N/A * Data read from this stream was always integrity protected in 0N/A * transit, and will usually have been confidentiality protected. 0N/A * Can't call isConnected() here, because the Handshakers 0N/A * do some initialization before we actually connect. 0N/A * Gets an output stream to write to the peer on the other side. 0N/A * Data written on this stream is always integrity protected, and 0N/A * will usually be confidentiality protected. 0N/A * Can't call isConnected() here, because the Handshakers 0N/A * do some initialization before we actually connect. 0N/A * Returns the the SSL Session in use by this connection. These can 0N/A * be long lived, and frequently correspond to an entire login session 0N/A * Force a synchronous handshake, if appropriate. 0N/A // start handshaking, if failed, the connection will be closed. 0N/A // handshake failed. log and return a nullSession 0N/A ", IOException in getSession(): " + e);
0N/A synchronized (
this) {
0N/A * Controls whether new connections may cause creation of new SSL 0N/A * As long as handshaking has not started, we can change 0N/A * whether we enable session creations. Otherwise, 0N/A * we will need to wait for the next handshake. 0N/A * Returns true if new connections may cause creation of new SSL 0N/A * Sets the flag controlling whether a server mode socket 0N/A * *REQUIRES* SSL client authentication. 0N/A * As long as handshaking has not started, we can change 0N/A * whether client authentication is needed. Otherwise, 0N/A * we will need to wait for the next handshake. 0N/A * Sets the flag controlling whether a server mode socket 0N/A * *REQUESTS* SSL client authentication. 0N/A * As long as handshaking has not started, we can change 0N/A * whether client authentication is requested. Otherwise, 0N/A * we will need to wait for the next handshake. 0N/A * Sets the flag controlling whether the socket is in SSL 0N/A * client or server mode. Must be called before any SSL 0N/A * traffic has started. 0N/A * If we have a handshaker, but haven't started 0N/A * SSL traffic, we can throw away our current 0N/A * handshaker, and start from scratch. Don't 0N/A * need to call doneConnect() again, we already 0N/A // If handshake has started, that's an error. Fall through... 0N/A ", setUseClientMode() invoked in state = " +
0N/A "Cannot change mode after SSL traffic has started");
0N/A * Returns the names of the cipher suites which could be enabled for use 0N/A * on an SSL connection. Normally, only a subset of these will actually 0N/A * be enabled by default, since this list may include cipher suites which 0N/A * do not support the mutual authentication of servers and clients, or 0N/A * which do not protect data confidentiality. Servers may also need 0N/A * certain kinds of certificates to use certain cipher suites. 0N/A * @return an array of cipher suite names 0N/A * Controls which particular cipher suites are enabled for use on 0N/A * this connection. The cipher suites must have been listed by 0N/A * getCipherSuites() as being supported. Even if a suite has been 0N/A * enabled, it might never be used if no peer supports it or the 0N/A * requisite certificates (and private keys) are not available. 0N/A * @param suites Names of all the cipher suites to enable. 0N/A * Returns the names of the SSL cipher suites which are currently enabled 0N/A * for use on this connection. When an SSL socket is first created, 0N/A * all enabled cipher suites <em>(a)</em> protect data confidentiality, 0N/A * by traffic encryption, and <em>(b)</em> can mutually authenticate 0N/A * both clients and servers. Thus, in some environments, this value 0N/A * @return an array of cipher suite names 0N/A * Returns the protocols that are supported by this implementation. 0N/A * A subset of the supported protocols may be enabled for this connection 0N/A * @ returns an array of protocol names. 0N/A * Controls which protocols are enabled for use on 0N/A * this connection. The protocols must have been listed by 0N/A * getSupportedProtocols() as being supported. 0N/A * @param protocols protocols to enable. 0N/A * @exception IllegalArgumentException when one of the protocols 0N/A * named by the parameter is not supported. 0N/A * Assigns the socket timeout. 0N/A * @see java.net.Socket#setSoTimeout 0N/A * Registers an event listener to receive notifications that an 0N/A * SSL handshake has completed on this connection. 0N/A * Removes a previously registered handshake completion listener. 0N/A * Try to configure the endpoint identification algorithm of the socket. 0N/A * @param identificationAlgorithm the algorithm used to check the 0N/A * endpoint identity. 0N/A * @return true if the identification algorithm configuration success. 0N/A * Returns the endpoint identification algorithm of the socket. 0N/A // We allocate a separate thread to deliver handshake completion 0N/A // events. This ensures that the notifications don't block the 0N/A // protocol state machine. 0N/A super(
"HandshakeCompletedNotify-Thread");
0N/A * Return the name of the current thread. Utility method. 0N/A * Returns a printable representation of this end of the connection.