1 /*
   2  * Copyright (c) 1996, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package sun.security.ssl;
  27 
  28 import java.io.EOFException;
  29 import java.io.IOException;
  30 import java.io.InputStream;
  31 import java.io.InterruptedIOException;
  32 import java.io.OutputStream;
  33 import java.net.InetAddress;
  34 import java.net.InetSocketAddress;
  35 import java.net.Socket;
  36 import java.net.SocketAddress;
  37 import java.net.SocketException;
  38 import java.net.UnknownHostException;
  39 import java.nio.ByteBuffer;
  40 import java.util.List;
  41 import java.util.concurrent.TimeUnit;
  42 import java.util.concurrent.locks.ReentrantLock;
  43 import java.util.function.BiFunction;
  44 import javax.net.ssl.HandshakeCompletedListener;
  45 import javax.net.ssl.SSLException;
  46 import javax.net.ssl.SSLHandshakeException;
  47 import javax.net.ssl.SSLParameters;
  48 import javax.net.ssl.SSLProtocolException;
  49 import javax.net.ssl.SSLServerSocket;
  50 import javax.net.ssl.SSLSession;
  51 import javax.net.ssl.SSLSocket;
  52 import jdk.internal.access.JavaNetInetAddressAccess;
  53 import jdk.internal.access.SharedSecrets;
  54 
  55 /**
  56  * Implementation of an SSL socket.
  57  * <P>
  58  * This is a normal connection type socket, implementing SSL over some lower
  59  * level socket, such as TCP.  Because it is layered over some lower level
  60  * socket, it MUST override all default socket methods.
  61  * <P>
  62  * This API offers a non-traditional option for establishing SSL
  63  * connections.  You may first establish the connection directly, then pass
  64  * that connection to the SSL socket constructor with a flag saying which
  65  * role should be taken in the handshake protocol.  (The two ends of the
  66  * connection must not choose the same role!)  This allows setup of SSL
  67  * proxying or tunneling, and also allows the kind of "role reversal"
  68  * that is required for most FTP data transfers.
  69  *
  70  * @see javax.net.ssl.SSLSocket
  71  * @see SSLServerSocket
  72  *
  73  * @author David Brownell
  74  */
  75 public final class SSLSocketImpl
  76         extends BaseSSLSocketImpl implements SSLTransport {
  77 
  78     final SSLContextImpl            sslContext;
  79     final TransportContext          conContext;
  80 
  81     private final AppInputStream    appInput = new AppInputStream();
  82     private final AppOutputStream   appOutput = new AppOutputStream();
  83 
  84     private String                  peerHost;
  85     private boolean                 autoClose;
  86     private boolean                 isConnected = false;
  87     private volatile boolean        tlsIsClosed = false;
  88 
  89     private final ReentrantLock     socketLock = new ReentrantLock();
  90     private final ReentrantLock     handshakeLock = new ReentrantLock();
  91 
  92     /*
  93      * Is the local name service trustworthy?
  94      *
  95      * If the local name service is not trustworthy, reverse host name
  96      * resolution should not be performed for endpoint identification.
  97      */
  98     private static final boolean trustNameService =
  99             Utilities.getBooleanProperty("jdk.tls.trustNameService", false);
 100 
 101     /**
 102      * Package-private constructor used to instantiate an unconnected
 103      * socket.
 104      *
 105      * This instance is meant to set handshake state to use "client mode".
 106      */
 107     SSLSocketImpl(SSLContextImpl sslContext) {
 108         super();
 109         this.sslContext = sslContext;
 110         HandshakeHash handshakeHash = new HandshakeHash();
 111         this.conContext = new TransportContext(sslContext, this,
 112                 new SSLSocketInputRecord(handshakeHash),
 113                 new SSLSocketOutputRecord(handshakeHash), true);
 114     }
 115 
 116     /**
 117      * Package-private constructor used to instantiate a server socket.
 118      *
 119      * This instance is meant to set handshake state to use "server mode".
 120      */
 121     SSLSocketImpl(SSLContextImpl sslContext, SSLConfiguration sslConfig) {
 122         super();
 123         this.sslContext = sslContext;
 124         HandshakeHash handshakeHash = new HandshakeHash();
 125         this.conContext = new TransportContext(sslContext, this, sslConfig,
 126                 new SSLSocketInputRecord(handshakeHash),
 127                 new SSLSocketOutputRecord(handshakeHash));
 128     }
 129 
 130     /**
 131      * Constructs an SSL connection to a named host at a specified
 132      * port, using the authentication context provided.
 133      *
 134      * This endpoint acts as the client, and may rejoin an existing SSL session
 135      * if appropriate.
 136      */
 137     SSLSocketImpl(SSLContextImpl sslContext, String peerHost,
 138             int peerPort) throws IOException, UnknownHostException {
 139         super();
 140         this.sslContext = sslContext;
 141         HandshakeHash handshakeHash = new HandshakeHash();
 142         this.conContext = new TransportContext(sslContext, this,
 143                 new SSLSocketInputRecord(handshakeHash),
 144                 new SSLSocketOutputRecord(handshakeHash), true);
 145         this.peerHost = peerHost;
 146         SocketAddress socketAddress =
 147                peerHost != null ? new InetSocketAddress(peerHost, peerPort) :
 148                new InetSocketAddress(InetAddress.getByName(null), peerPort);
 149         connect(socketAddress, 0);
 150     }
 151 
 152     /**
 153      * Constructs an SSL connection to a server at a specified
 154      * address, and TCP port, using the authentication context
 155      * provided.
 156      *
 157      * This endpoint acts as the client, and may rejoin an existing SSL
 158      * session if appropriate.
 159      */
 160     SSLSocketImpl(SSLContextImpl sslContext,
 161             InetAddress address, int peerPort) throws IOException {
 162         super();
 163         this.sslContext = sslContext;
 164         HandshakeHash handshakeHash = new HandshakeHash();
 165         this.conContext = new TransportContext(sslContext, this,
 166                 new SSLSocketInputRecord(handshakeHash),
 167                 new SSLSocketOutputRecord(handshakeHash), true);
 168 
 169         SocketAddress socketAddress = new InetSocketAddress(address, peerPort);
 170         connect(socketAddress, 0);
 171     }
 172 
 173     /**
 174      * Constructs an SSL connection to a named host at a specified
 175      * port, using the authentication context provided.
 176      *
 177      * This endpoint acts as the client, and may rejoin an existing SSL
 178      * session if appropriate.
 179      */
 180     SSLSocketImpl(SSLContextImpl sslContext,
 181             String peerHost, int peerPort, InetAddress localAddr,
 182             int localPort) throws IOException, UnknownHostException {
 183         super();
 184         this.sslContext = sslContext;
 185         HandshakeHash handshakeHash = new HandshakeHash();
 186         this.conContext = new TransportContext(sslContext, this,
 187                 new SSLSocketInputRecord(handshakeHash),
 188                 new SSLSocketOutputRecord(handshakeHash), true);
 189         this.peerHost = peerHost;
 190 
 191         bind(new InetSocketAddress(localAddr, localPort));
 192         SocketAddress socketAddress =
 193                peerHost != null ? new InetSocketAddress(peerHost, peerPort) :
 194                new InetSocketAddress(InetAddress.getByName(null), peerPort);
 195         connect(socketAddress, 0);
 196     }
 197 
 198     /**
 199      * Constructs an SSL connection to a server at a specified
 200      * address, and TCP port, using the authentication context
 201      * provided.
 202      *
 203      * This endpoint acts as the client, and may rejoin an existing SSL
 204      * session if appropriate.
 205      */
 206     SSLSocketImpl(SSLContextImpl sslContext,
 207             InetAddress peerAddr, int peerPort,
 208             InetAddress localAddr, int localPort) throws IOException {
 209         super();
 210         this.sslContext = sslContext;
 211         HandshakeHash handshakeHash = new HandshakeHash();
 212         this.conContext = new TransportContext(sslContext, this,
 213                 new SSLSocketInputRecord(handshakeHash),
 214                 new SSLSocketOutputRecord(handshakeHash), true);
 215 
 216         bind(new InetSocketAddress(localAddr, localPort));
 217         SocketAddress socketAddress = new InetSocketAddress(peerAddr, peerPort);
 218         connect(socketAddress, 0);
 219     }
 220 
 221     /**
 222      * Creates a server mode {@link Socket} layered over an
 223      * existing connected socket, and is able to read data which has
 224      * already been consumed/removed from the {@link Socket}'s
 225      * underlying {@link InputStream}.
 226      */
 227     SSLSocketImpl(SSLContextImpl sslContext, Socket sock,
 228             InputStream consumed, boolean autoClose) throws IOException {
 229         super(sock, consumed);
 230         // We always layer over a connected socket
 231         if (!sock.isConnected()) {
 232             throw new SocketException("Underlying socket is not connected");
 233         }
 234 
 235         this.sslContext = sslContext;
 236         HandshakeHash handshakeHash = new HandshakeHash();
 237         this.conContext = new TransportContext(sslContext, this,
 238                 new SSLSocketInputRecord(handshakeHash),
 239                 new SSLSocketOutputRecord(handshakeHash), false);
 240         this.autoClose = autoClose;
 241         doneConnect();
 242     }
 243 
 244     /**
 245      * Layer SSL traffic over an existing connection, rather than
 246      * creating a new connection.
 247      *
 248      * The existing connection may be used only for SSL traffic (using this
 249      * SSLSocket) until the SSLSocket.close() call returns. However, if a
 250      * protocol error is detected, that existing connection is automatically
 251      * closed.
 252      * <p>
 253      * This particular constructor always uses the socket in the
 254      * role of an SSL client. It may be useful in cases which start
 255      * using SSL after some initial data transfers, for example in some
 256      * SSL tunneling applications or as part of some kinds of application
 257      * protocols which negotiate use of a SSL based security.
 258      */
 259     SSLSocketImpl(SSLContextImpl sslContext, Socket sock,
 260             String peerHost, int port, boolean autoClose) throws IOException {
 261         super(sock);
 262         // We always layer over a connected socket
 263         if (!sock.isConnected()) {
 264             throw new SocketException("Underlying socket is not connected");
 265         }
 266 
 267         this.sslContext = sslContext;
 268         HandshakeHash handshakeHash = new HandshakeHash();
 269         this.conContext = new TransportContext(sslContext, this,
 270                 new SSLSocketInputRecord(handshakeHash),
 271                 new SSLSocketOutputRecord(handshakeHash), true);
 272         this.peerHost = peerHost;
 273         this.autoClose = autoClose;
 274         doneConnect();
 275     }
 276 
 277     @Override
 278     public void connect(SocketAddress endpoint,
 279             int timeout) throws IOException {
 280 
 281         if (isLayered()) {
 282             throw new SocketException("Already connected");
 283         }
 284 
 285         if (!(endpoint instanceof InetSocketAddress)) {
 286             throw new SocketException(
 287                     "Cannot handle non-Inet socket addresses.");
 288         }
 289 
 290         super.connect(endpoint, timeout);
 291         doneConnect();
 292     }
 293 
 294     @Override
 295     public String[] getSupportedCipherSuites() {
 296         return CipherSuite.namesOf(sslContext.getSupportedCipherSuites());
 297     }
 298 
 299     @Override
 300     public String[] getEnabledCipherSuites() {
 301         socketLock.lock();
 302         try {
 303             return CipherSuite.namesOf(
 304                     conContext.sslConfig.enabledCipherSuites);
 305         } finally {
 306             socketLock.unlock();
 307         }
 308     }
 309 
 310     @Override
 311     public void setEnabledCipherSuites(String[] suites) {
 312         socketLock.lock();
 313         try {
 314             conContext.sslConfig.enabledCipherSuites =
 315                     CipherSuite.validValuesOf(suites);
 316         } finally {
 317             socketLock.unlock();
 318         }
 319     }
 320 
 321     @Override
 322     public String[] getSupportedProtocols() {
 323         return ProtocolVersion.toStringArray(
 324                 sslContext.getSupportedProtocolVersions());
 325     }
 326 
 327     @Override
 328     public String[] getEnabledProtocols() {
 329         socketLock.lock();
 330         try {
 331             return ProtocolVersion.toStringArray(
 332                     conContext.sslConfig.enabledProtocols);
 333         } finally {
 334             socketLock.unlock();
 335         }
 336     }
 337 
 338     @Override
 339     public void setEnabledProtocols(String[] protocols) {
 340         if (protocols == null) {
 341             throw new IllegalArgumentException("Protocols cannot be null");
 342         }
 343 
 344         socketLock.lock();
 345         try {
 346             conContext.sslConfig.enabledProtocols =
 347                     ProtocolVersion.namesOf(protocols);
 348         } finally {
 349             socketLock.unlock();
 350         }
 351     }
 352 
 353     @Override
 354     public SSLSession getSession() {
 355         try {
 356             // start handshaking, if failed, the connection will be closed.
 357             ensureNegotiated();
 358         } catch (IOException ioe) {
 359             if (SSLLogger.isOn && SSLLogger.isOn("handshake")) {
 360                 SSLLogger.severe("handshake failed", ioe);
 361             }
 362 
 363             return SSLSessionImpl.nullSession;
 364         }
 365 
 366         return conContext.conSession;
 367     }
 368 
 369     @Override
 370     public SSLSession getHandshakeSession() {
 371         socketLock.lock();
 372         try {
 373             return conContext.handshakeContext == null ?
 374                     null : conContext.handshakeContext.handshakeSession;
 375         } finally {
 376             socketLock.unlock();
 377         }
 378     }
 379 
 380     @Override
 381     public void addHandshakeCompletedListener(
 382             HandshakeCompletedListener listener) {
 383         if (listener == null) {
 384             throw new IllegalArgumentException("listener is null");
 385         }
 386 
 387         socketLock.lock();
 388         try {
 389             conContext.sslConfig.addHandshakeCompletedListener(listener);
 390         } finally {
 391             socketLock.unlock();
 392         }
 393     }
 394 
 395     @Override
 396     public void removeHandshakeCompletedListener(
 397             HandshakeCompletedListener listener) {
 398         if (listener == null) {
 399             throw new IllegalArgumentException("listener is null");
 400         }
 401 
 402         socketLock.lock();
 403         try {
 404             conContext.sslConfig.removeHandshakeCompletedListener(listener);
 405         } finally {
 406             socketLock.unlock();
 407         }
 408     }
 409 
 410     @Override
 411     public void startHandshake() throws IOException {
 412         if (!isConnected) {
 413             throw new SocketException("Socket is not connected");
 414         }
 415 
 416         if (conContext.isBroken || conContext.isInboundClosed() ||
 417                 conContext.isOutboundClosed()) {
 418             throw new SocketException("Socket has been closed or broken");
 419         }
 420 
 421         handshakeLock.lock();
 422         try {
 423             // double check the context status
 424             if (conContext.isBroken || conContext.isInboundClosed() ||
 425                     conContext.isOutboundClosed()) {
 426                 throw new SocketException("Socket has been closed or broken");
 427             }
 428 
 429             try {
 430                 conContext.kickstart();
 431 
 432                 // All initial handshaking goes through this operation until we
 433                 // have a valid SSL connection.
 434                 //
 435                 // Handle handshake messages only, need no application data.
 436                 if (!conContext.isNegotiated) {
 437                     readHandshakeRecord();
 438                 }
 439             } catch (IOException ioe) {
 440                 throw conContext.fatal(Alert.HANDSHAKE_FAILURE,
 441                     "Couldn't kickstart handshaking", ioe);
 442             } catch (Exception oe) {    // including RuntimeException
 443                 handleException(oe);
 444             }
 445         } finally {
 446             handshakeLock.unlock();
 447         }
 448     }
 449 
 450     @Override
 451     public void setUseClientMode(boolean mode) {
 452         socketLock.lock();
 453         try {
 454             conContext.setUseClientMode(mode);
 455         } finally {
 456             socketLock.unlock();
 457         }
 458     }
 459 
 460     @Override
 461     public boolean getUseClientMode() {
 462         socketLock.lock();
 463         try {
 464             return conContext.sslConfig.isClientMode;
 465         } finally {
 466             socketLock.unlock();
 467         }
 468     }
 469 
 470     @Override
 471     public void setNeedClientAuth(boolean need) {
 472         socketLock.lock();
 473         try {
 474             conContext.sslConfig.clientAuthType =
 475                     (need ? ClientAuthType.CLIENT_AUTH_REQUIRED :
 476                             ClientAuthType.CLIENT_AUTH_NONE);
 477         } finally {
 478             socketLock.unlock();
 479         }
 480     }
 481 
 482     @Override
 483     public boolean getNeedClientAuth() {
 484         socketLock.lock();
 485         try {
 486             return (conContext.sslConfig.clientAuthType ==
 487                         ClientAuthType.CLIENT_AUTH_REQUIRED);
 488         } finally {
 489             socketLock.unlock();
 490         }
 491     }
 492 
 493     @Override
 494     public void setWantClientAuth(boolean want) {
 495         socketLock.lock();
 496         try {
 497             conContext.sslConfig.clientAuthType =
 498                     (want ? ClientAuthType.CLIENT_AUTH_REQUESTED :
 499                             ClientAuthType.CLIENT_AUTH_NONE);
 500         } finally {
 501             socketLock.unlock();
 502         }
 503     }
 504 
 505     @Override
 506     public boolean getWantClientAuth() {
 507         socketLock.lock();
 508         try {
 509             return (conContext.sslConfig.clientAuthType ==
 510                         ClientAuthType.CLIENT_AUTH_REQUESTED);
 511         } finally {
 512             socketLock.unlock();
 513         }
 514     }
 515 
 516     @Override
 517     public void setEnableSessionCreation(boolean flag) {
 518         socketLock.lock();
 519         try {
 520             conContext.sslConfig.enableSessionCreation = flag;
 521         } finally {
 522             socketLock.unlock();
 523         }
 524     }
 525 
 526     @Override
 527     public boolean getEnableSessionCreation() {
 528         socketLock.lock();
 529         try {
 530             return conContext.sslConfig.enableSessionCreation;
 531         } finally {
 532             socketLock.unlock();
 533         }
 534     }
 535 
 536     @Override
 537     public boolean isClosed() {
 538         return tlsIsClosed;
 539     }
 540 
 541     // Please don't synchronized this method.  Otherwise, the read and close
 542     // locks may be deadlocked.
 543     @Override
 544     public void close() throws IOException {
 545         if (tlsIsClosed) {
 546             return;
 547         }
 548 
 549         if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
 550             SSLLogger.fine("duplex close of SSLSocket");
 551         }
 552 
 553         try {
 554             // shutdown output bound, which may have been closed previously.
 555             if (!isOutputShutdown()) {
 556                 duplexCloseOutput();
 557             }
 558 
 559             // shutdown input bound, which may have been closed previously.
 560             if (!isInputShutdown()) {
 561                 duplexCloseInput();
 562             }
 563 
 564             if (!isClosed()) {
 565                 // close the connection directly
 566                 closeSocket(false);
 567             }
 568         } catch (IOException ioe) {
 569             // ignore the exception
 570             if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
 571                 SSLLogger.warning("SSLSocket duplex close failed", ioe);
 572             }
 573         } finally {
 574             tlsIsClosed = true;
 575         }
 576     }
 577 
 578     /**
 579      * Duplex close, start from closing outbound.
 580      *
 581      * For TLS 1.2 [RFC 5246], unless some other fatal alert has been
 582      * transmitted, each party is required to send a close_notify alert
 583      * before closing the write side of the connection.  The other party
 584      * MUST respond with a close_notify alert of its own and close down
 585      * the connection immediately, discarding any pending writes.  It is
 586      * not required for the initiator of the close to wait for the responding
 587      * close_notify alert before closing the read side of the connection.
 588      *
 589      * For TLS 1.3, Each party MUST send a close_notify alert before
 590      * closing its write side of the connection, unless it has already sent
 591      * some error alert.  This does not have any effect on its read side of
 592      * the connection.  Both parties need not wait to receive a close_notify
 593      * alert before closing their read side of the connection, though doing
 594      * so would introduce the possibility of truncation.
 595      *
 596      * In order to support user initiated duplex-close for TLS 1.3 connections,
 597      * the user_canceled alert is used together with the close_notify alert.
 598      */
 599     private void duplexCloseOutput() throws IOException {
 600         boolean useUserCanceled = false;
 601         boolean hasCloseReceipt = false;
 602         if (conContext.isNegotiated) {
 603             if (!conContext.protocolVersion.useTLS13PlusSpec()) {
 604                 hasCloseReceipt = true;
 605             } else {
 606                 // Use a user_canceled alert for TLS 1.3 duplex close.
 607                 useUserCanceled = true;
 608             }
 609         } else if (conContext.handshakeContext != null) {   // initial handshake
 610             // Use user_canceled alert regardless the protocol versions.
 611             useUserCanceled = true;
 612 
 613             // The protocol version may have been negotiated.
 614             ProtocolVersion pv = conContext.handshakeContext.negotiatedProtocol;
 615             if (pv == null || (!pv.useTLS13PlusSpec())) {
 616                 hasCloseReceipt = true;
 617             }
 618         }
 619 
 620         // Need a lock here so that the user_canceled alert and the
 621         // close_notify alert can be delivered together.
 622         int linger = getSoLinger();
 623         if (linger >= 0) {
 624             // don't wait more than SO_LINGER for obtaining the
 625             // the lock.
 626             //
 627             // keep and clear the current thread interruption status.
 628             boolean interrupted = Thread.interrupted();
 629             try {
 630                 if (conContext.outputRecord.recordLock.tryLock() ||
 631                         conContext.outputRecord.recordLock.tryLock(
 632                                 linger, TimeUnit.SECONDS)) {
 633                     try {
 634                         handleClosedNotifyAlert(useUserCanceled);
 635                     } finally {
 636                         conContext.outputRecord.recordLock.unlock();
 637                     }
 638                 } else {
 639                     // For layered, non-autoclose sockets, we are not
 640                     // able to bring them into a usable state, so we
 641                     // treat it as fatal error.
 642                     if (!super.isOutputShutdown()) {
 643                         if (isLayered() && !autoClose) {
 644                             throw new SSLException(
 645                                     "SO_LINGER timeout, " +
 646                                     "close_notify message cannot be sent.");
 647                         } else {
 648                             super.shutdownOutput();
 649                             if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
 650                                 SSLLogger.warning(
 651                                     "SSLSocket output duplex close failed: " +
 652                                     "SO_LINGER timeout, " +
 653                                     "close_notify message cannot be sent.");
 654                             }
 655                         }
 656                     }
 657 
 658                     // RFC2246 requires that the session becomes
 659                     // unresumable if any connection is terminated
 660                     // without proper close_notify messages with
 661                     // level equal to warning.
 662                     //
 663                     // RFC4346 no longer requires that a session not be
 664                     // resumed if failure to properly close a connection.
 665                     //
 666                     // We choose to make the session unresumable if
 667                     // failed to send the close_notify message.
 668                     //
 669                     conContext.conSession.invalidate();
 670                     if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
 671                         SSLLogger.warning(
 672                                 "Invalidate the session: SO_LINGER timeout, " +
 673                                 "close_notify message cannot be sent.");
 674                     }
 675                 }
 676             } catch (InterruptedException ex) {
 677                 // keep interrupted status
 678                 interrupted = true;
 679             }
 680 
 681             // restore the interrupted status
 682             if (interrupted) {
 683                 Thread.currentThread().interrupt();
 684             }
 685         } else {
 686             conContext.outputRecord.recordLock.lock();
 687             try {
 688                 handleClosedNotifyAlert(useUserCanceled);
 689             } finally {
 690                 conContext.outputRecord.recordLock.unlock();
 691             }
 692         }
 693 
 694         if (!isInputShutdown()) {
 695             bruteForceCloseInput(hasCloseReceipt);
 696         }
 697     }
 698 
 699     private void handleClosedNotifyAlert(
 700             boolean useUserCanceled) throws IOException {
 701         try {
 702             // send a user_canceled alert if needed.
 703             if (useUserCanceled) {
 704                 conContext.warning(Alert.USER_CANCELED);
 705             }
 706 
 707             // send a close_notify alert
 708             conContext.warning(Alert.CLOSE_NOTIFY);
 709         } finally {
 710             if (!conContext.isOutboundClosed()) {
 711                 conContext.outputRecord.close();
 712             }
 713 
 714             if (!super.isOutputShutdown() &&
 715                     (autoClose || !isLayered())) {
 716                 super.shutdownOutput();
 717             }
 718         }
 719     }
 720 
 721     /**
 722      * Duplex close, start from closing inbound.
 723      *
 724      * This method should only be called when the outbound has been closed,
 725      * but the inbound is still open.
 726      */
 727     private void duplexCloseInput() throws IOException {
 728         boolean hasCloseReceipt = false;
 729         if (conContext.isNegotiated &&
 730                 !conContext.protocolVersion.useTLS13PlusSpec()) {
 731             hasCloseReceipt = true;
 732         }   // No close receipt if handshake has no completed.
 733 
 734         bruteForceCloseInput(hasCloseReceipt);
 735     }
 736 
 737     /**
 738      * Brute force close the input bound.
 739      *
 740      * This method should only be called when the outbound has been closed,
 741      * but the inbound is still open.
 742      */
 743     private void bruteForceCloseInput(
 744             boolean hasCloseReceipt) throws IOException {
 745         if (hasCloseReceipt) {
 746             // It is not required for the initiator of the close to wait for
 747             // the responding close_notify alert before closing the read side
 748             // of the connection.  However, if the application protocol using
 749             // TLS provides that any data may be carried over the underlying
 750             // transport after the TLS connection is closed, the TLS
 751             // implementation MUST receive a "close_notify" alert before
 752             // indicating end-of-data to the application-layer.
 753             try {
 754                 this.shutdown();
 755             } finally {
 756                 if (!isInputShutdown()) {
 757                     shutdownInput(false);
 758                 }
 759             }
 760         } else {
 761             if (!conContext.isInboundClosed()) {
 762                 try (conContext.inputRecord) {
 763                     // Try the best to use up the input records and close the
 764                     // socket gracefully, without impact the performance too
 765                     // much.
 766                     appInput.deplete();
 767                 }
 768             }
 769 
 770             if ((autoClose || !isLayered()) && !super.isInputShutdown()) {
 771                 super.shutdownInput();
 772             }
 773         }
 774     }
 775 
 776     // Please don't synchronized this method.  Otherwise, the read and close
 777     // locks may be deadlocked.
 778     @Override
 779     public void shutdownInput() throws IOException {
 780         shutdownInput(true);
 781     }
 782 
 783     // It is not required to check the close_notify receipt unless an
 784     // application call shutdownInput() explicitly.
 785     private void shutdownInput(
 786             boolean checkCloseNotify) throws IOException {
 787         if (isInputShutdown()) {
 788             return;
 789         }
 790 
 791         if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
 792             SSLLogger.fine("close inbound of SSLSocket");
 793         }
 794 
 795         // Is it ready to close inbound?
 796         //
 797         // No need to throw exception if the initial handshake is not started.
 798         if (checkCloseNotify && !conContext.isInputCloseNotified &&
 799             (conContext.isNegotiated || conContext.handshakeContext != null)) {
 800 
 801             throw conContext.fatal(Alert.INTERNAL_ERROR,
 802                     "closing inbound before receiving peer's close_notify");
 803         }
 804 
 805         conContext.closeInbound();
 806         if ((autoClose || !isLayered()) && !super.isInputShutdown()) {
 807             super.shutdownInput();
 808         }
 809     }
 810 
 811     @Override
 812     public boolean isInputShutdown() {
 813         return conContext.isInboundClosed() &&
 814                 ((autoClose || !isLayered()) ? super.isInputShutdown(): true);
 815     }
 816 
 817     // Please don't synchronized this method.  Otherwise, the read and close
 818     // locks may be deadlocked.
 819     @Override
 820     public void shutdownOutput() throws IOException {
 821         if (isOutputShutdown()) {
 822             return;
 823         }
 824 
 825         if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
 826             SSLLogger.fine("close outbound of SSLSocket");
 827         }
 828         conContext.closeOutbound();
 829 
 830         if ((autoClose || !isLayered()) && !super.isOutputShutdown()) {
 831             super.shutdownOutput();
 832         }
 833     }
 834 
 835     @Override
 836     public boolean isOutputShutdown() {
 837         return conContext.isOutboundClosed() &&
 838                 ((autoClose || !isLayered()) ? super.isOutputShutdown(): true);
 839     }
 840 
 841     @Override
 842     public InputStream getInputStream() throws IOException {
 843         socketLock.lock();
 844         try {
 845             if (isClosed()) {
 846                 throw new SocketException("Socket is closed");
 847             }
 848 
 849             if (!isConnected) {
 850                 throw new SocketException("Socket is not connected");
 851             }
 852 
 853             if (conContext.isInboundClosed() || isInputShutdown()) {
 854                 throw new SocketException("Socket input is already shutdown");
 855             }
 856 
 857             return appInput;
 858         } finally {
 859             socketLock.unlock();
 860         }
 861     }
 862 
 863     private void ensureNegotiated() throws IOException {
 864         if (conContext.isNegotiated || conContext.isBroken ||
 865                 conContext.isInboundClosed() || conContext.isOutboundClosed()) {
 866             return;
 867         }
 868 
 869         handshakeLock.lock();
 870         try {
 871             // double check the context status
 872             if (conContext.isNegotiated || conContext.isBroken ||
 873                     conContext.isInboundClosed() ||
 874                     conContext.isOutboundClosed()) {
 875                 return;
 876             }
 877 
 878             startHandshake();
 879         } finally {
 880             handshakeLock.unlock();
 881         }
 882     }
 883 
 884     /**
 885      * InputStream for application data as returned by
 886      * SSLSocket.getInputStream().
 887      */
 888     private class AppInputStream extends InputStream {
 889         // One element array used to implement the single byte read() method
 890         private final byte[] oneByte = new byte[1];
 891 
 892         // the temporary buffer used to read network
 893         private ByteBuffer buffer;
 894 
 895         // Is application data available in the stream?
 896         private volatile boolean appDataIsAvailable;
 897 
 898         // reading lock
 899         private final ReentrantLock readLock = new ReentrantLock();
 900 
 901         // closing status
 902         private volatile boolean isClosing;
 903         private volatile boolean hasDepleted;
 904 
 905         AppInputStream() {
 906             this.appDataIsAvailable = false;
 907             this.buffer = ByteBuffer.allocate(4096);
 908         }
 909 
 910         /**
 911          * Return the minimum number of bytes that can be read
 912          * without blocking.
 913          */
 914         @Override
 915         public int available() throws IOException {
 916             // Currently not synchronized.
 917             if ((!appDataIsAvailable) || checkEOF()) {
 918                 return 0;
 919             }
 920 
 921             return buffer.remaining();
 922         }
 923 
 924         /**
 925          * Read a single byte, returning -1 on non-fault EOF status.
 926          */
 927         @Override
 928         public int read() throws IOException {
 929             int n = read(oneByte, 0, 1);
 930             if (n <= 0) {   // EOF
 931                 return -1;
 932             }
 933 
 934             return oneByte[0] & 0xFF;
 935         }
 936 
 937         /**
 938          * Reads up to {@code len} bytes of data from the input stream
 939          * into an array of bytes.
 940          *
 941          * An attempt is made to read as many as {@code len} bytes, but a
 942          * smaller number may be read. The number of bytes actually read
 943          * is returned as an integer.
 944          *
 945          * If the layer above needs more data, it asks for more, so we
 946          * are responsible only for blocking to fill at most one buffer,
 947          * and returning "-1" on non-fault EOF status.
 948          */
 949         @Override
 950         public int read(byte[] b, int off, int len) throws IOException {
 951             if (b == null) {
 952                 throw new NullPointerException("the target buffer is null");
 953             } else if (off < 0 || len < 0 || len > b.length - off) {
 954                 throw new IndexOutOfBoundsException(
 955                         "buffer length: " + b.length + ", offset; " + off +
 956                         ", bytes to read:" + len);
 957             } else if (len == 0) {
 958                 return 0;
 959             }
 960 
 961             if (checkEOF()) {
 962                 return -1;
 963             }
 964 
 965             // start handshaking if the connection has not been negotiated.
 966             if (!conContext.isNegotiated && !conContext.isBroken &&
 967                     !conContext.isInboundClosed() &&
 968                     !conContext.isOutboundClosed()) {
 969                 ensureNegotiated();
 970             }
 971 
 972             // Check if the Socket is invalid (error or closed).
 973             if (!conContext.isNegotiated ||
 974                     conContext.isBroken || conContext.isInboundClosed()) {
 975                 throw new SocketException("Connection or inbound has closed");
 976             }
 977 
 978             // Check if the input stream has been depleted.
 979             //
 980             // Note that the "hasDepleted" rather than the isClosing
 981             // filed is checked here, in case the closing process is
 982             // still in progress.
 983             if (hasDepleted) {
 984                 if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
 985                     SSLLogger.fine("The input stream has been depleted");
 986                 }
 987 
 988                 return -1;
 989             }
 990 
 991             // Read the available bytes at first.
 992             //
 993             // Note that the receiving and processing of post-handshake message
 994             // are also synchronized with the read lock.
 995             readLock.lock();
 996             try {
 997                 // Double check if the Socket is invalid (error or closed).
 998                 if (conContext.isBroken || conContext.isInboundClosed()) {
 999                     throw new SocketException(
1000                             "Connection or inbound has closed");
1001                 }
1002 
1003                 // Double check if the input stream has been depleted.
1004                 if (hasDepleted) {
1005                     if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
1006                         SSLLogger.fine("The input stream is closing");
1007                     }
1008 
1009                     return -1;
1010                 }
1011 
1012                 int remains = available();
1013                 if (remains > 0) {
1014                     int howmany = Math.min(remains, len);
1015                     buffer.get(b, off, howmany);
1016 
1017                     return howmany;
1018                 }
1019 
1020                 appDataIsAvailable = false;
1021                 try {
1022                     ByteBuffer bb = readApplicationRecord(buffer);
1023                     if (bb == null) {   // EOF
1024                         return -1;
1025                     } else {
1026                         // The buffer may be reallocated for bigger capacity.
1027                         buffer = bb;
1028                     }
1029 
1030                     bb.flip();
1031                     int volume = Math.min(len, bb.remaining());
1032                     buffer.get(b, off, volume);
1033                     appDataIsAvailable = true;
1034 
1035                     return volume;
1036                 } catch (Exception e) {   // including RuntimeException
1037                     // shutdown and rethrow (wrapped) exception as appropriate
1038                     handleException(e);
1039 
1040                     // dummy for compiler
1041                     return -1;
1042                 }
1043             } finally {
1044                 // Check if the input stream is closing.
1045                 //
1046                 // If the deplete() did not hold the lock, clean up the
1047                 // input stream here.
1048                 try {
1049                     if (isClosing) {
1050                         readLockedDeplete();
1051                     }
1052                 } finally {
1053                     readLock.unlock();
1054                 }
1055             }
1056         }
1057 
1058         /**
1059          * Skip n bytes.
1060          *
1061          * This implementation is somewhat less efficient than possible, but
1062          * not badly so (redundant copy).  We reuse the read() code to keep
1063          * things simpler.
1064          */
1065         @Override
1066         public long skip(long n) throws IOException {
1067             // dummy array used to implement skip()
1068             byte[] skipArray = new byte[256];
1069             long skipped = 0;
1070 
1071             readLock.lock();
1072             try {
1073                 while (n > 0) {
1074                     int len = (int)Math.min(n, skipArray.length);
1075                     int r = read(skipArray, 0, len);
1076                     if (r <= 0) {
1077                         break;
1078                     }
1079                     n -= r;
1080                     skipped += r;
1081                 }
1082             } finally {
1083                 readLock.unlock();
1084             }
1085 
1086             return skipped;
1087         }
1088 
1089         @Override
1090         public void close() throws IOException {
1091             if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
1092                 SSLLogger.finest("Closing input stream");
1093             }
1094 
1095             try {
1096                 SSLSocketImpl.this.close();
1097             } catch (IOException ioe) {
1098                 // ignore the exception
1099                 if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
1100                     SSLLogger.warning("input stream close failed", ioe);
1101                 }
1102             }
1103         }
1104 
1105         /**
1106          * Return whether we have reached end-of-file.
1107          *
1108          * If the socket is not connected, has been shutdown because of an error
1109          * or has been closed, throw an Exception.
1110          */
1111         private boolean checkEOF() throws IOException {
1112             if (conContext.isInboundClosed()) {
1113                 return true;
1114             } else if (conContext.isInputCloseNotified || conContext.isBroken) {
1115                 if (conContext.closeReason == null) {
1116                     return true;
1117                 } else {
1118                     throw new SSLException(
1119                         "Connection has closed: " + conContext.closeReason,
1120                         conContext.closeReason);
1121                 }
1122             }
1123 
1124             return false;
1125         }
1126 
1127         /**
1128          * Try the best to use up the input records so as to close the
1129          * socket gracefully, without impact the performance too much.
1130          */
1131         private void deplete() {
1132             if (conContext.isInboundClosed() || isClosing) {
1133                 return;
1134             }
1135 
1136             isClosing = true;
1137             if (readLock.tryLock()) {
1138                 try {
1139                     readLockedDeplete();
1140                 } finally {
1141                     readLock.unlock();
1142                 }
1143             }
1144         }
1145 
1146         /**
1147          * Try to use up the input records.
1148          *
1149          * Please don't call this method unless the readLock is held by
1150          * the current thread.
1151          */
1152         private void readLockedDeplete() {
1153             // double check
1154             if (hasDepleted || conContext.isInboundClosed()) {
1155                 return;
1156             }
1157 
1158             if (!(conContext.inputRecord instanceof SSLSocketInputRecord)) {
1159                 return;
1160             }
1161 
1162             SSLSocketInputRecord socketInputRecord =
1163                     (SSLSocketInputRecord)conContext.inputRecord;
1164             try {
1165                 socketInputRecord.deplete(
1166                     conContext.isNegotiated && (getSoTimeout() > 0));
1167             } catch (Exception ex) {
1168                 if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
1169                     SSLLogger.warning(
1170                         "input stream close depletion failed", ex);
1171                 }
1172             } finally {
1173                 hasDepleted = true;
1174             }
1175         }
1176     }
1177 
1178     @Override
1179     public OutputStream getOutputStream() throws IOException {
1180         socketLock.lock();
1181         try {
1182             if (isClosed()) {
1183                 throw new SocketException("Socket is closed");
1184             }
1185 
1186             if (!isConnected) {
1187                 throw new SocketException("Socket is not connected");
1188             }
1189 
1190             if (conContext.isOutboundDone() || isOutputShutdown()) {
1191                 throw new SocketException("Socket output is already shutdown");
1192             }
1193 
1194             return appOutput;
1195         } finally {
1196             socketLock.unlock();
1197         }
1198     }
1199 
1200 
1201     /**
1202      * OutputStream for application data as returned by
1203      * SSLSocket.getOutputStream().
1204      */
1205     private class AppOutputStream extends OutputStream {
1206         // One element array used to implement the write(byte) method
1207         private final byte[] oneByte = new byte[1];
1208 
1209         @Override
1210         public void write(int i) throws IOException {
1211             oneByte[0] = (byte)i;
1212             write(oneByte, 0, 1);
1213         }
1214 
1215         @Override
1216         public void write(byte[] b,
1217                 int off, int len) throws IOException {
1218             if (b == null) {
1219                 throw new NullPointerException("the source buffer is null");
1220             } else if (off < 0 || len < 0 || len > b.length - off) {
1221                 throw new IndexOutOfBoundsException(
1222                         "buffer length: " + b.length + ", offset; " + off +
1223                         ", bytes to read:" + len);
1224             } else if (len == 0) {
1225                 //
1226                 // Don't bother to really write empty records.  We went this
1227                 // far to drive the handshake machinery, for correctness; not
1228                 // writing empty records improves performance by cutting CPU
1229                 // time and network resource usage.  However, some protocol
1230                 // implementations are fragile and don't like to see empty
1231                 // records, so this also increases robustness.
1232                 //
1233                 return;
1234             }
1235 
1236             // Start handshaking if the connection has not been negotiated.
1237             if (!conContext.isNegotiated && !conContext.isBroken &&
1238                     !conContext.isInboundClosed() &&
1239                     !conContext.isOutboundClosed()) {
1240                 ensureNegotiated();
1241             }
1242 
1243             // Check if the Socket is invalid (error or closed).
1244             if (!conContext.isNegotiated ||
1245                     conContext.isBroken || conContext.isOutboundClosed()) {
1246                 throw new SocketException("Connection or outbound has closed");
1247             }
1248 
1249             //
1250 
1251             // Delegate the writing to the underlying socket.
1252             try {
1253                 conContext.outputRecord.deliver(b, off, len);
1254             } catch (SSLHandshakeException she) {
1255                 // may be record sequence number overflow
1256                 throw conContext.fatal(Alert.HANDSHAKE_FAILURE, she);
1257             } catch (IOException e) {
1258                 throw conContext.fatal(Alert.UNEXPECTED_MESSAGE, e);
1259             }
1260 
1261             // Is the sequence number is nearly overflow, or has the key usage
1262             // limit been reached?
1263             if (conContext.outputRecord.seqNumIsHuge() ||
1264                     conContext.outputRecord.writeCipher.atKeyLimit()) {
1265                 tryKeyUpdate();
1266             }
1267         }
1268 
1269         @Override
1270         public void close() throws IOException {
1271             if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
1272                 SSLLogger.finest("Closing output stream");
1273             }
1274 
1275             try {
1276                 SSLSocketImpl.this.close();
1277             } catch (IOException ioe) {
1278                 // ignore the exception
1279                 if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
1280                     SSLLogger.warning("output stream close failed", ioe);
1281                 }
1282             }
1283         }
1284     }
1285 
1286     @Override
1287     public SSLParameters getSSLParameters() {
1288         socketLock.lock();
1289         try {
1290             return conContext.sslConfig.getSSLParameters();
1291         } finally {
1292             socketLock.unlock();
1293         }
1294     }
1295 
1296     @Override
1297     public void setSSLParameters(SSLParameters params) {
1298         socketLock.lock();
1299         try {
1300             conContext.sslConfig.setSSLParameters(params);
1301 
1302             if (conContext.sslConfig.maximumPacketSize != 0) {
1303                 conContext.outputRecord.changePacketSize(
1304                         conContext.sslConfig.maximumPacketSize);
1305             }
1306         } finally {
1307             socketLock.unlock();
1308         }
1309     }
1310 
1311     @Override
1312     public String getApplicationProtocol() {
1313         socketLock.lock();
1314         try {
1315             return conContext.applicationProtocol;
1316         } finally {
1317             socketLock.unlock();
1318         }
1319     }
1320 
1321     @Override
1322     public String getHandshakeApplicationProtocol() {
1323         socketLock.lock();
1324         try {
1325             if (conContext.handshakeContext != null) {
1326                 return conContext.handshakeContext.applicationProtocol;
1327             }
1328         } finally {
1329             socketLock.unlock();
1330         }
1331 
1332         return null;
1333     }
1334 
1335     @Override
1336     public void setHandshakeApplicationProtocolSelector(
1337             BiFunction<SSLSocket, List<String>, String> selector) {
1338         socketLock.lock();
1339         try {
1340             conContext.sslConfig.socketAPSelector = selector;
1341         } finally {
1342             socketLock.unlock();
1343         }
1344     }
1345 
1346     @Override
1347     public BiFunction<SSLSocket, List<String>, String>
1348             getHandshakeApplicationProtocolSelector() {
1349         socketLock.lock();
1350         try {
1351             return conContext.sslConfig.socketAPSelector;
1352         } finally {
1353             socketLock.unlock();
1354         }
1355     }
1356 
1357     /**
1358      * Read the initial handshake records.
1359      */
1360     private int readHandshakeRecord() throws IOException {
1361         while (!conContext.isInboundClosed()) {
1362             try {
1363                 Plaintext plainText = decode(null);
1364                 if ((plainText.contentType == ContentType.HANDSHAKE.id) &&
1365                         conContext.isNegotiated) {
1366                     return 0;
1367                 }
1368             } catch (SSLException ssle) {
1369                 throw ssle;
1370             } catch (IOException ioe) {
1371                 if (!(ioe instanceof SSLException)) {
1372                     throw new SSLException("readHandshakeRecord", ioe);
1373                 } else {
1374                     throw ioe;
1375                 }
1376             }
1377         }
1378 
1379         return -1;
1380     }
1381 
1382     /**
1383      * Read application data record. Used by AppInputStream only, but defined
1384      * here so as to use the socket level synchronization.
1385      *
1386      * Note that the connection guarantees that handshake, alert, and change
1387      * cipher spec data streams are handled as they arrive, so we never see
1388      * them here.
1389      *
1390      * Note: Please be careful about the synchronization, and don't use this
1391      * method other than in the AppInputStream class!
1392      */
1393     private ByteBuffer readApplicationRecord(
1394             ByteBuffer buffer) throws IOException {
1395         while (!conContext.isInboundClosed()) {
1396             /*
1397              * clean the buffer and check if it is too small, e.g. because
1398              * the AppInputStream did not have the chance to see the
1399              * current packet length but rather something like that of the
1400              * handshake before. In that case we return 0 at this point to
1401              * give the caller the chance to adjust the buffer.
1402              */
1403             buffer.clear();
1404             int inLen = conContext.inputRecord.bytesInCompletePacket();
1405             if (inLen < 0) {    // EOF
1406                 handleEOF(null);
1407 
1408                 // if no exception thrown
1409                 return null;
1410             }
1411 
1412             // Is this packet bigger than SSL/TLS normally allows?
1413             if (inLen > SSLRecord.maxLargeRecordSize) {
1414                 throw new SSLProtocolException(
1415                         "Illegal packet size: " + inLen);
1416             }
1417 
1418             if (inLen > buffer.remaining()) {
1419                 buffer = ByteBuffer.allocate(inLen);
1420             }
1421 
1422             try {
1423                 Plaintext plainText;
1424                 socketLock.lock();
1425                 try {
1426                     plainText = decode(buffer);
1427                 } finally {
1428                     socketLock.unlock();
1429                 }
1430                 if (plainText.contentType == ContentType.APPLICATION_DATA.id &&
1431                         buffer.position() > 0) {
1432                     return buffer;
1433                 }
1434             } catch (SSLException ssle) {
1435                 throw ssle;
1436             } catch (IOException ioe) {
1437                 if (!(ioe instanceof SSLException)) {
1438                     throw new SSLException("readApplicationRecord", ioe);
1439                 } else {
1440                     throw ioe;
1441                 }
1442             }
1443         }
1444 
1445         //
1446         // couldn't read, due to some kind of error
1447         //
1448         return null;
1449     }
1450 
1451     private Plaintext decode(ByteBuffer destination) throws IOException {
1452         Plaintext plainText;
1453         try {
1454             if (destination == null) {
1455                 plainText = SSLTransport.decode(conContext,
1456                         null, 0, 0, null, 0, 0);
1457             } else {
1458                 plainText = SSLTransport.decode(conContext,
1459                         null, 0, 0, new ByteBuffer[]{destination}, 0, 1);
1460             }
1461         } catch (EOFException eofe) {
1462             // EOFException is special as it is related to close_notify.
1463             plainText = handleEOF(eofe);
1464         }
1465 
1466         // Is the sequence number is nearly overflow?
1467         if (plainText != Plaintext.PLAINTEXT_NULL &&
1468                 (conContext.inputRecord.seqNumIsHuge() ||
1469                 conContext.inputRecord.readCipher.atKeyLimit())) {
1470             tryKeyUpdate();
1471         }
1472 
1473         return plainText;
1474     }
1475 
1476     /**
1477      * Try key update for sequence number wrap or key usage limit.
1478      *
1479      * Note that in order to maintain the handshake status properly, we check
1480      * the sequence number and key usage limit after the last record
1481      * reading/writing process.
1482      *
1483      * As we request renegotiation or close the connection for wrapped sequence
1484      * number when there is enough sequence number space left to handle a few
1485      * more records, so the sequence number of the last record cannot be
1486      * wrapped.
1487      */
1488     private void tryKeyUpdate() throws IOException {
1489         // Don't bother to kickstart if handshaking is in progress, or if the
1490         // connection is not duplex-open.
1491         if ((conContext.handshakeContext == null) &&
1492                 !conContext.isOutboundClosed() &&
1493                 !conContext.isInboundClosed() &&
1494                 !conContext.isBroken) {
1495             if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
1496                 SSLLogger.finest("trigger key update");
1497             }
1498             startHandshake();
1499         }
1500     }
1501 
1502     /**
1503      * Initialize the handshaker and socket streams.
1504      *
1505      * Called by connect, the layered constructor, and SSLServerSocket.
1506      */
1507     void doneConnect() throws IOException {
1508         socketLock.lock();
1509         try {
1510             // In server mode, it is not necessary to set host and serverNames.
1511             // Otherwise, would require a reverse DNS lookup to get
1512             // the hostname.
1513             if (peerHost == null || peerHost.isEmpty()) {
1514                 boolean useNameService =
1515                         trustNameService && conContext.sslConfig.isClientMode;
1516                 useImplicitHost(useNameService);
1517             } else {
1518                 conContext.sslConfig.serverNames =
1519                         Utilities.addToSNIServerNameList(
1520                                 conContext.sslConfig.serverNames, peerHost);
1521             }
1522 
1523             InputStream sockInput = super.getInputStream();
1524             conContext.inputRecord.setReceiverStream(sockInput);
1525 
1526             OutputStream sockOutput = super.getOutputStream();
1527             conContext.inputRecord.setDeliverStream(sockOutput);
1528             conContext.outputRecord.setDeliverStream(sockOutput);
1529 
1530             this.isConnected = true;
1531         } finally {
1532             socketLock.unlock();
1533         }
1534     }
1535 
1536     private void useImplicitHost(boolean useNameService) {
1537         // Note: If the local name service is not trustworthy, reverse
1538         // host name resolution should not be performed for endpoint
1539         // identification.  Use the application original specified
1540         // hostname or IP address instead.
1541 
1542         // Get the original hostname via jdk.internal.access.SharedSecrets
1543         InetAddress inetAddress = getInetAddress();
1544         if (inetAddress == null) {      // not connected
1545             return;
1546         }
1547 
1548         JavaNetInetAddressAccess jna =
1549                 SharedSecrets.getJavaNetInetAddressAccess();
1550         String originalHostname = jna.getOriginalHostName(inetAddress);
1551         if (originalHostname != null && !originalHostname.isEmpty()) {
1552 
1553             this.peerHost = originalHostname;
1554             if (conContext.sslConfig.serverNames.isEmpty() &&
1555                     !conContext.sslConfig.noSniExtension) {
1556                 conContext.sslConfig.serverNames =
1557                         Utilities.addToSNIServerNameList(
1558                                 conContext.sslConfig.serverNames, peerHost);
1559             }
1560 
1561             return;
1562         }
1563 
1564         // No explicitly specified hostname, no server name indication.
1565         if (!useNameService) {
1566             // The local name service is not trustworthy, use IP address.
1567             this.peerHost = inetAddress.getHostAddress();
1568         } else {
1569             // Use the underlying reverse host name resolution service.
1570             this.peerHost = getInetAddress().getHostName();
1571         }
1572     }
1573 
1574     // ONLY used by HttpsClient to setup the URI specified hostname
1575     //
1576     // Please NOTE that this method MUST be called before calling to
1577     // SSLSocket.setSSLParameters(). Otherwise, the {@code host} parameter
1578     // may override SNIHostName in the customized server name indication.
1579     public void setHost(String host) {
1580         socketLock.lock();
1581         try {
1582             this.peerHost = host;
1583             this.conContext.sslConfig.serverNames =
1584                     Utilities.addToSNIServerNameList(
1585                             conContext.sslConfig.serverNames, host);
1586         } finally {
1587             socketLock.unlock();
1588         }
1589     }
1590 
1591     /**
1592      * Handle an exception.
1593      *
1594      * This method is called by top level exception handlers (in read(),
1595      * write()) to make sure we always shutdown the connection correctly
1596      * and do not pass runtime exception to the application.
1597      *
1598      * This method never returns normally, it always throws an IOException.
1599      */
1600     private void handleException(Exception cause) throws IOException {
1601         if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
1602             SSLLogger.warning("handling exception", cause);
1603         }
1604 
1605         // Don't close the Socket in case of timeouts or interrupts.
1606         if (cause instanceof InterruptedIOException) {
1607             throw (IOException)cause;
1608         }
1609 
1610         // need to perform error shutdown
1611         boolean isSSLException = (cause instanceof SSLException);
1612         Alert alert;
1613         if (isSSLException) {
1614             if (cause instanceof SSLHandshakeException) {
1615                 alert = Alert.HANDSHAKE_FAILURE;
1616             } else {
1617                 alert = Alert.UNEXPECTED_MESSAGE;
1618             }
1619         } else {
1620             if (cause instanceof IOException) {
1621                 alert = Alert.UNEXPECTED_MESSAGE;
1622             } else {
1623                 // RuntimeException
1624                 alert = Alert.INTERNAL_ERROR;
1625             }
1626         }
1627 
1628         throw conContext.fatal(alert, cause);
1629     }
1630 
1631     private Plaintext handleEOF(EOFException eofe) throws IOException {
1632         if (requireCloseNotify || conContext.handshakeContext != null) {
1633             SSLException ssle;
1634             if (conContext.handshakeContext != null) {
1635                 ssle = new SSLHandshakeException(
1636                         "Remote host terminated the handshake");
1637             } else {
1638                 ssle = new SSLProtocolException(
1639                         "Remote host terminated the connection");
1640             }
1641 
1642             if (eofe != null) {
1643                 ssle.initCause(eofe);
1644             }
1645             throw ssle;
1646         } else {
1647             // treat as if we had received a close_notify
1648             conContext.isInputCloseNotified = true;
1649             shutdownInput();
1650 
1651             return Plaintext.PLAINTEXT_NULL;
1652         }
1653     }
1654 
1655 
1656     @Override
1657     public String getPeerHost() {
1658         return peerHost;
1659     }
1660 
1661     @Override
1662     public int getPeerPort() {
1663         return getPort();
1664     }
1665 
1666     @Override
1667     public boolean useDelegatedTask() {
1668         return false;
1669     }
1670 
1671     @Override
1672     public void shutdown() throws IOException {
1673         if (!isClosed()) {
1674             if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
1675                 SSLLogger.fine("close the underlying socket");
1676             }
1677 
1678             try {
1679                 if (conContext.isInputCloseNotified) {
1680                     // Close the connection, no wait for more peer response.
1681                     closeSocket(false);
1682                 } else {
1683                     // Close the connection, may wait for peer close_notify.
1684                     closeSocket(true);
1685                 }
1686             } finally {
1687                 tlsIsClosed = true;
1688             }
1689         }
1690     }
1691 
1692     private void closeSocket(boolean selfInitiated) throws IOException {
1693         if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
1694             SSLLogger.fine("close the SSL connection " +
1695                 (selfInitiated ? "(initiative)" : "(passive)"));
1696         }
1697 
1698         if (autoClose || !isLayered()) {
1699             super.close();
1700         } else if (selfInitiated) {
1701             if (!conContext.isInboundClosed() && !isInputShutdown()) {
1702                 // wait for close_notify alert to clear input stream.
1703                 waitForClose();
1704             }
1705         }
1706     }
1707 
1708    /**
1709     * Wait for close_notify alert for a graceful closure.
1710     *
1711     * [RFC 5246] If the application protocol using TLS provides that any
1712     * data may be carried over the underlying transport after the TLS
1713     * connection is closed, the TLS implementation must receive the responding
1714     * close_notify alert before indicating to the application layer that
1715     * the TLS connection has ended.  If the application protocol will not
1716     * transfer any additional data, but will only close the underlying
1717     * transport connection, then the implementation MAY choose to close the
1718     * transport without waiting for the responding close_notify.
1719     */
1720     private void waitForClose() throws IOException {
1721         if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
1722             SSLLogger.fine("wait for close_notify or alert");
1723         }
1724 
1725         while (!conContext.isInboundClosed()) {
1726             try {
1727                 Plaintext plainText = decode(null);
1728                 // discard and continue
1729                 if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
1730                     SSLLogger.finest(
1731                         "discard plaintext while waiting for close", plainText);
1732                 }
1733             } catch (Exception e) {   // including RuntimeException
1734                 handleException(e);
1735             }
1736         }
1737     }
1738 }