SSLSocketImpl.java 57.2 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1996, 2020, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25 26 27
 */

package sun.security.ssl;

X
xuelei 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.List;
41
import java.util.concurrent.locks.ReentrantLock;
42
import java.util.function.BiFunction;
X
xuelei 已提交
43 44 45 46 47 48 49 50
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLProtocolException;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
51 52
import jdk.internal.misc.JavaNetInetAddressAccess;
import jdk.internal.misc.SharedSecrets;
53

D
duke 已提交
54
/**
X
xuelei 已提交
55 56 57 58 59 60 61
 * Implementation of an SSL socket.
 * <P>
 * This is a normal connection type socket, implementing SSL over some lower
 * level socket, such as TCP.  Because it is layered over some lower level
 * socket, it MUST override all default socket methods.
 * <P>
 * This API offers a non-traditional option for establishing SSL
D
duke 已提交
62 63 64 65 66 67 68 69 70 71 72 73
 * connections.  You may first establish the connection directly, then pass
 * that connection to the SSL socket constructor with a flag saying which
 * role should be taken in the handshake protocol.  (The two ends of the
 * connection must not choose the same role!)  This allows setup of SSL
 * proxying or tunneling, and also allows the kind of "role reversal"
 * that is required for most FTP data transfers.
 *
 * @see javax.net.ssl.SSLSocket
 * @see SSLServerSocket
 *
 * @author David Brownell
 */
