1 /*
   2  * Copyright (c) 1995, 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 java.net;
  27 
  28 import java.io.FileDescriptor;
  29 import java.io.IOException;
  30 import java.io.InputStream;
  31 import java.io.OutputStream;
  32 
  33 import java.security.AccessController;
  34 import java.security.PrivilegedActionException;
  35 import java.security.PrivilegedExceptionAction;
  36 import java.util.Collections;
  37 import java.util.HashSet;
  38 import java.util.Objects;
  39 import java.util.Set;
  40 
  41 import sun.net.ConnectionResetException;
  42 import sun.net.NetHooks;
  43 import sun.net.PlatformSocketImpl;
  44 import sun.net.ResourceManager;
  45 import sun.net.ext.ExtendedSocketOptions;
  46 import sun.net.util.IPAddressUtil;
  47 import sun.net.util.SocketExceptions;
  48 
  49 /**
  50  * Default Socket Implementation. This implementation does
  51  * not implement any security checks.
  52  * Note this class should <b>NOT</b> be public.
  53  *
  54  * @author  Steven B. Byrne
  55  */
  56 abstract class AbstractPlainSocketImpl extends SocketImpl implements PlatformSocketImpl {
  57     /* instance variable for SO_TIMEOUT */
  58     int timeout;   // timeout in millisec
  59     // traffic class
  60     private int trafficClass;
  61 
  62     private boolean shut_rd = false;
  63     private boolean shut_wr = false;
  64 
  65     private SocketInputStream socketInputStream = null;
  66     private SocketOutputStream socketOutputStream = null;
  67 
  68     /* number of threads using the FileDescriptor */
  69     protected int fdUseCount = 0;
  70 
  71     /* lock when increment/decrementing fdUseCount */
  72     protected final Object fdLock = new Object();
  73 
  74     /* indicates a close is pending on the file descriptor */
  75     protected boolean closePending = false;
  76 
  77     /* indicates connection reset state */
  78     private volatile boolean connectionReset;
  79 
  80     /* indicates whether impl is bound  */
  81     boolean isBound;
  82 
  83     /* indicates whether impl is connected  */
  84     volatile boolean isConnected;
  85 
  86    /* whether this Socket is a stream (TCP) socket or not (UDP)
  87     */
  88     protected boolean stream;
  89 
  90     /* whether this is a server or not */
  91     final boolean isServer;
  92 
  93     /**
  94      * Load net library into runtime.
  95      */
  96     static {
  97         jdk.internal.loader.BootLoader.loadLibrary("net");
  98     }
  99 
 100     private static volatile boolean checkedReusePort;
 101     private static volatile boolean isReusePortAvailable;
 102 
 103     /**
 104      * Tells whether SO_REUSEPORT is supported.
 105      */
 106     static boolean isReusePortAvailable() {
 107         if (!checkedReusePort) {
 108             isReusePortAvailable = isReusePortAvailable0();
 109             checkedReusePort = true;
 110         }
 111         return isReusePortAvailable;
 112     }
 113 
 114     AbstractPlainSocketImpl(boolean isServer) {
 115         this.isServer = isServer;
 116     }
 117 
 118     /**
 119      * Creates a socket with a boolean that specifies whether this
 120      * is a stream socket (true) or an unconnected UDP socket (false).
 121      */
 122     protected synchronized void create(boolean stream) throws IOException {
 123         this.stream = stream;
 124         if (!stream) {
 125             ResourceManager.beforeUdpCreate();
 126             // only create the fd after we know we will be able to create the socket
 127             fd = new FileDescriptor();
 128             try {
 129                 socketCreate(false);
 130                 SocketCleanable.register(fd);
 131             } catch (IOException ioe) {
 132                 ResourceManager.afterUdpClose();
 133                 fd = null;
 134                 throw ioe;
 135             }
 136         } else {
 137             fd = new FileDescriptor();
 138             socketCreate(true);
 139             SocketCleanable.register(fd);
 140         }
 141     }
 142 
 143     /**
 144      * Creates a socket and connects it to the specified port on
 145      * the specified host.
 146      * @param host the specified host
 147      * @param port the specified port
 148      */
 149     protected void connect(String host, int port)
 150         throws UnknownHostException, IOException
 151     {
 152         boolean connected = false;
 153         try {
 154             InetAddress address = InetAddress.getByName(host);
 155             // recording this.address as supplied by caller before calling connect
 156             this.address = address;
 157             this.port = port;
 158             if (address.isLinkLocalAddress()) {
 159                 address = IPAddressUtil.toScopedAddress(address);
 160             }
 161 
 162             connectToAddress(address, port, timeout);
 163             connected = true;
 164         } finally {
 165             if (!connected) {
 166                 try {
 167                     close();
 168                 } catch (IOException ioe) {
 169                     /* Do nothing. If connect threw an exception then
 170                        it will be passed up the call stack */
 171                 }
 172             }
 173             isConnected = connected;
 174         }
 175     }
 176 
 177     /**
 178      * Creates a socket and connects it to the specified address on
 179      * the specified port.
 180      * @param address the address
 181      * @param port the specified port
 182      */
 183     protected void connect(InetAddress address, int port) throws IOException {
 184         // recording this.address as supplied by caller before calling connect
 185         this.address = address;
 186         this.port = port;
 187         if (address.isLinkLocalAddress()) {
 188             address = IPAddressUtil.toScopedAddress(address);
 189         }
 190 
 191         try {
 192             connectToAddress(address, port, timeout);
 193             isConnected = true;
 194             return;
 195         } catch (IOException e) {
 196             // everything failed
 197             close();
 198             throw e;
 199         }
 200     }
 201 
 202     /**
 203      * Creates a socket and connects it to the specified address on
 204      * the specified port.
 205      * @param address the address
 206      * @param timeout the timeout value in milliseconds, or zero for no timeout.
 207      * @throws IOException if connection fails
 208      * @throws  IllegalArgumentException if address is null or is a
 209      *          SocketAddress subclass not supported by this socket
 210      * @since 1.4
 211      */
 212     protected void connect(SocketAddress address, int timeout)
 213             throws IOException {
 214         boolean connected = false;
 215         try {
 216             if (address == null || !(address instanceof InetSocketAddress))
 217                 throw new IllegalArgumentException("unsupported address type");
 218             InetSocketAddress addr = (InetSocketAddress) address;
 219             if (addr.isUnresolved())
 220                 throw new UnknownHostException(addr.getHostName());
 221             // recording this.address as supplied by caller before calling connect
 222             InetAddress ia = addr.getAddress();
 223             this.address = ia;
 224             this.port = addr.getPort();
 225             if (ia.isLinkLocalAddress()) {
 226                 ia = IPAddressUtil.toScopedAddress(ia);
 227             }
 228             connectToAddress(ia, port, timeout);
 229             connected = true;
 230         } finally {
 231             if (!connected) {
 232                 try {
 233                     close();
 234                 } catch (IOException ioe) {
 235                     /* Do nothing. If connect threw an exception then
 236                        it will be passed up the call stack */
 237                 }
 238             }
 239             isConnected = connected;
 240         }
 241     }
 242 
 243     private void connectToAddress(InetAddress address, int port, int timeout) throws IOException {
 244         if (address.isAnyLocalAddress()) {
 245             doConnect(InetAddress.getLocalHost(), port, timeout);
 246         } else {
 247             doConnect(address, port, timeout);
 248         }
 249     }
 250 
 251     public void setOption(int opt, Object val) throws SocketException {
 252         if (isClosedOrPending()) {
 253             throw new SocketException("Socket Closed");
 254         }
 255         boolean on = true;
 256         switch (opt) {
 257             /* check type safety b4 going native.  These should never
 258              * fail, since only java.Socket* has access to
 259              * PlainSocketImpl.setOption().
 260              */
 261         case SO_LINGER:
 262             if (val == null || (!(val instanceof Integer) && !(val instanceof Boolean)))
 263                 throw new SocketException("Bad parameter for option");
 264             if (val instanceof Boolean) {
 265                 /* true only if disabling - enabling should be Integer */
 266                 on = false;
 267             }
 268             break;
 269         case SO_TIMEOUT:
 270             if (val == null || (!(val instanceof Integer)))
 271                 throw new SocketException("Bad parameter for SO_TIMEOUT");
 272             int tmp = ((Integer) val).intValue();
 273             if (tmp < 0)
 274                 throw new IllegalArgumentException("timeout < 0");
 275             timeout = tmp;
 276             break;
 277         case IP_TOS:
 278              if (val == null || !(val instanceof Integer)) {
 279                  throw new SocketException("bad argument for IP_TOS");
 280              }
 281              trafficClass = ((Integer)val).intValue();
 282              break;
 283         case SO_BINDADDR:
 284             throw new SocketException("Cannot re-bind socket");
 285         case TCP_NODELAY:
 286             if (val == null || !(val instanceof Boolean))
 287                 throw new SocketException("bad parameter for TCP_NODELAY");
 288             on = ((Boolean)val).booleanValue();
 289             break;
 290         case SO_SNDBUF:
 291         case SO_RCVBUF:
 292             if (val == null || !(val instanceof Integer) ||
 293                 !(((Integer)val).intValue() > 0)) {
 294                 throw new SocketException("bad parameter for SO_SNDBUF " +
 295                                           "or SO_RCVBUF");
 296             }
 297             break;
 298         case SO_KEEPALIVE:
 299             if (val == null || !(val instanceof Boolean))
 300                 throw new SocketException("bad parameter for SO_KEEPALIVE");
 301             on = ((Boolean)val).booleanValue();
 302             break;
 303         case SO_OOBINLINE:
 304             if (val == null || !(val instanceof Boolean))
 305                 throw new SocketException("bad parameter for SO_OOBINLINE");
 306             on = ((Boolean)val).booleanValue();
 307             break;
 308         case SO_REUSEADDR:
 309             if (val == null || !(val instanceof Boolean))
 310                 throw new SocketException("bad parameter for SO_REUSEADDR");
 311             on = ((Boolean)val).booleanValue();
 312             break;
 313         case SO_REUSEPORT:
 314             if (val == null || !(val instanceof Boolean))
 315                 throw new SocketException("bad parameter for SO_REUSEPORT");
 316             if (!supportedOptions().contains(StandardSocketOptions.SO_REUSEPORT))
 317                 throw new UnsupportedOperationException("unsupported option");
 318             on = ((Boolean)val).booleanValue();
 319             break;
 320         default:
 321             throw new SocketException("unrecognized TCP option: " + opt);
 322         }
 323         socketSetOption(opt, on, val);
 324     }
 325     public Object getOption(int opt) throws SocketException {
 326         if (isClosedOrPending()) {
 327             throw new SocketException("Socket Closed");
 328         }
 329         if (opt == SO_TIMEOUT) {
 330             return timeout;
 331         }
 332         int ret = 0;
 333         /*
 334          * The native socketGetOption() knows about 3 options.
 335          * The 32 bit value it returns will be interpreted according
 336          * to what we're asking.  A return of -1 means it understands
 337          * the option but its turned off.  It will raise a SocketException
 338          * if "opt" isn't one it understands.
 339          */
 340 
 341         switch (opt) {
 342         case TCP_NODELAY:
 343             ret = socketGetOption(opt, null);
 344             return Boolean.valueOf(ret != -1);
 345         case SO_OOBINLINE:
 346             ret = socketGetOption(opt, null);
 347             return Boolean.valueOf(ret != -1);
 348         case SO_LINGER:
 349             ret = socketGetOption(opt, null);
 350             return (ret == -1) ? Boolean.FALSE: (Object)(ret);
 351         case SO_REUSEADDR:
 352             ret = socketGetOption(opt, null);
 353             return Boolean.valueOf(ret != -1);
 354         case SO_BINDADDR:
 355             InetAddressContainer in = new InetAddressContainer();
 356             ret = socketGetOption(opt, in);
 357             return in.addr;
 358         case SO_SNDBUF:
 359         case SO_RCVBUF:
 360             ret = socketGetOption(opt, null);
 361             return ret;
 362         case IP_TOS:
 363             try {
 364                 ret = socketGetOption(opt, null);
 365                 if (ret == -1) { // ipv6 tos
 366                     return trafficClass;
 367                 } else {
 368                     return ret;
 369                 }
 370             } catch (SocketException se) {
 371                     // TODO - should make better effort to read TOS or TCLASS
 372                     return trafficClass; // ipv6 tos
 373             }
 374         case SO_KEEPALIVE:
 375             ret = socketGetOption(opt, null);
 376             return Boolean.valueOf(ret != -1);
 377         case SO_REUSEPORT:
 378             if (!supportedOptions().contains(StandardSocketOptions.SO_REUSEPORT)) {
 379                 throw new UnsupportedOperationException("unsupported option");
 380             }
 381             ret = socketGetOption(opt, null);
 382             return Boolean.valueOf(ret != -1);
 383         // should never get here
 384         default:
 385             return null;
 386         }
 387     }
 388 
 389     static final ExtendedSocketOptions extendedOptions =
 390             ExtendedSocketOptions.getInstance();
 391 
 392     private static final Set<SocketOption<?>> clientSocketOptions = clientSocketOptions();
 393     private static final Set<SocketOption<?>> serverSocketOptions = serverSocketOptions();
 394 
 395     private static Set<SocketOption<?>> clientSocketOptions() {
 396         HashSet<SocketOption<?>> options = new HashSet<>();
 397         options.add(StandardSocketOptions.SO_KEEPALIVE);
 398         options.add(StandardSocketOptions.SO_SNDBUF);
 399         options.add(StandardSocketOptions.SO_RCVBUF);
 400         options.add(StandardSocketOptions.SO_REUSEADDR);
 401         options.add(StandardSocketOptions.SO_LINGER);
 402         options.add(StandardSocketOptions.IP_TOS);
 403         options.add(StandardSocketOptions.TCP_NODELAY);
 404         if (isReusePortAvailable())
 405             options.add(StandardSocketOptions.SO_REUSEPORT);
 406         options.addAll(ExtendedSocketOptions.clientSocketOptions());
 407         return Collections.unmodifiableSet(options);
 408     }
 409 
 410     private static Set<SocketOption<?>> serverSocketOptions() {
 411         HashSet<SocketOption<?>> options = new HashSet<>();
 412         options.add(StandardSocketOptions.SO_RCVBUF);
 413         options.add(StandardSocketOptions.SO_REUSEADDR);
 414         options.add(StandardSocketOptions.IP_TOS);
 415         if (isReusePortAvailable())
 416             options.add(StandardSocketOptions.SO_REUSEPORT);
 417         options.addAll(ExtendedSocketOptions.serverSocketOptions());
 418         return Collections.unmodifiableSet(options);
 419     }
 420 
 421     @Override
 422     protected Set<SocketOption<?>> supportedOptions() {
 423         if (isServer)
 424             return serverSocketOptions;
 425         else
 426             return clientSocketOptions;
 427     }
 428 
 429     @Override
 430     protected <T> void setOption(SocketOption<T> name, T value) throws IOException {
 431         Objects.requireNonNull(name);
 432         if (!supportedOptions().contains(name))
 433             throw new UnsupportedOperationException("'" + name + "' not supported");
 434 
 435         if (!name.type().isInstance(value))
 436             throw new IllegalArgumentException("Invalid value '" + value + "'");
 437 
 438         if (isClosedOrPending())
 439             throw new SocketException("Socket closed");
 440 
 441         if (name == StandardSocketOptions.SO_KEEPALIVE) {
 442             setOption(SocketOptions.SO_KEEPALIVE, value);
 443         } else if (name == StandardSocketOptions.SO_SNDBUF) {
 444             if (((Integer)value).intValue() < 0)
 445                 throw new IllegalArgumentException("Invalid send buffer size:" + value);
 446             setOption(SocketOptions.SO_SNDBUF, value);
 447         } else if (name == StandardSocketOptions.SO_RCVBUF) {
 448             if (((Integer)value).intValue() < 0)
 449                 throw new IllegalArgumentException("Invalid recv buffer size:" + value);
 450             setOption(SocketOptions.SO_RCVBUF, value);
 451         } else if (name == StandardSocketOptions.SO_REUSEADDR) {
 452             setOption(SocketOptions.SO_REUSEADDR, value);
 453         } else if (name == StandardSocketOptions.SO_REUSEPORT) {
 454             setOption(SocketOptions.SO_REUSEPORT, value);
 455         } else if (name == StandardSocketOptions.SO_LINGER ) {
 456             if (((Integer)value).intValue() < 0)
 457                 setOption(SocketOptions.SO_LINGER, false);
 458             else
 459                 setOption(SocketOptions.SO_LINGER, value);
 460         } else if (name == StandardSocketOptions.IP_TOS) {
 461             int i = ((Integer)value).intValue();
 462             if (i < 0 || i > 255)
 463                 throw new IllegalArgumentException("Invalid IP_TOS value: " + value);
 464             setOption(SocketOptions.IP_TOS, value);
 465         } else if (name == StandardSocketOptions.TCP_NODELAY) {
 466             setOption(SocketOptions.TCP_NODELAY, value);
 467         } else if (extendedOptions.isOptionSupported(name)) {
 468             extendedOptions.setOption(fd, name, value);
 469         } else {
 470             throw new AssertionError("unknown option: " + name);
 471         }
 472     }
 473 
 474     @Override
 475     @SuppressWarnings("unchecked")
 476     protected <T> T getOption(SocketOption<T> name) throws IOException {
 477         Objects.requireNonNull(name);
 478         if (!supportedOptions().contains(name))
 479             throw new UnsupportedOperationException("'" + name + "' not supported");
 480 
 481         if (isClosedOrPending())
 482             throw new SocketException("Socket closed");
 483 
 484         if (name == StandardSocketOptions.SO_KEEPALIVE) {
 485             return (T)getOption(SocketOptions.SO_KEEPALIVE);
 486         } else if (name == StandardSocketOptions.SO_SNDBUF) {
 487             return (T)getOption(SocketOptions.SO_SNDBUF);
 488         } else if (name == StandardSocketOptions.SO_RCVBUF) {
 489             return (T)getOption(SocketOptions.SO_RCVBUF);
 490         } else if (name == StandardSocketOptions.SO_REUSEADDR) {
 491             return (T)getOption(SocketOptions.SO_REUSEADDR);
 492         } else if (name == StandardSocketOptions.SO_REUSEPORT) {
 493             return (T)getOption(SocketOptions.SO_REUSEPORT);
 494         } else if (name == StandardSocketOptions.SO_LINGER) {
 495             Object value = getOption(SocketOptions.SO_LINGER);
 496             if (value instanceof Boolean) {
 497                 assert ((Boolean)value).booleanValue() == false;
 498                 value = -1;
 499             }
 500             return (T)value;
 501         } else if (name == StandardSocketOptions.IP_TOS) {
 502             return (T)getOption(SocketOptions.IP_TOS);
 503         } else if (name == StandardSocketOptions.TCP_NODELAY) {
 504             return (T)getOption(SocketOptions.TCP_NODELAY);
 505         } else if (extendedOptions.isOptionSupported(name)) {
 506             return (T) extendedOptions.getOption(fd, name);
 507         } else {
 508             throw new AssertionError("unknown option: " + name);
 509         }
 510     }
 511 
 512     /**
 513      * The workhorse of the connection operation.  Tries several times to
 514      * establish a connection to the given <host, port>.  If unsuccessful,
 515      * throws an IOException indicating what went wrong.
 516      */
 517 
 518     synchronized void doConnect(InetAddress address, int port, int timeout) throws IOException {
 519         synchronized (fdLock) {
 520             if (!closePending && !isBound) {
 521                 NetHooks.beforeTcpConnect(fd, address, port);
 522             }
 523         }
 524         try {
 525             acquireFD();
 526             try {
 527                 socketConnect(address, port, timeout);
 528                 /* socket may have been closed during poll/select */
 529                 synchronized (fdLock) {
 530                     if (closePending) {
 531                         throw new SocketException ("Socket closed");
 532                     }
 533                 }
 534             } finally {
 535                 releaseFD();
 536             }
 537         } catch (IOException e) {
 538             close();
 539             throw SocketExceptions.of(e, new InetSocketAddress(address, port));
 540         }
 541     }
 542 
 543     /**
 544      * Binds the socket to the specified address of the specified local port.
 545      * @param address the address
 546      * @param lport the port
 547      */
 548     protected synchronized void bind(InetAddress address, int lport)
 549         throws IOException
 550     {
 551        synchronized (fdLock) {
 552             if (!closePending && !isBound) {
 553                 NetHooks.beforeTcpBind(fd, address, lport);
 554             }
 555         }
 556         if (address.isLinkLocalAddress()) {
 557             address = IPAddressUtil.toScopedAddress(address);
 558         }
 559         socketBind(address, lport);
 560         isBound = true;
 561     }
 562 
 563     /**
 564      * Listens, for a specified amount of time, for connections.
 565      * @param count the amount of time to listen for connections
 566      */
 567     protected synchronized void listen(int count) throws IOException {
 568         socketListen(count);
 569     }
 570 
 571     /**
 572      * Accepts connections.
 573      * @param si the socket impl
 574      */
 575     protected void accept(SocketImpl si) throws IOException {
 576         si.fd = new FileDescriptor();
 577         acquireFD();
 578         try {
 579             socketAccept(si);
 580         } finally {
 581             releaseFD();
 582         }
 583         SocketCleanable.register(si.fd);
 584     }
 585 
 586     /**
 587      * Gets an InputStream for this socket.
 588      */
 589     protected synchronized InputStream getInputStream() throws IOException {
 590         synchronized (fdLock) {
 591             if (isClosedOrPending())
 592                 throw new IOException("Socket Closed");
 593             if (shut_rd)
 594                 throw new IOException("Socket input is shutdown");
 595             if (socketInputStream == null) {
 596                 PrivilegedExceptionAction<SocketInputStream> pa = () -> new SocketInputStream(this);
 597                 try {
 598                     socketInputStream = AccessController.doPrivileged(pa);
 599                 } catch (PrivilegedActionException e) {
 600                     throw (IOException) e.getCause();
 601                 }
 602             }
 603         }
 604         return socketInputStream;
 605     }
 606 
 607     void setInputStream(SocketInputStream in) {
 608         socketInputStream = in;
 609     }
 610 
 611     /**
 612      * Gets an OutputStream for this socket.
 613      */
 614     protected synchronized OutputStream getOutputStream() throws IOException {
 615         synchronized (fdLock) {
 616             if (isClosedOrPending())
 617                 throw new IOException("Socket Closed");
 618             if (shut_wr)
 619                 throw new IOException("Socket output is shutdown");
 620             if (socketOutputStream == null) {
 621                 PrivilegedExceptionAction<SocketOutputStream> pa = () -> new SocketOutputStream(this);
 622                 try {
 623                     socketOutputStream = AccessController.doPrivileged(pa);
 624                 } catch (PrivilegedActionException e) {
 625                     throw (IOException) e.getCause();
 626                 }
 627             }
 628         }
 629         return socketOutputStream;
 630     }
 631 
 632     void setFileDescriptor(FileDescriptor fd) {
 633         this.fd = fd;
 634     }
 635 
 636     void setAddress(InetAddress address) {
 637         this.address = address;
 638     }
 639 
 640     void setPort(int port) {
 641         this.port = port;
 642     }
 643 
 644     void setLocalPort(int localport) {
 645         this.localport = localport;
 646     }
 647 
 648     /**
 649      * Returns the number of bytes that can be read without blocking.
 650      */
 651     protected synchronized int available() throws IOException {
 652         if (isClosedOrPending()) {
 653             throw new IOException("Stream closed.");
 654         }
 655 
 656         /*
 657          * If connection has been reset or shut down for input, then return 0
 658          * to indicate there are no buffered bytes.
 659          */
 660         if (isConnectionReset() || shut_rd) {
 661             return 0;
 662         }
 663 
 664         /*
 665          * If no bytes available and we were previously notified
 666          * of a connection reset then we move to the reset state.
 667          *
 668          * If are notified of a connection reset then check
 669          * again if there are bytes buffered on the socket.
 670          */
 671         int n = 0;
 672         try {
 673             n = socketAvailable();
 674         } catch (ConnectionResetException exc1) {
 675             setConnectionReset();
 676         }
 677         return n;
 678     }
 679 
 680     /**
 681      * Closes the socket.
 682      */
 683     protected void close() throws IOException {
 684         synchronized(fdLock) {
 685             if (fd != null) {
 686                 if (!stream) {
 687                     ResourceManager.afterUdpClose();
 688                 }
 689                 if (fdUseCount == 0) {
 690                     if (closePending) {
 691                         return;
 692                     }
 693                     closePending = true;
 694                     /*
 695                      * We close the FileDescriptor in two-steps - first the
 696                      * "pre-close" which closes the socket but doesn't
 697                      * release the underlying file descriptor. This operation
 698                      * may be lengthy due to untransmitted data and a long
 699                      * linger interval. Once the pre-close is done we do the
 700                      * actual socket to release the fd.
 701                      */
 702                     try {
 703                         socketPreClose();
 704                     } finally {
 705                         socketClose();
 706                     }
 707                     fd = null;
 708                     return;
 709                 } else {
 710                     /*
 711                      * If a thread has acquired the fd and a close
 712                      * isn't pending then use a deferred close.
 713                      * Also decrement fdUseCount to signal the last
 714                      * thread that releases the fd to close it.
 715                      */
 716                     if (!closePending) {
 717                         closePending = true;
 718                         fdUseCount--;
 719                         socketPreClose();
 720                     }
 721                 }
 722             }
 723         }
 724     }
 725 
 726     void reset() {
 727         throw new InternalError("should not get here");
 728     }
 729 
 730     /**
 731      * Shutdown read-half of the socket connection;
 732      */
 733     protected void shutdownInput() throws IOException {
 734       if (fd != null) {
 735           socketShutdown(SHUT_RD);
 736           if (socketInputStream != null) {
 737               socketInputStream.setEOF(true);
 738           }
 739           shut_rd = true;
 740       }
 741     }
 742 
 743     /**
 744      * Shutdown write-half of the socket connection;
 745      */
 746     protected void shutdownOutput() throws IOException {
 747       if (fd != null) {
 748           socketShutdown(SHUT_WR);
 749           shut_wr = true;
 750       }
 751     }
 752 
 753     protected boolean supportsUrgentData () {
 754         return true;
 755     }
 756 
 757     protected void sendUrgentData (int data) throws IOException {
 758         if (fd == null) {
 759             throw new IOException("Socket Closed");
 760         }
 761         socketSendUrgentData (data);
 762     }
 763 
 764     /*
 765      * "Acquires" and returns the FileDescriptor for this impl
 766      *
 767      * A corresponding releaseFD is required to "release" the
 768      * FileDescriptor.
 769      */
 770     FileDescriptor acquireFD() {
 771         synchronized (fdLock) {
 772             fdUseCount++;
 773             return fd;
 774         }
 775     }
 776 
 777     /*
 778      * "Release" the FileDescriptor for this impl.
 779      *
 780      * If the use count goes to -1 then the socket is closed.
 781      */
 782     void releaseFD() {
 783         synchronized (fdLock) {
 784             fdUseCount--;
 785             if (fdUseCount == -1) {
 786                 if (fd != null) {
 787                     try {
 788                         socketClose();
 789                     } catch (IOException e) {
 790                     } finally {
 791                         fd = null;
 792                     }
 793                 }
 794             }
 795         }
 796     }
 797 
 798     boolean isConnectionReset() {
 799         return connectionReset;
 800     }
 801 
 802     void setConnectionReset() {
 803         connectionReset = true;
 804     }
 805 
 806     /*
 807      * Return true if already closed or close is pending
 808      */
 809     public boolean isClosedOrPending() {
 810         /*
 811          * Lock on fdLock to ensure that we wait if a
 812          * close is in progress.
 813          */
 814         synchronized (fdLock) {
 815             if (closePending || (fd == null)) {
 816                 return true;
 817             } else {
 818                 return false;
 819             }
 820         }
 821     }
 822 
 823     /*
 824      * Return the current value of SO_TIMEOUT
 825      */
 826     public int getTimeout() {
 827         return timeout;
 828     }
 829 
 830     /*
 831      * "Pre-close" a socket by dup'ing the file descriptor - this enables
 832      * the socket to be closed without releasing the file descriptor.
 833      */
 834     private void socketPreClose() throws IOException {
 835         socketClose0(true);
 836     }
 837 
 838     /*
 839      * Close the socket (and release the file descriptor).
 840      */
 841     protected void socketClose() throws IOException {
 842         SocketCleanable.unregister(fd);
 843         socketClose0(false);
 844     }
 845 
 846     abstract void socketCreate(boolean stream) throws IOException;
 847     abstract void socketConnect(InetAddress address, int port, int timeout)
 848         throws IOException;
 849     abstract void socketBind(InetAddress address, int port)
 850         throws IOException;
 851     abstract void socketListen(int count)
 852         throws IOException;
 853     abstract void socketAccept(SocketImpl s)
 854         throws IOException;
 855     abstract int socketAvailable()
 856         throws IOException;
 857     abstract void socketClose0(boolean useDeferredClose)
 858         throws IOException;
 859     abstract void socketShutdown(int howto)
 860         throws IOException;
 861     abstract void socketSetOption(int cmd, boolean on, Object value)
 862         throws SocketException;
 863     abstract int socketGetOption(int opt, Object iaContainerObj) throws SocketException;
 864     abstract void socketSendUrgentData(int data)
 865         throws IOException;
 866 
 867     public static final int SHUT_RD = 0;
 868     public static final int SHUT_WR = 1;
 869 
 870     private static native boolean isReusePortAvailable0();
 871 }