X
xuelei 已提交
74 75
public final class SSLSocketImpl
        extends BaseSSLSocketImpl implements SSLTransport {
76

X
xuelei 已提交
77 78
    final SSLContextImpl            sslContext;
    final TransportContext          conContext;
D
duke 已提交
79

X
xuelei 已提交
80 81
    private final AppInputStream    appInput = new AppInputStream();
    private final AppOutputStream   appOutput = new AppOutputStream();
D
duke 已提交
82

X
xuelei 已提交
83 84 85
    private String                  peerHost;
    private boolean                 autoClose;
    private boolean                 isConnected = false;
86
    private volatile boolean        tlsIsClosed = false;
87

88 89 90
    private final ReentrantLock     socketLock = new ReentrantLock();
    private final ReentrantLock     handshakeLock = new ReentrantLock();

91 92 93 94 95 96
    /*
     * Is the local name service trustworthy?
     *
     * If the local name service is not trustworthy, reverse host name
     * resolution should not be performed for endpoint identification.
     */
X
xuelei 已提交
97 98
    private static final boolean trustNameService =
            Utilities.getBooleanProperty("jdk.tls.trustNameService", false);
D
duke 已提交
99 100

    /**
X
xuelei 已提交
101 102
     * Package-private constructor used to instantiate an unconnected
     * socket.
D
duke 已提交
103
     *
X
xuelei 已提交
104
     * This instance is meant to set handshake state to use "client mode".
D
duke 已提交
105
     */
X
xuelei 已提交
106
    SSLSocketImpl(SSLContextImpl sslContext) {
D
duke 已提交
107
        super();
X
xuelei 已提交
108 109 110 111 112
        this.sslContext = sslContext;
        HandshakeHash handshakeHash = new HandshakeHash();
        this.conContext = new TransportContext(sslContext, this,
                new SSLSocketInputRecord(handshakeHash),
                new SSLSocketOutputRecord(handshakeHash), true);
D
duke 已提交
113 114 115
    }

    /**
X
xuelei 已提交
116
     * Package-private constructor used to instantiate a server socket.
D
duke 已提交
117
     *
X
xuelei 已提交
118
     * This instance is meant to set handshake state to use "server mode".
D
duke 已提交
119
     */
X
xuelei 已提交
120
    SSLSocketImpl(SSLContextImpl sslContext, SSLConfiguration sslConfig) {
D
duke 已提交
121
        super();
X
xuelei 已提交
122 123 124 125 126
        this.sslContext = sslContext;
        HandshakeHash handshakeHash = new HandshakeHash();
        this.conContext = new TransportContext(sslContext, this, sslConfig,
                new SSLSocketInputRecord(handshakeHash),
                new SSLSocketOutputRecord(handshakeHash));
D
duke 已提交
127 128 129
    }

    /**
X
xuelei 已提交
130 131
     * Constructs an SSL connection to a named host at a specified
     * port, using the authentication context provided.
D
duke 已提交
132
     *
X
xuelei 已提交
133 134
     * This endpoint acts as the client, and may rejoin an existing SSL session
     * if appropriate.
D
duke 已提交
135
     */
X
xuelei 已提交
136 137
    SSLSocketImpl(SSLContextImpl sslContext, String peerHost,
            int peerPort) throws IOException, UnknownHostException {
D
duke 已提交
138
        super();
X
xuelei 已提交
139 140 141 142 143 144
        this.sslContext = sslContext;
        HandshakeHash handshakeHash = new HandshakeHash();
        this.conContext = new TransportContext(sslContext, this,
                new SSLSocketInputRecord(handshakeHash),
                new SSLSocketOutputRecord(handshakeHash), true);
        this.peerHost = peerHost;
145
        SocketAddress socketAddress =
X
xuelei 已提交
146 147
               peerHost != null ? new InetSocketAddress(peerHost, peerPort) :
               new InetSocketAddress(InetAddress.getByName(null), peerPort);
D
duke 已提交
148 149 150 151
        connect(socketAddress, 0);
    }

    /**
X
xuelei 已提交
152 153 154
     * Constructs an SSL connection to a server at a specified
     * address, and TCP port, using the authentication context
     * provided.
D
duke 已提交
155
     *
X
xuelei 已提交
156 157
     * This endpoint acts as the client, and may rejoin an existing SSL
     * session if appropriate.
D
duke 已提交
158
     */
X
xuelei 已提交
159 160
    SSLSocketImpl(SSLContextImpl sslContext,
            InetAddress address, int peerPort) throws IOException {
D
duke 已提交
161
        super();
X
xuelei 已提交
162 163 164 165 166
        this.sslContext = sslContext;
        HandshakeHash handshakeHash = new HandshakeHash();
        this.conContext = new TransportContext(sslContext, this,
                new SSLSocketInputRecord(handshakeHash),
                new SSLSocketOutputRecord(handshakeHash), true);
X
xuelei 已提交
167

X
xuelei 已提交
168 169
        SocketAddress socketAddress = new InetSocketAddress(address, peerPort);
        connect(socketAddress, 0);
D
duke 已提交
170 171 172
    }

    /**
X
xuelei 已提交
173 174 175 176 177
     * Constructs an SSL connection to a named host at a specified
     * port, using the authentication context provided.
     *
     * This endpoint acts as the client, and may rejoin an existing SSL
     * session if appropriate.
D
duke 已提交
178
     */
X
xuelei 已提交
179 180 181
    SSLSocketImpl(SSLContextImpl sslContext,
            String peerHost, int peerPort, InetAddress localAddr,
            int localPort) throws IOException, UnknownHostException {
D
duke 已提交
182
        super();
X
xuelei 已提交
183 184 185 186 187 188
        this.sslContext = sslContext;
        HandshakeHash handshakeHash = new HandshakeHash();
        this.conContext = new TransportContext(sslContext, this,
                new SSLSocketInputRecord(handshakeHash),
                new SSLSocketOutputRecord(handshakeHash), true);
        this.peerHost = peerHost;
D
duke 已提交
189

X
xuelei 已提交
190 191 192 193 194 195
        bind(new InetSocketAddress(localAddr, localPort));
        SocketAddress socketAddress =
               peerHost != null ? new InetSocketAddress(peerHost, peerPort) :
               new InetSocketAddress(InetAddress.getByName(null), peerPort);
        connect(socketAddress, 0);
    }
D
duke 已提交
196 197

    /**
X
xuelei 已提交
198 199 200
     * Constructs an SSL connection to a server at a specified
     * address, and TCP port, using the authentication context
     * provided.
D
duke 已提交
201
     *
X
xuelei 已提交
202 203
     * This endpoint acts as the client, and may rejoin an existing SSL
     * session if appropriate.
D
duke 已提交
204
     */
X
xuelei 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217
    SSLSocketImpl(SSLContextImpl sslContext,
            InetAddress peerAddr, int peerPort,
            InetAddress localAddr, int localPort) throws IOException {
        super();
        this.sslContext = sslContext;
        HandshakeHash handshakeHash = new HandshakeHash();
        this.conContext = new TransportContext(sslContext, this,
                new SSLSocketInputRecord(handshakeHash),
                new SSLSocketOutputRecord(handshakeHash), true);

        bind(new InetSocketAddress(localAddr, localPort));
        SocketAddress socketAddress = new InetSocketAddress(peerAddr, peerPort);
        connect(socketAddress, 0);
D
duke 已提交
218 219
    }

220 221 222 223 224 225
    /**
     * Creates a server mode {@link Socket} layered over an
     * existing connected socket, and is able to read data which has
     * already been consumed/removed from the {@link Socket}'s
     * underlying {@link InputStream}.
     */
X
xuelei 已提交
226
    SSLSocketImpl(SSLContextImpl sslContext, Socket sock,
227 228 229 230 231 232 233
            InputStream consumed, boolean autoClose) throws IOException {
        super(sock, consumed);
        // We always layer over a connected socket
        if (!sock.isConnected()) {
            throw new SocketException("Underlying socket is not connected");
        }

X
xuelei 已提交
234 235 236 237 238
        this.sslContext = sslContext;
        HandshakeHash handshakeHash = new HandshakeHash();
        this.conContext = new TransportContext(sslContext, this,
                new SSLSocketInputRecord(handshakeHash),
                new SSLSocketOutputRecord(handshakeHash), false);
239 240 241 242
        this.autoClose = autoClose;
        doneConnect();
    }

D
duke 已提交
243
    /**
X
xuelei 已提交
244 245 246 247 248 249 250 251 252 253 254 255 256
     * Layer SSL traffic over an existing connection, rather than
     * creating a new connection.
     *
     * The existing connection may be used only for SSL traffic (using this
     * SSLSocket) until the SSLSocket.close() call returns. However, if a
     * protocol error is detected, that existing connection is automatically
     * closed.
     * <p>
     * This particular constructor always uses the socket in the
     * role of an SSL client. It may be useful in cases which start
     * using SSL after some initial data transfers, for example in some
     * SSL tunneling applications or as part of some kinds of application
     * protocols which negotiate use of a SSL based security.
D
duke 已提交
257
     */
X
xuelei 已提交
258 259 260 261 262 263 264
    SSLSocketImpl(SSLContextImpl sslContext, Socket sock,
            String peerHost, int port, boolean autoClose) throws IOException {
        super(sock);
        // We always layer over a connected socket
        if (!sock.isConnected()) {
            throw new SocketException("Underlying socket is not connected");
        }
D
duke 已提交
265

X
xuelei 已提交
266 267 268 269 270 271 272 273
        this.sslContext = sslContext;
        HandshakeHash handshakeHash = new HandshakeHash();
        this.conContext = new TransportContext(sslContext, this,
                new SSLSocketInputRecord(handshakeHash),
                new SSLSocketOutputRecord(handshakeHash), true);
        this.peerHost = peerHost;
        this.autoClose = autoClose;
        doneConnect();
D
duke 已提交
274 275
    }

276
    @Override
X
xuelei 已提交
277 278
    public void connect(SocketAddress endpoint,
            int timeout) throws IOException {
D
duke 已提交
279

280
        if (isLayered()) {
D
duke 已提交
281 282 283 284 285
            throw new SocketException("Already connected");
        }

        if (!(endpoint instanceof InetSocketAddress)) {
            throw new SocketException(
X
xuelei 已提交
286
                    "Cannot handle non-Inet socket addresses.");
D
duke 已提交
287 288 289 290 291 292
        }

        super.connect(endpoint, timeout);
        doneConnect();
    }

X
xuelei 已提交
293 294 295 296
    @Override
    public String[] getSupportedCipherSuites() {
        return CipherSuite.namesOf(sslContext.getSupportedCipherSuites());
    }
297

X
xuelei 已提交
298
    @Override
299 300 301 302 303 304 305 306
    public String[] getEnabledCipherSuites() {
        socketLock.lock();
        try {
            return CipherSuite.namesOf(
                    conContext.sslConfig.enabledCipherSuites);
        } finally {
            socketLock.unlock();
        }
D
duke 已提交
307 308
    }

X
xuelei 已提交
309
    @Override
310 311 312 313 314 315 316 317
    public void setEnabledCipherSuites(String[] suites) {
        socketLock.lock();
        try {
            conContext.sslConfig.enabledCipherSuites =
                    CipherSuite.validValuesOf(suites);
        } finally {
            socketLock.unlock();
        }
D
duke 已提交
318 319
    }

X
xuelei 已提交
320 321 322 323
    @Override
    public String[] getSupportedProtocols() {
        return ProtocolVersion.toStringArray(
                sslContext.getSupportedProtocolVersions());
D
duke 已提交
324 325
    }

X
xuelei 已提交
326
    @Override
327 328 329 330 331 332 333 334
    public String[] getEnabledProtocols() {
        socketLock.lock();
        try {
            return ProtocolVersion.toStringArray(
                    conContext.sslConfig.enabledProtocols);
        } finally {
            socketLock.unlock();
        }
D
duke 已提交
335 336
    }

X
xuelei 已提交
337
    @Override
338
    public void setEnabledProtocols(String[] protocols) {
X
xuelei 已提交
339 340 341
        if (protocols == null) {
            throw new IllegalArgumentException("Protocols cannot be null");
        }
D
duke 已提交
342

343 344 345 346 347 348 349
        socketLock.lock();
        try {
            conContext.sslConfig.enabledProtocols =
                    ProtocolVersion.namesOf(protocols);
        } finally {
            socketLock.unlock();
        }
X
xuelei 已提交
350
    }
D
duke 已提交
351

X
xuelei 已提交
352
    @Override
353
    public SSLSession getSession() {
X
xuelei 已提交
354 355
        try {
            // start handshaking, if failed, the connection will be closed.
356
            ensureNegotiated(false);
X
xuelei 已提交
357 358 359 360
        } catch (IOException ioe) {
            if (SSLLogger.isOn && SSLLogger.isOn("handshake")) {
                SSLLogger.severe("handshake failed", ioe);
            }
D
duke 已提交
361

X
xuelei 已提交
362
            return new SSLSessionImpl();
X
xuelei 已提交
363
        }
D
duke 已提交
364

X
xuelei 已提交
365 366
        return conContext.conSession;
    }
D
duke 已提交
367

X
xuelei 已提交
368
    @Override
369 370 371 372 373 374 375 376
    public SSLSession getHandshakeSession() {
        socketLock.lock();
        try {
            return conContext.handshakeContext == null ?
                    null : conContext.handshakeContext.handshakeSession;
        } finally {
            socketLock.unlock();
        }
X
xuelei 已提交
377
    }
378

X
xuelei 已提交
379
    @Override
380
    public void addHandshakeCompletedListener(
X
xuelei 已提交
381 382 383
            HandshakeCompletedListener listener) {
        if (listener == null) {
            throw new IllegalArgumentException("listener is null");
384
        }
X
xuelei 已提交
385

386 387 388 389 390 391
        socketLock.lock();
        try {
            conContext.sslConfig.addHandshakeCompletedListener(listener);
        } finally {
            socketLock.unlock();
        }
X
xuelei 已提交
392
    }
X
xuelei 已提交
393

X
xuelei 已提交
394
    @Override
395
    public void removeHandshakeCompletedListener(
X
xuelei 已提交
396 397 398
            HandshakeCompletedListener listener) {
        if (listener == null) {
            throw new IllegalArgumentException("listener is null");
X
xuelei 已提交
399
        }
X
xuelei 已提交
400

401 402 403 404 405 406
        socketLock.lock();
        try {
            conContext.sslConfig.removeHandshakeCompletedListener(listener);
        } finally {
            socketLock.unlock();
        }
407 408
    }

X
xuelei 已提交
409
    @Override
410
    public void startHandshake() throws IOException {
411 412 413 414
        startHandshake(true);
    }

    private void startHandshake(boolean resumable) throws IOException {
415 416 417
        if (!isConnected) {
            throw new SocketException("Socket is not connected");
        }
D
duke 已提交
418

419 420 421 422 423
        if (conContext.isBroken || conContext.isInboundClosed() ||
                conContext.isOutboundClosed()) {
            throw new SocketException("Socket has been closed or broken");
        }

424 425
        handshakeLock.lock();
        try {
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
            // double check the context status
            if (conContext.isBroken || conContext.isInboundClosed() ||
                    conContext.isOutboundClosed()) {
                throw new SocketException("Socket has been closed or broken");
            }

            try {
                conContext.kickstart();

                // All initial handshaking goes through this operation until we
                // have a valid SSL connection.
                //
                // Handle handshake messages only, need no application data.
                if (!conContext.isNegotiated) {
                    readHandshakeRecord();
                }
442
            } catch (InterruptedIOException iioe) {
443 444 445 446 447 448
                if(resumable){
                    handleException(iioe);
                } else{
                    throw conContext.fatal(Alert.HANDSHAKE_FAILURE,
                            "Couldn't kickstart handshaking", iioe);
                }
449
            } catch (IOException ioe) {
450
                throw conContext.fatal(Alert.HANDSHAKE_FAILURE,
451 452 453
                    "Couldn't kickstart handshaking", ioe);
            } catch (Exception oe) {    // including RuntimeException
                handleException(oe);
X
xuelei 已提交
454
            }
455 456
        } finally {
            handshakeLock.unlock();
D
duke 已提交
457 458 459
        }
    }

X
xuelei 已提交
460
    @Override
461 462 463 464 465 466 467
    public void setUseClientMode(boolean mode) {
        socketLock.lock();
        try {
            conContext.setUseClientMode(mode);
        } finally {
            socketLock.unlock();
        }
D
duke 已提交
468 469
    }

470
    @Override
471 472 473 474 475 476 477
    public boolean getUseClientMode() {
        socketLock.lock();
        try {
            return conContext.sslConfig.isClientMode;
        } finally {
            socketLock.unlock();
        }
D
duke 已提交
478 479
    }

X
xuelei 已提交
480
    @Override
481 482 483 484 485 486 487 488 489
    public void setNeedClientAuth(boolean need) {
        socketLock.lock();
        try {
            conContext.sslConfig.clientAuthType =
                    (need ? ClientAuthType.CLIENT_AUTH_REQUIRED :
                            ClientAuthType.CLIENT_AUTH_NONE);
        } finally {
            socketLock.unlock();
        }
D
duke 已提交
490 491
    }

X
xuelei 已提交
492
    @Override
493 494 495 496
    public boolean getNeedClientAuth() {
        socketLock.lock();
        try {
            return (conContext.sslConfig.clientAuthType ==
X
xuelei 已提交
497
                        ClientAuthType.CLIENT_AUTH_REQUIRED);
498 499 500
        } finally {
            socketLock.unlock();
        }
D
duke 已提交
501 502
    }

503
    @Override
504 505 506 507 508 509 510 511 512
    public void setWantClientAuth(boolean want) {
        socketLock.lock();
        try {
            conContext.sslConfig.clientAuthType =
                    (want ? ClientAuthType.CLIENT_AUTH_REQUESTED :
                            ClientAuthType.CLIENT_AUTH_NONE);
        } finally {
            socketLock.unlock();
        }
D
duke 已提交
513 514
    }

X
xuelei 已提交
515
    @Override
516 517 518 519
    public boolean getWantClientAuth() {
        socketLock.lock();
        try {
            return (conContext.sslConfig.clientAuthType ==
X
xuelei 已提交
520
                        ClientAuthType.CLIENT_AUTH_REQUESTED);
521 522 523
        } finally {
            socketLock.unlock();
        }
D
duke 已提交
524 525
    }

X
xuelei 已提交
526
    @Override
527 528 529 530 531 532 533
    public void setEnableSessionCreation(boolean flag) {
        socketLock.lock();
        try {
            conContext.sslConfig.enableSessionCreation = flag;
        } finally {
            socketLock.unlock();
        }
D
duke 已提交
534 535
    }

X
xuelei 已提交
536
    @Override
537 538 539 540 541 542 543
    public boolean getEnableSessionCreation() {
        socketLock.lock();
        try {
            return conContext.sslConfig.enableSessionCreation;
        } finally {
            socketLock.unlock();
        }
D
duke 已提交
544 545
    }

X
xuelei 已提交
546
    @Override
547 548
    public boolean isClosed() {
        return tlsIsClosed;
549 550
    }

551 552
    // Please don't synchronized this method.  Otherwise, the read and close
    // locks may be deadlocked.
553
    @Override
554 555 556 557 558 559 560 561 562
    public void close() throws IOException {
        if (tlsIsClosed) {
            return;
        }

        if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
            SSLLogger.fine("duplex close of SSLSocket");
        }

563
        try {
564 565 566 567 568 569 570 571 572 573 574 575 576 577
            // shutdown output bound, which may have been closed previously.
            if (!isOutputShutdown()) {
                duplexCloseOutput();
            }

            // shutdown input bound, which may have been closed previously.
            if (!isInputShutdown()) {
                duplexCloseInput();
            }

            if (!isClosed()) {
                // close the connection directly
                closeSocket(false);
            }
578
        } catch (IOException ioe) {
X
xuelei 已提交
579 580
            // ignore the exception
            if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
581
                SSLLogger.warning("SSLSocket duplex close failed", ioe);
D
duke 已提交
582 583
            }
        } finally {
X
xuelei 已提交
584
            tlsIsClosed = true;
D
duke 已提交
585 586 587
        }
    }

588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
    /**
     * Duplex close, start from closing outbound.
     *
     * For TLS 1.2 [RFC 5246], unless some other fatal alert has been
     * transmitted, each party is required to send a close_notify alert
     * before closing the write side of the connection.  The other party
     * MUST respond with a close_notify alert of its own and close down
     * the connection immediately, discarding any pending writes.  It is
     * not required for the initiator of the close to wait for the responding
     * close_notify alert before closing the read side of the connection.
     *
     * For TLS 1.3, Each party MUST send a close_notify alert before
     * closing its write side of the connection, unless it has already sent
     * some error alert.  This does not have any effect on its read side of
     * the connection.  Both parties need not wait to receive a close_notify
     * alert before closing their read side of the connection, though doing
     * so would introduce the possibility of truncation.
     *
     * In order to support user initiated duplex-close for TLS 1.3 connections,
     * the user_canceled alert is used together with the close_notify alert.
     */
    private void duplexCloseOutput() throws IOException {
        boolean useUserCanceled = false;
        boolean hasCloseReceipt = false;
        if (conContext.isNegotiated) {
            if (!conContext.protocolVersion.useTLS13PlusSpec()) {
                hasCloseReceipt = true;
            } else {
                // Use a user_canceled alert for TLS 1.3 duplex close.
                useUserCanceled = true;
            }
        } else if (conContext.handshakeContext != null) {   // initial handshake
            // Use user_canceled alert regardless the protocol versions.
            useUserCanceled = true;

            // The protocol version may have been negotiated.
            ProtocolVersion pv = conContext.handshakeContext.negotiatedProtocol;
            if (pv == null || (!pv.useTLS13PlusSpec())) {
                hasCloseReceipt = true;
            }
        }

        // Need a lock here so that the user_canceled alert and the
        // close_notify alert can be delivered together.
        try {
            synchronized (conContext.outputRecord) {
                // send a user_canceled alert if needed.
                if (useUserCanceled) {
                    conContext.warning(Alert.USER_CANCELED);
                }

                // send a close_notify alert
                conContext.warning(Alert.CLOSE_NOTIFY);
            }
        } finally {
            if (!conContext.isOutboundClosed()) {
                conContext.outputRecord.close();
            }

            if ((autoClose || !isLayered()) && !super.isOutputShutdown()) {
                super.shutdownOutput();
            }
        }

        if (!isInputShutdown()) {
            bruteForceCloseInput(hasCloseReceipt);
        }
    }

    /**
     * Duplex close, start from closing inbound.
     *
     * This method should only be called when the outbound has been closed,
     * but the inbound is still open.
     */
    private void duplexCloseInput() throws IOException {
        boolean hasCloseReceipt = false;
        if (conContext.isNegotiated &&
                !conContext.protocolVersion.useTLS13PlusSpec()) {
            hasCloseReceipt = true;
        }   // No close receipt if handshake has no completed.

        bruteForceCloseInput(hasCloseReceipt);
    }

    /**
     * Brute force close the input bound.
     *
     * This method should only be called when the outbound has been closed,
     * but the inbound is still open.
     */
    private void bruteForceCloseInput(
            boolean hasCloseReceipt) throws IOException {
        if (hasCloseReceipt) {
            // It is not required for the initiator of the close to wait for
            // the responding close_notify alert before closing the read side
            // of the connection.  However, if the application protocol using
            // TLS provides that any data may be carried over the underlying
            // transport after the TLS connection is closed, the TLS
            // implementation MUST receive a "close_notify" alert before
            // indicating end-of-data to the application-layer.
            try {
                this.shutdown();
            } finally {
                if (!isInputShutdown()) {
                    shutdownInput(false);
                }
            }
        } else {
            if (!conContext.isInboundClosed()) {
698 699 700 701 702 703
                try (conContext.inputRecord) {
                    // Try the best to use up the input records and close the
                    // socket gracefully, without impact the performance too
                    // much.
                    appInput.deplete();
                }
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
            }

            if ((autoClose || !isLayered()) && !super.isInputShutdown()) {
                super.shutdownInput();
            }
        }
    }

    // Please don't synchronized this method.  Otherwise, the read and close
    // locks may be deadlocked.
    @Override
    public void shutdownInput() throws IOException {
        shutdownInput(true);
    }

    // It is not required to check the close_notify receipt unless an
    // application call shutdownInput() explicitly.
    private void shutdownInput(
            boolean checkCloseNotify) throws IOException {
        if (isInputShutdown()) {
            return;
        }

        if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
            SSLLogger.fine("close inbound of SSLSocket");
        }

        // Is it ready to close inbound?
        //
        // No need to throw exception if the initial handshake is not started.
        if (checkCloseNotify && !conContext.isInputCloseNotified &&
            (conContext.isNegotiated || conContext.handshakeContext != null)) {

737
            throw conContext.fatal(Alert.INTERNAL_ERROR,
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
                    "closing inbound before receiving peer's close_notify");
        }

        conContext.closeInbound();
        if ((autoClose || !isLayered()) && !super.isInputShutdown()) {
            super.shutdownInput();
        }
    }

    @Override
    public boolean isInputShutdown() {
        return conContext.isInboundClosed() &&
                ((autoClose || !isLayered()) ? super.isInputShutdown(): true);
    }

    // Please don't synchronized this method.  Otherwise, the read and close
    // locks may be deadlocked.
    @Override
    public void shutdownOutput() throws IOException {
        if (isOutputShutdown()) {
            return;
        }

        if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
            SSLLogger.fine("close outbound of SSLSocket");
        }
        conContext.closeOutbound();

        if ((autoClose || !isLayered()) && !super.isOutputShutdown()) {
            super.shutdownOutput();
        }
    }

    @Override
    public boolean isOutputShutdown() {
        return conContext.isOutboundClosed() &&
                ((autoClose || !isLayered()) ? super.isOutputShutdown(): true);
    }

X
xuelei 已提交
777
    @Override
778 779 780 781 782 783
    public InputStream getInputStream() throws IOException {
        socketLock.lock();
        try {
            if (isClosed()) {
                throw new SocketException("Socket is closed");
            }
D
duke 已提交
784

785 786 787
            if (!isConnected) {
                throw new SocketException("Socket is not connected");
            }
D
duke 已提交
788

789 790 791
            if (conContext.isInboundClosed() || isInputShutdown()) {
                throw new SocketException("Socket input is already shutdown");
            }
792

793 794 795 796
            return appInput;
        } finally {
            socketLock.unlock();
        }
D
duke 已提交
797 798
    }

799
    private void ensureNegotiated(boolean resumable) throws IOException {
800 801
        if (conContext.isNegotiated || conContext.isBroken ||
                conContext.isInboundClosed() || conContext.isOutboundClosed()) {
X
xuelei 已提交
802
            return;
D
duke 已提交
803 804
        }

805 806
        handshakeLock.lock();
        try {
807 808 809 810 811 812 813
            // double check the context status
            if (conContext.isNegotiated || conContext.isBroken ||
                    conContext.isInboundClosed() ||
                    conContext.isOutboundClosed()) {
                return;
            }

814
            startHandshake(resumable);
815 816
        } finally {
            handshakeLock.unlock();
817
        }
D
duke 已提交
818 819
    }

X
xuelei 已提交
820 821 822
    /**
     * InputStream for application data as returned by
     * SSLSocket.getInputStream().
D
duke 已提交
823
     */
X
xuelei 已提交
824 825 826
    private class AppInputStream extends InputStream {
        // One element array used to implement the single byte read() method
        private final byte[] oneByte = new byte[1];
827

X
xuelei 已提交
828 829
        // the temporary buffer used to read network
        private ByteBuffer buffer;
830

X
xuelei 已提交
831
        // Is application data available in the stream?
832
        private volatile boolean appDataIsAvailable;
D
duke 已提交
833

834 835 836
        // reading lock
        private final ReentrantLock readLock = new ReentrantLock();

837 838 839 840
        // closing status
        private volatile boolean isClosing;
        private volatile boolean hasDepleted;

X
xuelei 已提交
841 842 843
        AppInputStream() {
            this.appDataIsAvailable = false;
            this.buffer = ByteBuffer.allocate(4096);
844
        }
D
duke 已提交
845

X
xuelei 已提交
846 847 848
        /**
         * Return the minimum number of bytes that can be read
         * without blocking.
D
duke 已提交
849
         */
X
xuelei 已提交
850 851 852 853 854
        @Override
        public int available() throws IOException {
            // Currently not synchronized.
            if ((!appDataIsAvailable) || checkEOF()) {
                return 0;
D
duke 已提交
855
            }
856

X
xuelei 已提交
857
            return buffer.remaining();
D
duke 已提交
858 859
        }

X
xuelei 已提交
860 861
        /**
         * Read a single byte, returning -1 on non-fault EOF status.
D
duke 已提交
862
         */
X
xuelei 已提交
863
        @Override
864
        public int read() throws IOException {
X
xuelei 已提交
865 866 867 868
            int n = read(oneByte, 0, 1);
            if (n <= 0) {   // EOF
                return -1;
            }
869

X
xuelei 已提交
870
            return oneByte[0] & 0xFF;
D
duke 已提交
871 872
        }

X
xuelei 已提交
873 874 875 876 877 878 879 880 881 882 883 884 885
        /**
         * Reads up to {@code len} bytes of data from the input stream
         * into an array of bytes.
         *
         * An attempt is made to read as many as {@code len} bytes, but a
         * smaller number may be read. The number of bytes actually read
         * is returned as an integer.
         *
         * If the layer above needs more data, it asks for more, so we
         * are responsible only for blocking to fill at most one buffer,
         * and returning "-1" on non-fault EOF status.
         */
        @Override
886
        public int read(byte[] b, int off, int len) throws IOException {
X
xuelei 已提交
887 888 889 890 891 892 893 894
            if (b == null) {
                throw new NullPointerException("the target buffer is null");
            } else if (off < 0 || len < 0 || len > b.length - off) {
                throw new IndexOutOfBoundsException(
                        "buffer length: " + b.length + ", offset; " + off +
                        ", bytes to read:" + len);
            } else if (len == 0) {
                return 0;
D
duke 已提交
895 896
            }

X
xuelei 已提交
897 898
            if (checkEOF()) {
                return -1;
D
duke 已提交
899 900
            }

X
xuelei 已提交
901
            // start handshaking if the connection has not been negotiated.
902 903 904
            if (!conContext.isNegotiated && !conContext.isBroken &&
                    !conContext.isInboundClosed() &&
                    !conContext.isOutboundClosed()) {
905
                ensureNegotiated(true);
D
duke 已提交
906 907
            }

908 909 910 911
            // Check if the Socket is invalid (error or closed).
            if (!conContext.isNegotiated ||
                    conContext.isBroken || conContext.isInboundClosed()) {
                throw new SocketException("Connection or inbound has closed");
D
duke 已提交
912 913
            }

914 915 916 917 918 919 920 921 922 923 924 925 926
            // Check if the input stream has been depleted.
            //
            // Note that the "hasDepleted" rather than the isClosing
            // filed is checked here, in case the closing process is
            // still in progress.
            if (hasDepleted) {
                if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
                    SSLLogger.fine("The input stream has been depleted");
                }

                return -1;
            }

927 928 929 930
            // Read the available bytes at first.
            //
            // Note that the receiving and processing of post-handshake message
            // are also synchronized with the read lock.
931 932
            readLock.lock();
            try {
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
                // Double check if the Socket is invalid (error or closed).
                if (conContext.isBroken || conContext.isInboundClosed()) {
                    throw new SocketException(
                            "Connection or inbound has closed");
                }

                // Double check if the input stream has been depleted.
                if (hasDepleted) {
                    if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
                        SSLLogger.fine("The input stream is closing");
                    }

                    return -1;
                }

948 949 950 951 952 953 954 955 956 957 958 959
                int remains = available();
                if (remains > 0) {
                    int howmany = Math.min(remains, len);
                    buffer.get(b, off, howmany);

                    return howmany;
                }

                appDataIsAvailable = false;
                try {
                    ByteBuffer bb = readApplicationRecord(buffer);
                    if (bb == null) {   // EOF
X
xuelei 已提交
960
                        return -1;
961 962 963
                    } else {
                        // The buffer may be reallocated for bigger capacity.
                        buffer = bb;
X
xuelei 已提交
964
                    }
D
duke 已提交
965

966 967 968 969
                    bb.flip();
                    int volume = Math.min(len, bb.remaining());
                    buffer.get(b, off, volume);
                    appDataIsAvailable = true;
970

971 972 973 974
                    return volume;
                } catch (Exception e) {   // including RuntimeException
                    // shutdown and rethrow (wrapped) exception as appropriate
                    handleException(e);
D
duke 已提交
975

976 977
                    // dummy for compiler
                    return -1;
X
xuelei 已提交
978
                }
979
            } finally {
980 981 982 983 984 985 986 987 988 989 990
                // Check if the input stream is closing.
                //
                // If the deplete() did not hold the lock, clean up the
                // input stream here.
                try {
                    if (isClosing) {
                        readLockedDeplete();
                    }
                } finally {
                    readLock.unlock();
                }
X
xuelei 已提交
991
            }
992 993
        }

X
xuelei 已提交
994 995 996 997 998
        /**
         * Skip n bytes.
         *
         * This implementation is somewhat less efficient than possible, but
         * not badly so (redundant copy).  We reuse the read() code to keep
999
         * things simpler.
X
xuelei 已提交
1000 1001
         */
        @Override
1002
        public long skip(long n) throws IOException {
X
xuelei 已提交
1003 1004 1005
            // dummy array used to implement skip()
            byte[] skipArray = new byte[256];
            long skipped = 0;
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016

            readLock.lock();
            try {
                while (n > 0) {
                    int len = (int)Math.min(n, skipArray.length);
                    int r = read(skipArray, 0, len);
                    if (r <= 0) {
                        break;
                    }
                    n -= r;
                    skipped += r;
1017
                }
1018 1019
            } finally {
                readLock.unlock();
1020 1021
            }

X
xuelei 已提交
1022
            return skipped;
1023
        }
1024

X
xuelei 已提交
1025 1026 1027 1028 1029
        @Override
        public void close() throws IOException {
            if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
                SSLLogger.finest("Closing input stream");
            }
1030

1031
            try {
1032
                SSLSocketImpl.this.close();
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
            } catch (IOException ioe) {
                // ignore the exception
                if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
                    SSLLogger.warning("input stream close failed", ioe);
                }
            }
        }

        /**
         * Return whether we have reached end-of-file.
         *
         * If the socket is not connected, has been shutdown because of an error
         * or has been closed, throw an Exception.
         */
        private boolean checkEOF() throws IOException {
1048 1049 1050 1051 1052 1053 1054 1055 1056
            if (conContext.isBroken) {
                if (conContext.closeReason == null) {
                    return true;
                } else {
                    throw new SSLException(
                            "Connection has closed: " + conContext.closeReason,
                            conContext.closeReason);
                }
            } else if (conContext.isInboundClosed()) {
1057
                return true;
1058
            } else if (conContext.isInputCloseNotified) {
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
                if (conContext.closeReason == null) {
                    return true;
                } else {
                    throw new SSLException(
                        "Connection has closed: " + conContext.closeReason,
                        conContext.closeReason);
                }
            }

            return false;
1069
        }
1070 1071 1072 1073 1074

        /**
         * Try the best to use up the input records so as to close the
         * socket gracefully, without impact the performance too much.
         */
1075
        private void deplete() {
1076
            if (conContext.isInboundClosed() || isClosing) {
1077 1078 1079
                return;
            }

1080 1081 1082 1083 1084 1085
            isClosing = true;
            if (readLock.tryLock()) {
                try {
                    readLockedDeplete();
                } finally {
                    readLock.unlock();
1086
                }
1087 1088
            }
        }
1089

1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
        /**
         * Try to use up the input records.
         *
         * Please don't call this method unless the readLock is held by
         * the current thread.
         */
        private void readLockedDeplete() {
            // double check
            if (hasDepleted || conContext.isInboundClosed()) {
                return;
            }
1101

1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
            if (!(conContext.inputRecord instanceof SSLSocketInputRecord)) {
                return;
            }

            SSLSocketInputRecord socketInputRecord =
                    (SSLSocketInputRecord)conContext.inputRecord;
            try {
                socketInputRecord.deplete(
                    conContext.isNegotiated && (getSoTimeout() > 0));
            } catch (Exception ex) {
                if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
                    SSLLogger.warning(
                        "input stream close depletion failed", ex);
1115
                }
1116
            } finally {
1117
                hasDepleted = true;
1118 1119
            }
        }
1120 1121
    }

1122
    @Override
1123 1124 1125 1126 1127 1128
    public OutputStream getOutputStream() throws IOException {
        socketLock.lock();
        try {
            if (isClosed()) {
                throw new SocketException("Socket is closed");
            }
D
duke 已提交
1129

1130 1131 1132
            if (!isConnected) {
                throw new SocketException("Socket is not connected");
            }
D
duke 已提交
1133

1134 1135 1136
            if (conContext.isOutboundDone() || isOutputShutdown()) {
                throw new SocketException("Socket output is already shutdown");
            }
1137

1138 1139 1140 1141
            return appOutput;
        } finally {
            socketLock.unlock();
        }
D
duke 已提交
1142 1143
    }

X
xuelei 已提交
1144

D
duke 已提交
1145
    /**
X
xuelei 已提交
1146 1147
     * OutputStream for application data as returned by
     * SSLSocket.getOutputStream().
D
duke 已提交
1148
     */
X
xuelei 已提交
1149 1150 1151 1152 1153 1154 1155 1156
    private class AppOutputStream extends OutputStream {
        // One element array used to implement the write(byte) method
        private final byte[] oneByte = new byte[1];

        @Override
        public void write(int i) throws IOException {
            oneByte[0] = (byte)i;
            write(oneByte, 0, 1);
D
duke 已提交
1157 1158
        }

X
xuelei 已提交
1159
        @Override
1160
        public void write(byte[] b,
X
xuelei 已提交
1161 1162 1163 1164 1165 1166 1167 1168
                int off, int len) throws IOException {
            if (b == null) {
                throw new NullPointerException("the source buffer is null");
            } else if (off < 0 || len < 0 || len > b.length - off) {
                throw new IndexOutOfBoundsException(
                        "buffer length: " + b.length + ", offset; " + off +
                        ", bytes to read:" + len);
            } else if (len == 0) {
1169 1170 1171 1172 1173 1174 1175 1176
                //
                // Don't bother to really write empty records.  We went this
                // far to drive the handshake machinery, for correctness; not
                // writing empty records improves performance by cutting CPU
                // time and network resource usage.  However, some protocol
                // implementations are fragile and don't like to see empty
                // records, so this also increases robustness.
                //
X
xuelei 已提交
1177 1178 1179
                return;
            }

1180 1181 1182 1183
            // Start handshaking if the connection has not been negotiated.
            if (!conContext.isNegotiated && !conContext.isBroken &&
                    !conContext.isInboundClosed() &&
                    !conContext.isOutboundClosed()) {
1184
                ensureNegotiated(true);
X
xuelei 已提交
1185
            }
D
duke 已提交
1186

1187 1188 1189 1190 1191 1192 1193
            // Check if the Socket is invalid (error or closed).
            if (!conContext.isNegotiated ||
                    conContext.isBroken || conContext.isOutboundClosed()) {
                throw new SocketException("Connection or outbound has closed");
            }

            //
D
duke 已提交
1194

X
xuelei 已提交
1195
            // Delegate the writing to the underlying socket.
D
duke 已提交
1196
            try {
1197 1198 1199
                conContext.outputRecord.deliver(b, off, len);
            } catch (SSLHandshakeException she) {
                // may be record sequence number overflow
1200
                throw conContext.fatal(Alert.HANDSHAKE_FAILURE, she);
1201 1202 1203 1204 1205
            } catch (SSLException ssle) {
                throw conContext.fatal(Alert.UNEXPECTED_MESSAGE, ssle);
            }   // re-throw other IOException, which should be caused by
                // the underlying plain socket and could be handled by
                // applications (for example, re-try the connection).
1206 1207 1208 1209 1210 1211

            // Is the sequence number is nearly overflow, or has the key usage
            // limit been reached?
            if (conContext.outputRecord.seqNumIsHuge() ||
                    conContext.outputRecord.writeCipher.atKeyLimit()) {
                tryKeyUpdate();
D
duke 已提交
1212 1213
            }
        }
X
xuelei 已提交
1214 1215 1216 1217 1218 1219 1220

        @Override
        public void close() throws IOException {
            if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
                SSLLogger.finest("Closing output stream");
            }

1221
            try {
1222
                SSLSocketImpl.this.close();
1223 1224 1225 1226 1227 1228
            } catch (IOException ioe) {
                // ignore the exception
                if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
                    SSLLogger.warning("output stream close failed", ioe);
                }
            }
D
duke 已提交
1229 1230 1231
        }
    }

X
xuelei 已提交
1232
    @Override
1233 1234 1235 1236 1237 1238 1239
    public SSLParameters getSSLParameters() {
        socketLock.lock();
        try {
            return conContext.sslConfig.getSSLParameters();
        } finally {
            socketLock.unlock();
        }
X
xuelei 已提交
1240 1241
    }

1242
    @Override
1243 1244 1245 1246
    public void setSSLParameters(SSLParameters params) {
        socketLock.lock();
        try {
            conContext.sslConfig.setSSLParameters(params);
D
duke 已提交
1247

1248 1249 1250 1251 1252 1253
            if (conContext.sslConfig.maximumPacketSize != 0) {
                conContext.outputRecord.changePacketSize(
                        conContext.sslConfig.maximumPacketSize);
            }
        } finally {
            socketLock.unlock();
D
duke 已提交
1254 1255 1256
        }
    }

1257
    @Override
1258 1259 1260 1261 1262 1263 1264
    public String getApplicationProtocol() {
        socketLock.lock();
        try {
            return conContext.applicationProtocol;
        } finally {
            socketLock.unlock();
        }
D
duke 已提交
1265 1266
    }

1267
    @Override
1268 1269 1270 1271 1272 1273 1274 1275
    public String getHandshakeApplicationProtocol() {
        socketLock.lock();
        try {
            if (conContext.handshakeContext != null) {
                return conContext.handshakeContext.applicationProtocol;
            }
        } finally {
            socketLock.unlock();
D
duke 已提交
1276 1277
        }

X
xuelei 已提交
1278
        return null;
D
duke 已提交
1279 1280
    }

1281
    @Override
1282
    public void setHandshakeApplicationProtocolSelector(
X
xuelei 已提交
1283
            BiFunction<SSLSocket, List<String>, String> selector) {
1284 1285 1286 1287 1288 1289
        socketLock.lock();
        try {
            conContext.sslConfig.socketAPSelector = selector;
        } finally {
            socketLock.unlock();
        }
D
duke 已提交
1290 1291
    }

1292
    @Override
1293
    public BiFunction<SSLSocket, List<String>, String>
X
xuelei 已提交
1294
            getHandshakeApplicationProtocolSelector() {
1295 1296 1297 1298 1299 1300
        socketLock.lock();
        try {
            return conContext.sslConfig.socketAPSelector;
        } finally {
            socketLock.unlock();
        }
D
duke 已提交
1301 1302
    }

1303 1304 1305 1306 1307
    /**
     * Read the initial handshake records.
     */
    private int readHandshakeRecord() throws IOException {
        while (!conContext.isInboundClosed()) {
X
xuelei 已提交
1308 1309 1310 1311 1312 1313 1314 1315
            try {
                Plaintext plainText = decode(null);
                if ((plainText.contentType == ContentType.HANDSHAKE.id) &&
                        conContext.isNegotiated) {
                    return 0;
                }
            } catch (SSLException ssle) {
                throw ssle;
1316 1317 1318
            } catch (InterruptedIOException iioe) {
                // don't change exception in case of timeouts or interrupts
                throw iioe;
X
xuelei 已提交
1319
            } catch (IOException ioe) {
1320
                throw new SSLException("readHandshakeRecord", ioe);
X
xuelei 已提交
1321
            }
X
xuelei 已提交
1322
        }
1323

X
xuelei 已提交
1324 1325
        return -1;
    }
D
duke 已提交
1326

1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
    /**
     * Read application data record. Used by AppInputStream only, but defined
     * here so as to use the socket level synchronization.
     *
     * Note that the connection guarantees that handshake, alert, and change
     * cipher spec data streams are handled as they arrive, so we never see
     * them here.
     *
     * Note: Please be careful about the synchronization, and don't use this
     * method other than in the AppInputStream class!
     */
    private ByteBuffer readApplicationRecord(
            ByteBuffer buffer) throws IOException {
        while (!conContext.isInboundClosed()) {
D
duke 已提交
1341
            /*
X
xuelei 已提交
1342 1343 1344 1345 1346
             * clean the buffer and check if it is too small, e.g. because
             * the AppInputStream did not have the chance to see the
             * current packet length but rather something like that of the
             * handshake before. In that case we return 0 at this point to
             * give the caller the chance to adjust the buffer.
D
duke 已提交
1347
             */
X
xuelei 已提交
1348 1349 1350 1351
            buffer.clear();
            int inLen = conContext.inputRecord.bytesInCompletePacket();
            if (inLen < 0) {    // EOF
                handleEOF(null);
1352

X
xuelei 已提交
1353
                // if no exception thrown
1354
                return null;
D
duke 已提交
1355 1356
            }

1357 1358 1359 1360 1361 1362 1363 1364
            // Is this packet bigger than SSL/TLS normally allows?
            if (inLen > SSLRecord.maxLargeRecordSize) {
                throw new SSLProtocolException(
                        "Illegal packet size: " + inLen);
            }

            if (inLen > buffer.remaining()) {
                buffer = ByteBuffer.allocate(inLen);
X
xuelei 已提交
1365
            }
D
duke 已提交
1366

X
xuelei 已提交
1367
            try {
1368
                Plaintext plainText;
1369 1370
                socketLock.lock();
                try {
1371
                    plainText = decode(buffer);
1372 1373
                } finally {
                    socketLock.unlock();
1374 1375 1376 1377
                }
                if (plainText.contentType == ContentType.APPLICATION_DATA.id &&
                        buffer.position() > 0) {
                    return buffer;
X
xuelei 已提交
1378 1379 1380
                }
            } catch (SSLException ssle) {
                throw ssle;
1381 1382 1383
            } catch (InterruptedIOException iioe) {
                // don't change exception in case of timeouts or interrupts
                throw iioe;
X
xuelei 已提交
1384 1385
            } catch (IOException ioe) {
                if (!(ioe instanceof SSLException)) {
1386
                    throw new SSLException("readApplicationRecord", ioe);
X
xuelei 已提交
1387 1388 1389
                } else {
                    throw ioe;
                }
D
duke 已提交
1390 1391 1392
            }
        }

X
xuelei 已提交
1393 1394 1395
        //
        // couldn't read, due to some kind of error
        //
1396
        return null;
D
duke 已提交
1397 1398
    }

X
xuelei 已提交
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
    private Plaintext decode(ByteBuffer destination) throws IOException {
        Plaintext plainText;
        try {
            if (destination == null) {
                plainText = SSLTransport.decode(conContext,
                        null, 0, 0, null, 0, 0);
            } else {
                plainText = SSLTransport.decode(conContext,
                        null, 0, 0, new ByteBuffer[]{destination}, 0, 1);
            }
        } catch (EOFException eofe) {
            // EOFException is special as it is related to close_notify.
            plainText = handleEOF(eofe);
        }
D
duke 已提交
1413

X
xuelei 已提交
1414 1415
        // Is the sequence number is nearly overflow?
        if (plainText != Plaintext.PLAINTEXT_NULL &&
1416 1417
                (conContext.inputRecord.seqNumIsHuge() ||
                conContext.inputRecord.readCipher.atKeyLimit())) {
X
xuelei 已提交
1418 1419 1420 1421
            tryKeyUpdate();
        }

        return plainText;
D
duke 已提交
1422 1423 1424
    }

    /**
1425
     * Try key update for sequence number wrap or key usage limit.
D
duke 已提交
1426
     *
X
xuelei 已提交
1427
     * Note that in order to maintain the handshake status properly, we check
1428 1429 1430 1431
     * the sequence number and key usage limit after the last record
     * reading/writing process.
     *
     * As we request renegotiation or close the connection for wrapped sequence
X
xuelei 已提交
1432 1433 1434 1435 1436
     * number when there is enough sequence number space left to handle a few
     * more records, so the sequence number of the last record cannot be
     * wrapped.
     */
    private void tryKeyUpdate() throws IOException {
1437 1438
        // Don't bother to kickstart if handshaking is in progress, or if the
        // connection is not duplex-open.
X
xuelei 已提交
1439
        if ((conContext.handshakeContext == null) &&
1440 1441 1442
                !conContext.isOutboundClosed() &&
                !conContext.isInboundClosed() &&
                !conContext.isBroken) {
X
xuelei 已提交
1443
            if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
1444
                SSLLogger.finest("trigger key update");
X
xuelei 已提交
1445
            }
1446
            startHandshake();
X
xuelei 已提交
1447
        }
D
duke 已提交
1448 1449 1450
    }

    /**
X
xuelei 已提交
1451
     * Initialize the handshaker and socket streams.
D
duke 已提交
1452
     *
X
xuelei 已提交
1453
     * Called by connect, the layered constructor, and SSLServerSocket.
D
duke 已提交
1454
     */
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
    void doneConnect() throws IOException {
        socketLock.lock();
        try {
            // In server mode, it is not necessary to set host and serverNames.
            // Otherwise, would require a reverse DNS lookup to get
            // the hostname.
            if (peerHost == null || peerHost.isEmpty()) {
                boolean useNameService =
                        trustNameService && conContext.sslConfig.isClientMode;
                useImplicitHost(useNameService);
            } else {
                conContext.sslConfig.serverNames =
                        Utilities.addToSNIServerNameList(
                                conContext.sslConfig.serverNames, peerHost);
            }
D
duke 已提交
1470

1471 1472
            InputStream sockInput = super.getInputStream();
            conContext.inputRecord.setReceiverStream(sockInput);
X
xuelei 已提交
1473

1474 1475 1476
            OutputStream sockOutput = super.getOutputStream();
            conContext.inputRecord.setDeliverStream(sockOutput);
            conContext.outputRecord.setDeliverStream(sockOutput);
X
xuelei 已提交
1477

1478 1479 1480 1481
            this.isConnected = true;
        } finally {
            socketLock.unlock();
        }
D
duke 已提交
1482 1483
    }

X
xuelei 已提交
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
    private void useImplicitHost(boolean useNameService) {
        // Note: If the local name service is not trustworthy, reverse
        // host name resolution should not be performed for endpoint
        // identification.  Use the application original specified
        // hostname or IP address instead.

        // Get the original hostname via jdk.internal.misc.SharedSecrets
        InetAddress inetAddress = getInetAddress();
        if (inetAddress == null) {      // not connected
            return;
D
duke 已提交
1494
        }
1495

X
xuelei 已提交
1496 1497 1498
        JavaNetInetAddressAccess jna =
                SharedSecrets.getJavaNetInetAddressAccess();
        String originalHostname = jna.getOriginalHostName(inetAddress);
1499
        if (originalHostname != null && !originalHostname.isEmpty()) {
D
duke 已提交
1500

X
xuelei 已提交
1501 1502 1503 1504 1505 1506 1507 1508 1509
            this.peerHost = originalHostname;
            if (conContext.sslConfig.serverNames.isEmpty() &&
                    !conContext.sslConfig.noSniExtension) {
                conContext.sslConfig.serverNames =
                        Utilities.addToSNIServerNameList(
                                conContext.sslConfig.serverNames, peerHost);
            }

            return;
D
duke 已提交
1510
        }
X
xuelei 已提交
1511 1512 1513 1514 1515 1516 1517 1518

        // No explicitly specified hostname, no server name indication.
        if (!useNameService) {
            // The local name service is not trustworthy, use IP address.
            this.peerHost = inetAddress.getHostAddress();
        } else {
            // Use the underlying reverse host name resolution service.
            this.peerHost = getInetAddress().getHostName();
D
duke 已提交
1519 1520 1521
        }
    }

X
xuelei 已提交
1522 1523 1524 1525 1526
    // ONLY used by HttpsClient to setup the URI specified hostname
    //
    // Please NOTE that this method MUST be called before calling to
    // SSLSocket.setSSLParameters(). Otherwise, the {@code host} parameter
    // may override SNIHostName in the customized server name indication.
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
    public void setHost(String host) {
        socketLock.lock();
        try {
            this.peerHost = host;
            this.conContext.sslConfig.serverNames =
                    Utilities.addToSNIServerNameList(
                            conContext.sslConfig.serverNames, host);
        } finally {
            socketLock.unlock();
        }
X
xuelei 已提交
1537
    }
D
duke 已提交
1538 1539

    /**
X
xuelei 已提交
1540 1541 1542 1543 1544 1545 1546
     * Handle an exception.
     *
     * This method is called by top level exception handlers (in read(),
     * write()) to make sure we always shutdown the connection correctly
     * and do not pass runtime exception to the application.
     *
     * This method never returns normally, it always throws an IOException.
D
duke 已提交
1547
     */
X
xuelei 已提交
1548 1549 1550
    private void handleException(Exception cause) throws IOException {
        if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
            SSLLogger.warning("handling exception", cause);
1551
        }
1552

X
xuelei 已提交
1553 1554 1555
        // Don't close the Socket in case of timeouts or interrupts.
        if (cause instanceof InterruptedIOException) {
            throw (IOException)cause;
1556 1557
        }

X
xuelei 已提交
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
        // need to perform error shutdown
        boolean isSSLException = (cause instanceof SSLException);
        Alert alert;
        if (isSSLException) {
            if (cause instanceof SSLHandshakeException) {
                alert = Alert.HANDSHAKE_FAILURE;
            } else {
                alert = Alert.UNEXPECTED_MESSAGE;
            }
        } else {
            if (cause instanceof IOException) {
                alert = Alert.UNEXPECTED_MESSAGE;
            } else {
                // RuntimeException
                alert = Alert.INTERNAL_ERROR;
            }
1574
        }
1575 1576

        throw conContext.fatal(alert, cause);
X
xuelei 已提交
1577
    }
1578

X
xuelei 已提交
1579 1580 1581 1582 1583 1584
    private Plaintext handleEOF(EOFException eofe) throws IOException {
        if (requireCloseNotify || conContext.handshakeContext != null) {
            SSLException ssle;
            if (conContext.handshakeContext != null) {
                ssle = new SSLHandshakeException(
                        "Remote host terminated the handshake");
1585
            } else {
X
xuelei 已提交
1586 1587 1588 1589 1590 1591
                ssle = new SSLProtocolException(
                        "Remote host terminated the connection");
            }

            if (eofe != null) {
                ssle.initCause(eofe);
1592
            }
X
xuelei 已提交
1593 1594 1595 1596
            throw ssle;
        } else {
            // treat as if we had received a close_notify
            conContext.isInputCloseNotified = true;
1597
            shutdownInput();
X
xuelei 已提交
1598 1599

            return Plaintext.PLAINTEXT_NULL;
X
xuelei 已提交
1600
        }
D
duke 已提交
1601 1602
    }

1603 1604

    @Override
X
xuelei 已提交
1605 1606
    public String getPeerHost() {
        return peerHost;
1607 1608
    }

1609
    @Override
X
xuelei 已提交
1610 1611
    public int getPeerPort() {
        return getPort();
1612 1613 1614
    }

    @Override
X
xuelei 已提交
1615 1616
    public boolean useDelegatedTask() {
        return false;
1617 1618
    }

X
xuelei 已提交
1619 1620 1621 1622 1623 1624
    @Override
    public void shutdown() throws IOException {
        if (!isClosed()) {
            if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
                SSLLogger.fine("close the underlying socket");
            }
D
duke 已提交
1625

X
xuelei 已提交
1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
            try {
                if (conContext.isInputCloseNotified) {
                    // Close the connection, no wait for more peer response.
                    closeSocket(false);
                } else {
                    // Close the connection, may wait for peer close_notify.
                    closeSocket(true);
                }
            } finally {
                tlsIsClosed = true;
D
duke 已提交
1636 1637 1638
            }
        }
    }
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685

    private void closeSocket(boolean selfInitiated) throws IOException {
        if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
            SSLLogger.fine("close the SSL connection " +
                (selfInitiated ? "(initiative)" : "(passive)"));
        }

        if (autoClose || !isLayered()) {
            super.close();
        } else if (selfInitiated) {
            if (!conContext.isInboundClosed() && !isInputShutdown()) {
                // wait for close_notify alert to clear input stream.
                waitForClose();
            }
        }
    }

   /**
    * Wait for close_notify alert for a graceful closure.
    *
    * [RFC 5246] If the application protocol using TLS provides that any
    * data may be carried over the underlying transport after the TLS
    * connection is closed, the TLS implementation must receive the responding
    * close_notify alert before indicating to the application layer that
    * the TLS connection has ended.  If the application protocol will not
    * transfer any additional data, but will only close the underlying
    * transport connection, then the implementation MAY choose to close the
    * transport without waiting for the responding close_notify.
    */
    private void waitForClose() throws IOException {
        if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
            SSLLogger.fine("wait for close_notify or alert");
        }

        while (!conContext.isInboundClosed()) {
            try {
                Plaintext plainText = decode(null);
                // discard and continue
                if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
                    SSLLogger.finest(
                        "discard plaintext while waiting for close", plainText);
                }
            } catch (Exception e) {   // including RuntimeException
                handleException(e);
            }
        }
    }
D
duke 已提交
1686
}