1 /*
2 * Copyright (c) 2019, 2025, 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.nio.ch;
27
28 import java.io.FileDescriptor;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.io.InterruptedIOException;
32 import java.io.OutputStream;
33 import java.io.UncheckedIOException;
34 import java.lang.ref.Cleaner.Cleanable;
35 import java.net.InetAddress;
36 import java.net.InetSocketAddress;
37 import java.net.ProtocolFamily;
38 import java.net.SocketAddress;
39 import java.net.SocketException;
40 import java.net.SocketImpl;
41 import java.net.SocketOption;
42 import java.net.SocketTimeoutException;
43 import java.net.StandardProtocolFamily;
44 import java.net.StandardSocketOptions;
45 import java.net.UnknownHostException;
46 import java.nio.ByteBuffer;
47 import java.util.Collections;
48 import java.util.HashSet;
49 import java.util.Objects;
50 import java.util.Set;
51 import java.util.concurrent.TimeUnit;
52 import java.util.concurrent.locks.ReentrantLock;
53
54 import jdk.internal.access.JavaIOFileDescriptorAccess;
55 import jdk.internal.access.SharedSecrets;
56 import jdk.internal.ref.CleanerFactory;
57 import sun.net.ConnectionResetException;
58 import sun.net.PlatformSocketImpl;
59 import sun.net.ext.ExtendedSocketOptions;
60 import jdk.internal.util.Exceptions;
61
62 import static java.util.concurrent.TimeUnit.MILLISECONDS;
63 import static java.util.concurrent.TimeUnit.NANOSECONDS;
64 import static jdk.internal.util.Exceptions.filterNonSocketInfo;
65 import static jdk.internal.util.Exceptions.formatMsg;
66
67 /**
68 * NIO based SocketImpl.
69 *
70 * The underlying socket used by this SocketImpl is initially configured blocking.
71 * If a connect, accept or read is attempted with a timeout, or a virtual
72 * thread invokes a blocking operation, then the socket is changed to non-blocking
73 * When in non-blocking mode, operations that don't complete immediately will
74 * poll the socket (or park when invoked on a virtual thread) and preserve
75 * the semantics of blocking operations.
76 */
77
78 public final class NioSocketImpl extends SocketImpl implements PlatformSocketImpl {
79 private static final NativeDispatcher nd = new SocketDispatcher();
80
81 // The maximum number of bytes to read/write per syscall to avoid needing
82 // a huge buffer from the temporary buffer cache
83 private static final int MAX_BUFFER_SIZE = 128 * 1024;
84
85 // true if this is a SocketImpl for a ServerSocket
86 private final boolean server;
87
88 // Lock held when reading (also used when accepting or connecting)
89 private final ReentrantLock readLock = new ReentrantLock();
90
91 // Lock held when writing
92 private final ReentrantLock writeLock = new ReentrantLock();
93
94 // The stateLock for read/changing state
95 private final Object stateLock = new Object();
96 private static final int ST_NEW = 0;
97 private static final int ST_UNCONNECTED = 1;
98 private static final int ST_CONNECTING = 2;
99 private static final int ST_CONNECTED = 3;
100 private static final int ST_CLOSING = 4;
101 private static final int ST_CLOSED = 5;
102 private volatile int state; // need stateLock to change
103
104 private Cleanable cleaner;
105
106 // set to true when the socket is in non-blocking mode
107 private volatile boolean nonBlocking;
108
109 // used by connect/read/write/accept, protected by stateLock
110 private long readerThread;
111 private long writerThread;
112
113 // used when SO_REUSEADDR is emulated, protected by stateLock
114 private boolean isReuseAddress;
115
116 // read or accept timeout in millis
117 private volatile int timeout;
118
119 // flags to indicate if the connection is shutdown for input and output
120 private volatile boolean isInputClosed;
121 private volatile boolean isOutputClosed;
122
123 // used by read to emulate legacy behavior, protected by readLock
124 private boolean readEOF;
125 private boolean connectionReset;
126
127 /**
128 * Creates an instance of this SocketImpl.
129 * @param server true if this is a SocketImpl for a ServerSocket
130 */
131 public NioSocketImpl(boolean server) {
132 this.server = server;
133 }
134
135 /**
136 * Returns true if the socket is open.
137 */
138 private boolean isOpen() {
139 return state < ST_CLOSING;
140 }
141
142 /**
143 * Throws SocketException if the socket is not open.
144 */
145 private void ensureOpen() throws SocketException {
146 int state = this.state;
147 if (state == ST_NEW)
148 throw new SocketException("Socket not created");
149 if (state >= ST_CLOSING)
150 throw new SocketException("Socket closed");
151 }
152
153 /**
154 * Throws SocketException if the socket is not open and connected.
155 */
156 private void ensureOpenAndConnected() throws SocketException {
157 int state = this.state;
158 if (state < ST_CONNECTED)
159 throw new SocketException("Not connected");
160 if (state > ST_CONNECTED)
161 throw new SocketException("Socket closed");
162 }
163
164 /**
165 * Disables the current thread for scheduling purposes until the
166 * socket is ready for I/O or is asynchronously closed, for up to the
167 * specified waiting time.
168 * @throws IOException if an I/O error occurs
169 */
170 private void park(FileDescriptor fd, int event, long nanos) throws IOException {
171 Thread t = Thread.currentThread();
172 if (t.isVirtual()) {
173 Poller.poll(fdVal(fd), event, nanos, this::isOpen);
174 if (t.isInterrupted()) {
175 throw new InterruptedIOException();
176 }
177 } else {
178 long millis;
179 if (nanos == 0) {
180 millis = -1;
181 } else {
182 millis = NANOSECONDS.toMillis(nanos);
183 if (nanos > MILLISECONDS.toNanos(millis)) {
184 // Round up any excess nanos to the nearest millisecond to
185 // avoid parking for less than requested.
186 millis++;
187 }
188 }
189 Net.poll(fd, event, millis);
190 }
191 }
192
193 /**
194 * Disables the current thread for scheduling purposes until the socket is
195 * ready for I/O or is asynchronously closed.
196 * @throws IOException if an I/O error occurs
197 */
198 private void park(FileDescriptor fd, int event) throws IOException {
199 park(fd, event, 0);
200 }
201
202 /**
203 * Ensures that the socket is configured non-blocking invoked on a virtual
204 * thread or the operation has a timeout
205 * @throws IOException if there is an I/O error changing the blocking mode
206 */
207 private void configureNonBlockingIfNeeded(FileDescriptor fd, boolean timed)
208 throws IOException
209 {
210 if (!nonBlocking
211 && (timed || Thread.currentThread().isVirtual())) {
212 assert readLock.isHeldByCurrentThread() || writeLock.isHeldByCurrentThread();
213 IOUtil.configureBlocking(fd, false);
214 nonBlocking = true;
215 }
216 }
217
218 /**
219 * Marks the beginning of a read operation that might block.
220 * @throws SocketException if the socket is closed or not connected
221 */
222 private FileDescriptor beginRead() throws SocketException {
223 synchronized (stateLock) {
224 ensureOpenAndConnected();
225 readerThread = NativeThread.current();
226 return fd;
227 }
228 }
229
230 /**
231 * Marks the end of a read operation that may have blocked.
232 * @throws SocketException is the socket is closed
233 */
234 private void endRead(boolean completed) throws SocketException {
235 synchronized (stateLock) {
236 readerThread = 0;
237 int state = this.state;
238 if (state == ST_CLOSING)
239 tryFinishClose();
240 if (!completed && state >= ST_CLOSING)
241 throw new SocketException("Socket closed");
242 }
243 }
244
245 /**
246 * Attempts to read bytes from the socket into the given byte array.
247 */
248 private int tryRead(FileDescriptor fd, byte[] b, int off, int len)
249 throws IOException
250 {
251 ByteBuffer dst = Util.getTemporaryDirectBuffer(len);
252 assert dst.position() == 0;
253 try {
254 int n = nd.read(fd, ((DirectBuffer)dst).address(), len);
255 if (n > 0) {
256 dst.get(b, off, n);
257 }
258 return n;
259 } finally {
260 Util.offerFirstTemporaryDirectBuffer(dst);
261 }
262 }
263
264 /**
265 * Reads bytes from the socket into the given byte array with a timeout.
266 * @throws SocketTimeoutException if the read timeout elapses
267 */
268 private int timedRead(FileDescriptor fd, byte[] b, int off, int len, long nanos)
269 throws IOException
270 {
271 long startNanos = System.nanoTime();
272 int n = tryRead(fd, b, off, len);
273 while (n == IOStatus.UNAVAILABLE && isOpen()) {
274 long remainingNanos = nanos - (System.nanoTime() - startNanos);
275 if (remainingNanos <= 0) {
276 throw new SocketTimeoutException("Read timed out");
277 }
278 park(fd, Net.POLLIN, remainingNanos);
279 n = tryRead(fd, b, off, len);
280 }
281 return n;
282 }
283
284 /**
285 * Reads bytes from the socket into the given byte array.
286 * @return the number of bytes read or -1 at EOF
287 * @throws SocketException if the socket is closed or a socket I/O error occurs
288 * @throws SocketTimeoutException if the read timeout elapses
289 */
290 private int implRead(byte[] b, int off, int len, long remainingNanos) throws IOException {
291 int n = 0;
292 SocketException ex = null;
293 FileDescriptor fd = beginRead();
294 try {
295 if (connectionReset)
296 throw new SocketException("Connection reset");
297 if (isInputClosed)
298 return -1;
299 configureNonBlockingIfNeeded(fd, remainingNanos > 0);
300 if (remainingNanos > 0) {
301 // read with timeout
302 n = timedRead(fd, b, off, len, remainingNanos);
303 } else {
304 // read, no timeout
305 n = tryRead(fd, b, off, len);
306 while (IOStatus.okayToRetry(n) && isOpen()) {
307 park(fd, Net.POLLIN);
308 n = tryRead(fd, b, off, len);
309 }
310 }
311 } catch (InterruptedIOException e) {
312 throw e;
313 } catch (ConnectionResetException e) {
314 connectionReset = true;
315 throw new SocketException("Connection reset");
316 } catch (IOException ioe) {
317 // translate to SocketException to maintain compatibility
318 ex = asSocketException(ioe);
319 } finally {
320 endRead(n > 0);
321 }
322 if (n <= 0 && isInputClosed) {
323 return -1;
324 }
325 if (ex != null) {
326 throw ex;
327 }
328 return n;
329 }
330
331 /**
332 * Reads bytes from the socket into the given byte array.
333 * @return the number of bytes read or -1 at EOF
334 * @throws IndexOutOfBoundsException if the bound checks fail
335 * @throws SocketException if the socket is closed or a socket I/O error occurs
336 * @throws SocketTimeoutException if the read timeout elapses
337 */
338 private int read(byte[] b, int off, int len) throws IOException {
339 Objects.checkFromIndexSize(off, len, b.length);
340 if (len == 0) {
341 return 0;
342 } else {
343 long remainingNanos = 0;
344 int timeout = this.timeout;
345 if (timeout > 0) {
346 remainingNanos = tryLock(readLock, timeout, MILLISECONDS);
347 if (remainingNanos <= 0) {
348 assert !readLock.isHeldByCurrentThread();
349 throw new SocketTimeoutException("Read timed out");
350 }
351 } else {
352 readLock.lock();
353 }
354 try {
355 // emulate legacy behavior to return -1, even if socket is closed
356 if (readEOF)
357 return -1;
358 // read up to MAX_BUFFER_SIZE bytes
359 int size = Math.min(len, MAX_BUFFER_SIZE);
360 int n = implRead(b, off, size, remainingNanos);
361 if (n == -1)
362 readEOF = true;
363 return n;
364 } finally {
365 readLock.unlock();
366 }
367 }
368 }
369
370 /**
371 * Marks the beginning of a write operation that might block.
372 * @throws SocketException if the socket is closed or not connected
373 */
374 private FileDescriptor beginWrite() throws SocketException {
375 synchronized (stateLock) {
376 ensureOpenAndConnected();
377 writerThread = NativeThread.current();
378 return fd;
379 }
380 }
381
382 /**
383 * Marks the end of a write operation that may have blocked.
384 * @throws SocketException is the socket is closed
385 */
386 private void endWrite(boolean completed) throws SocketException {
387 synchronized (stateLock) {
388 writerThread = 0;
389 int state = this.state;
390 if (state == ST_CLOSING)
391 tryFinishClose();
392 if (!completed && state >= ST_CLOSING)
393 throw new SocketException("Socket closed");
394 }
395 }
396
397 /**
398 * Attempts to write a sequence of bytes to the socket from the given
399 * byte array.
400 */
401 private int tryWrite(FileDescriptor fd, byte[] b, int off, int len)
402 throws IOException
403 {
404 ByteBuffer src = Util.getTemporaryDirectBuffer(len);
405 assert src.position() == 0;
406 try {
407 src.put(b, off, len);
408 return nd.write(fd, ((DirectBuffer)src).address(), len);
409 } finally {
410 Util.offerFirstTemporaryDirectBuffer(src);
411 }
412 }
413
414 /**
415 * Writes a sequence of bytes to the socket from the given byte array.
416 * @return the number of bytes written
417 * @throws SocketException if the socket is closed or a socket I/O error occurs
418 */
419 private int implWrite(byte[] b, int off, int len) throws IOException {
420 int n = 0;
421 SocketException ex = null;
422 FileDescriptor fd = beginWrite();
423 try {
424 configureNonBlockingIfNeeded(fd, false);
425 n = tryWrite(fd, b, off, len);
426 while (IOStatus.okayToRetry(n) && isOpen()) {
427 park(fd, Net.POLLOUT);
428 n = tryWrite(fd, b, off, len);
429 }
430 } catch (InterruptedIOException e) {
431 throw e;
432 } catch (IOException ioe) {
433 // translate to SocketException to maintain compatibility
434 ex = asSocketException(ioe);
435 } finally {
436 endWrite(n > 0);
437 }
438 if (ex != null) {
439 throw ex;
440 }
441 return n;
442 }
443
444 /**
445 * Writes a sequence of bytes to the socket from the given byte array.
446 * @throws SocketException if the socket is closed or a socket I/O error occurs
447 */
448 private void write(byte[] b, int off, int len) throws IOException {
449 Objects.checkFromIndexSize(off, len, b.length);
450 if (len > 0) {
451 writeLock.lock();
452 try {
453 int pos = off;
454 int end = off + len;
455 while (pos < end) {
456 // write up to MAX_BUFFER_SIZE bytes
457 int size = Math.min((end - pos), MAX_BUFFER_SIZE);
458 int n = implWrite(b, pos, size);
459 pos += n;
460 }
461 } finally {
462 writeLock.unlock();
463 }
464 }
465 }
466
467 /**
468 * Creates the socket.
469 * @param stream {@code true} for a streams socket
470 */
471 @Override
472 protected void create(boolean stream) throws IOException {
473 if (!stream) {
474 throw new IOException("Datagram socket creation not supported");
475 }
476 synchronized (stateLock) {
477 if (state != ST_NEW)
478 throw new IOException("Already created");
479 FileDescriptor fd;
480 if (server) {
481 fd = Net.serverSocket();
482 } else {
483 fd = Net.socket();
484 }
485 Runnable closer = closerFor(fd);
486 this.fd = fd;
487 this.cleaner = CleanerFactory.cleaner().register(this, closer);
488 this.state = ST_UNCONNECTED;
489 }
490 }
491
492 /**
493 * Marks the beginning of a connect operation that might block.
494 * @throws SocketException if the socket is closed or already connected
495 */
496 private FileDescriptor beginConnect(InetAddress address, int port)
497 throws IOException
498 {
499 synchronized (stateLock) {
500 int state = this.state;
501 if (state != ST_UNCONNECTED) {
502 if (state == ST_NEW)
503 throw new SocketException("Not created");
504 if (state == ST_CONNECTING)
505 throw new SocketException("Connection in progress");
506 if (state == ST_CONNECTED)
507 throw new SocketException("Already connected");
508 if (state >= ST_CLOSING)
509 throw new SocketException("Socket closed");
510 assert false;
511 }
512 this.state = ST_CONNECTING;
513
514 // save the remote address/port
515 this.address = address;
516 this.port = port;
517
518 readerThread = NativeThread.current();
519 return fd;
520 }
521 }
522
523 /**
524 * Marks the end of a connect operation that may have blocked.
525 * @throws SocketException is the socket is closed
526 */
527 private void endConnect(FileDescriptor fd, boolean completed) throws IOException {
528 synchronized (stateLock) {
529 readerThread = 0;
530 int state = this.state;
531 if (state == ST_CLOSING)
532 tryFinishClose();
533 if (completed && state == ST_CONNECTING) {
534 this.state = ST_CONNECTED;
535 localport = Net.localAddress(fd).getPort();
536 } else if (!completed && state >= ST_CLOSING) {
537 throw new SocketException("Socket closed");
538 }
539 }
540 }
541
542 /**
543 * Waits for a connection attempt to finish with a timeout
544 * @throws SocketTimeoutException if the connect timeout elapses
545 */
546 private boolean timedFinishConnect(FileDescriptor fd, long nanos) throws IOException {
547 long startNanos = System.nanoTime();
548 boolean polled = Net.pollConnectNow(fd);
549 while (!polled && isOpen()) {
550 long remainingNanos = nanos - (System.nanoTime() - startNanos);
551 if (remainingNanos <= 0) {
552 throw new SocketTimeoutException("Connect timed out");
553 }
554 park(fd, Net.POLLOUT, remainingNanos);
555 polled = Net.pollConnectNow(fd);
556 }
557 return polled && isOpen();
558 }
559
560 /**
561 * Attempts to establish a connection to the given socket address with a
562 * timeout. Closes the socket if connection cannot be established.
563 * @throws IOException if the address is not a resolved InetSocketAddress or
564 * the connection cannot be established
565 */
566 @Override
567 protected void connect(SocketAddress remote, int millis) throws IOException {
568 // SocketImpl connect only specifies IOException
569 if (!(remote instanceof InetSocketAddress))
570 throw new IOException("Unsupported address type");
571 InetSocketAddress isa = (InetSocketAddress) remote;
572 if (isa.isUnresolved()) {
573 throw new UnknownHostException(
574 formatMsg(filterNonSocketInfo(isa.getHostName())));
575 }
576
577 InetAddress address = isa.getAddress();
578 if (address.isAnyLocalAddress())
579 address = InetAddress.getLocalHost();
580 int port = isa.getPort();
581
582 ReentrantLock connectLock = readLock;
583 try {
584 connectLock.lock();
585 try {
586 boolean connected = false;
587 FileDescriptor fd = beginConnect(address, port);
588 try {
589 configureNonBlockingIfNeeded(fd, millis > 0);
590 int n = Net.connect(fd, address, port);
591 if (n > 0) {
592 // connection established
593 connected = true;
594 } else {
595 assert IOStatus.okayToRetry(n);
596 if (millis > 0) {
597 // finish connect with timeout
598 long nanos = MILLISECONDS.toNanos(millis);
599 connected = timedFinishConnect(fd, nanos);
600 } else {
601 // finish connect, no timeout
602 boolean polled = false;
603 while (!polled && isOpen()) {
604 park(fd, Net.POLLOUT);
605 polled = Net.pollConnectNow(fd);
606 }
607 connected = polled && isOpen();
608 }
609 }
610 } finally {
611 endConnect(fd, connected);
612 }
613 } finally {
614 connectLock.unlock();
615 }
616 } catch (IOException ioe) {
617 close();
618 if (ioe instanceof SocketTimeoutException) {
619 throw ioe;
620 } else if (ioe instanceof InterruptedIOException) {
621 assert Thread.currentThread().isVirtual();
622 throw new SocketException("Closed by interrupt");
623 } else {
624 throw Exceptions.ioException(ioe, isa);
625 }
626 }
627 }
628
629 @Override
630 protected void connect(String host, int port) throws IOException {
631 connect(new InetSocketAddress(host, port), 0);
632 }
633
634 @Override
635 protected void connect(InetAddress address, int port) throws IOException {
636 connect(new InetSocketAddress(address, port), 0);
637 }
638
639 @Override
640 protected void bind(InetAddress host, int port) throws IOException {
641 synchronized (stateLock) {
642 ensureOpen();
643 if (localport != 0)
644 throw new SocketException("Already bound");
645 Net.bind(fd, host, port);
646 // set the address field to the given host address to
647 // maintain long standing behavior. When binding to 0.0.0.0
648 // then the actual local address will be ::0 when IPv6 is enabled.
649 address = host;
650 localport = Net.localAddress(fd).getPort();
651 }
652 }
653
654 @Override
655 protected void listen(int backlog) throws IOException {
656 synchronized (stateLock) {
657 ensureOpen();
658 if (localport == 0)
659 throw new SocketException("Not bound");
660 Net.listen(fd, backlog < 1 ? 50 : backlog);
661 }
662 }
663
664 /**
665 * Marks the beginning of an accept operation that might block.
666 * @throws SocketException if the socket is closed
667 */
668 private FileDescriptor beginAccept() throws SocketException {
669 synchronized (stateLock) {
670 ensureOpen();
671 if (localport == 0)
672 throw new SocketException("Not bound");
673 readerThread = NativeThread.current();
674 return fd;
675 }
676 }
677
678 /**
679 * Marks the end of an accept operation that may have blocked.
680 * @throws SocketException is the socket is closed
681 */
682 private void endAccept(boolean completed) throws SocketException {
683 synchronized (stateLock) {
684 int state = this.state;
685 readerThread = 0;
686 if (state == ST_CLOSING)
687 tryFinishClose();
688 if (!completed && state >= ST_CLOSING)
689 throw new SocketException("Socket closed");
690 }
691 }
692
693 /**
694 * Accepts a new connection with a timeout.
695 * @throws SocketTimeoutException if the accept timeout elapses
696 */
697 private int timedAccept(FileDescriptor fd,
698 FileDescriptor newfd,
699 InetSocketAddress[] isaa,
700 long nanos)
701 throws IOException
702 {
703 long startNanos = System.nanoTime();
704 int n = Net.accept(fd, newfd, isaa);
705 while (n == IOStatus.UNAVAILABLE && isOpen()) {
706 long remainingNanos = nanos - (System.nanoTime() - startNanos);
707 if (remainingNanos <= 0) {
708 throw new SocketTimeoutException("Accept timed out");
709 }
710 park(fd, Net.POLLIN, remainingNanos);
711 n = Net.accept(fd, newfd, isaa);
712 }
713 return n;
714 }
715
716 /**
717 * Accepts a new connection so that the given SocketImpl is connected to
718 * the peer. The SocketImpl must be a newly created NioSocketImpl.
719 */
720 @Override
721 protected void accept(SocketImpl si) throws IOException {
722 NioSocketImpl nsi = (NioSocketImpl) si;
723 if (nsi.state != ST_NEW)
724 throw new SocketException("Not a newly created SocketImpl");
725
726 FileDescriptor newfd = new FileDescriptor();
727 InetSocketAddress[] isaa = new InetSocketAddress[1];
728
729 // acquire the lock, adjusting the timeout for cases where several
730 // threads are accepting connections and there is a timeout set
731 ReentrantLock acceptLock = readLock;
732 int timeout = this.timeout;
733 long remainingNanos = 0;
734 if (timeout > 0) {
735 remainingNanos = tryLock(acceptLock, timeout, MILLISECONDS);
736 if (remainingNanos <= 0) {
737 assert !acceptLock.isHeldByCurrentThread();
738 throw new SocketTimeoutException("Accept timed out");
739 }
740 } else {
741 acceptLock.lock();
742 }
743
744 // accept a connection
745 try {
746 int n = 0;
747 FileDescriptor fd = beginAccept();
748 try {
749 configureNonBlockingIfNeeded(fd, remainingNanos > 0);
750 if (remainingNanos > 0) {
751 // accept with timeout
752 n = timedAccept(fd, newfd, isaa, remainingNanos);
753 } else {
754 // accept, no timeout
755 n = Net.accept(fd, newfd, isaa);
756 while (IOStatus.okayToRetry(n) && isOpen()) {
757 park(fd, Net.POLLIN);
758 n = Net.accept(fd, newfd, isaa);
759 }
760 }
761 } finally {
762 endAccept(n > 0);
763 assert IOStatus.check(n);
764 }
765 } finally {
766 acceptLock.unlock();
767 }
768
769 // get local address and configure accepted socket to blocking mode
770 InetSocketAddress localAddress;
771 try {
772 localAddress = Net.localAddress(newfd);
773 IOUtil.configureBlocking(newfd, true);
774 } catch (IOException ioe) {
775 nd.close(newfd);
776 throw ioe;
777 }
778
779 // set the fields
780 Runnable closer = closerFor(newfd);
781 synchronized (nsi.stateLock) {
782 nsi.fd = newfd;
783 nsi.cleaner = CleanerFactory.cleaner().register(nsi, closer);
784 nsi.localport = localAddress.getPort();
785 nsi.address = isaa[0].getAddress();
786 nsi.port = isaa[0].getPort();
787 nsi.state = ST_CONNECTED;
788 }
789 }
790
791 @Override
792 protected InputStream getInputStream() {
793 return new InputStream() {
794 @Override
795 public int read() throws IOException {
796 byte[] a = new byte[1];
797 int n = read(a, 0, 1);
798 return (n > 0) ? (a[0] & 0xff) : -1;
799 }
800 @Override
801 public int read(byte[] b, int off, int len) throws IOException {
802 return NioSocketImpl.this.read(b, off, len);
803 }
804 @Override
805 public int available() throws IOException {
806 return NioSocketImpl.this.available();
807 }
808 @Override
809 public void close() throws IOException {
810 NioSocketImpl.this.close();
811 }
812 };
813 }
814
815 @Override
816 protected OutputStream getOutputStream() {
817 return new OutputStream() {
818 @Override
819 public void write(int b) throws IOException {
820 byte[] a = new byte[]{(byte) b};
821 write(a, 0, 1);
822 }
823 @Override
824 public void write(byte[] b, int off, int len) throws IOException {
825 NioSocketImpl.this.write(b, off, len);
826 }
827 @Override
828 public void close() throws IOException {
829 NioSocketImpl.this.close();
830 }
831 };
832 }
833
834 @Override
835 protected int available() throws IOException {
836 synchronized (stateLock) {
837 ensureOpenAndConnected();
838 if (isInputClosed) {
839 return 0;
840 } else {
841 return Net.available(fd);
842 }
843 }
844 }
845
846 /**
847 * Closes the socket if there are no I/O operations in progress.
848 */
849 private boolean tryClose() throws IOException {
850 assert Thread.holdsLock(stateLock) && state == ST_CLOSING;
851 if (readerThread == 0 && writerThread == 0) {
852 try {
853 cleaner.clean();
854 } catch (UncheckedIOException ioe) {
855 throw ioe.getCause();
856 } finally {
857 state = ST_CLOSED;
858 }
859 return true;
860 } else {
861 return false;
862 }
863 }
864
865 /**
866 * Invokes tryClose to attempt to close the socket.
867 *
868 * This method is used for deferred closing by I/O operations.
869 */
870 private void tryFinishClose() {
871 try {
872 tryClose();
873 } catch (IOException ignore) { }
874 }
875
876 /**
877 * Closes the socket. If there are I/O operations in progress then the
878 * socket is pre-closed and the threads are signalled. The socket will be
879 * closed when the last I/O operation aborts.
880 */
881 @Override
882 protected void close() throws IOException {
883 synchronized (stateLock) {
884 int state = this.state;
885 if (state >= ST_CLOSING)
886 return;
887 if (state == ST_NEW) {
888 // stillborn
889 this.state = ST_CLOSED;
890 return;
891 }
892 boolean connected = (state == ST_CONNECTED);
893 this.state = ST_CLOSING;
894
895 // shutdown output when linger interval not set to 0
896 if (connected) {
897 try {
898 var SO_LINGER = StandardSocketOptions.SO_LINGER;
899 if ((int) Net.getSocketOption(fd, SO_LINGER) != 0) {
900 Net.shutdown(fd, Net.SHUT_WR);
901 }
902 } catch (IOException ignore) { }
903 }
904
905 // attempt to close the socket. If there are I/O operations in progress
906 // then the socket is pre-closed and the thread(s) signalled. The
907 // last thread will close the file descriptor.
908 if (!tryClose()) {
909 nd.preClose(fd, readerThread, writerThread);
910 }
911 }
912 }
913
914 // the socket options supported by client and server sockets
915 private static volatile Set<SocketOption<?>> clientSocketOptions;
916 private static volatile Set<SocketOption<?>> serverSocketOptions;
917
918 @Override
919 protected Set<SocketOption<?>> supportedOptions() {
920 Set<SocketOption<?>> options = (server) ? serverSocketOptions : clientSocketOptions;
921 if (options == null) {
922 options = new HashSet<>();
923 options.add(StandardSocketOptions.SO_RCVBUF);
924 options.add(StandardSocketOptions.SO_REUSEADDR);
925 if (server) {
926 // IP_TOS added for server socket to maintain compatibility
927 options.add(StandardSocketOptions.IP_TOS);
928 options.addAll(ExtendedSocketOptions.serverSocketOptions());
929 } else {
930 options.add(StandardSocketOptions.IP_TOS);
931 options.add(StandardSocketOptions.SO_KEEPALIVE);
932 options.add(StandardSocketOptions.SO_SNDBUF);
933 options.add(StandardSocketOptions.SO_LINGER);
934 options.add(StandardSocketOptions.TCP_NODELAY);
935 options.addAll(ExtendedSocketOptions.clientSocketOptions());
936 }
937 if (Net.isReusePortAvailable())
938 options.add(StandardSocketOptions.SO_REUSEPORT);
939 options = Collections.unmodifiableSet(options);
940 if (server) {
941 serverSocketOptions = options;
942 } else {
943 clientSocketOptions = options;
944 }
945 }
946 return options;
947 }
948
949 @Override
950 protected <T> void setOption(SocketOption<T> opt, T value) throws IOException {
951 if (!supportedOptions().contains(opt))
952 throw new UnsupportedOperationException("'" + opt + "' not supported");
953 if (!opt.type().isInstance(value))
954 throw new IllegalArgumentException("Invalid value '" + value + "'");
955 synchronized (stateLock) {
956 ensureOpen();
957 if (opt == StandardSocketOptions.IP_TOS) {
958 // maps to IPV6_TCLASS and/or IP_TOS
959 Net.setIpSocketOption(fd, family(), opt, value);
960 } else if (opt == StandardSocketOptions.SO_REUSEADDR) {
961 boolean b = (boolean) value;
962 if (Net.useExclusiveBind()) {
963 isReuseAddress = b;
964 } else {
965 Net.setSocketOption(fd, opt, b);
966 }
967 } else {
968 // option does not need special handling
969 Net.setSocketOption(fd, opt, value);
970 }
971 }
972 }
973
974 @SuppressWarnings("unchecked")
975 protected <T> T getOption(SocketOption<T> opt) throws IOException {
976 if (!supportedOptions().contains(opt))
977 throw new UnsupportedOperationException("'" + opt + "' not supported");
978 synchronized (stateLock) {
979 ensureOpen();
980 if (opt == StandardSocketOptions.IP_TOS) {
981 return (T) Net.getSocketOption(fd, family(), opt);
982 } else if (opt == StandardSocketOptions.SO_REUSEADDR) {
983 if (Net.useExclusiveBind()) {
984 return (T) Boolean.valueOf(isReuseAddress);
985 } else {
986 return (T) Net.getSocketOption(fd, opt);
987 }
988 } else {
989 // option does not need special handling
990 return (T) Net.getSocketOption(fd, opt);
991 }
992 }
993 }
994
995 private boolean booleanValue(Object value, String desc) throws SocketException {
996 if (!(value instanceof Boolean))
997 throw new SocketException("Bad value for " + desc);
998 return (boolean) value;
999 }
1000
1001 private int intValue(Object value, String desc) throws SocketException {
1002 if (!(value instanceof Integer))
1003 throw new SocketException("Bad value for " + desc);
1004 return (int) value;
1005 }
1006
1007 @Override
1008 public void setOption(int opt, Object value) throws SocketException {
1009 synchronized (stateLock) {
1010 ensureOpen();
1011 try {
1012 switch (opt) {
1013 case SO_LINGER: {
1014 // the value is "false" to disable, or linger interval to enable
1015 int i;
1016 if (value instanceof Boolean && ((boolean) value) == false) {
1017 i = -1;
1018 } else {
1019 i = intValue(value, "SO_LINGER");
1020 }
1021 Net.setSocketOption(fd, StandardSocketOptions.SO_LINGER, i);
1022 break;
1023 }
1024 case SO_TIMEOUT: {
1025 int i = intValue(value, "SO_TIMEOUT");
1026 if (i < 0)
1027 throw new IllegalArgumentException("timeout < 0");
1028 timeout = i;
1029 break;
1030 }
1031 case IP_TOS: {
1032 int i = intValue(value, "IP_TOS");
1033 Net.setIpSocketOption(fd, family(), StandardSocketOptions.IP_TOS, i);
1034 break;
1035 }
1036 case TCP_NODELAY: {
1037 boolean b = booleanValue(value, "TCP_NODELAY");
1038 Net.setSocketOption(fd, StandardSocketOptions.TCP_NODELAY, b);
1039 break;
1040 }
1041 case SO_SNDBUF: {
1042 int i = intValue(value, "SO_SNDBUF");
1043 if (i <= 0)
1044 throw new SocketException("SO_SNDBUF <= 0");
1045 Net.setSocketOption(fd, StandardSocketOptions.SO_SNDBUF, i);
1046 break;
1047 }
1048 case SO_RCVBUF: {
1049 int i = intValue(value, "SO_RCVBUF");
1050 if (i <= 0)
1051 throw new SocketException("SO_RCVBUF <= 0");
1052 Net.setSocketOption(fd, StandardSocketOptions.SO_RCVBUF, i);
1053 break;
1054 }
1055 case SO_KEEPALIVE: {
1056 boolean b = booleanValue(value, "SO_KEEPALIVE");
1057 Net.setSocketOption(fd, StandardSocketOptions.SO_KEEPALIVE, b);
1058 break;
1059 }
1060 case SO_OOBINLINE: {
1061 boolean b = booleanValue(value, "SO_OOBINLINE");
1062 Net.setSocketOption(fd, ExtendedSocketOption.SO_OOBINLINE, b);
1063 break;
1064 }
1065 case SO_REUSEADDR: {
1066 boolean b = booleanValue(value, "SO_REUSEADDR");
1067 if (Net.useExclusiveBind()) {
1068 isReuseAddress = b;
1069 } else {
1070 Net.setSocketOption(fd, StandardSocketOptions.SO_REUSEADDR, b);
1071 }
1072 break;
1073 }
1074 case SO_REUSEPORT: {
1075 if (!Net.isReusePortAvailable())
1076 throw new SocketException("SO_REUSEPORT not supported");
1077 boolean b = booleanValue(value, "SO_REUSEPORT");
1078 Net.setSocketOption(fd, StandardSocketOptions.SO_REUSEPORT, b);
1079 break;
1080 }
1081 default:
1082 throw new SocketException("Unknown option " + opt);
1083 }
1084 } catch (SocketException e) {
1085 throw e;
1086 } catch (IllegalArgumentException | IOException e) {
1087 throw asSocketException(e);
1088 }
1089 }
1090 }
1091
1092 @Override
1093 public Object getOption(int opt) throws SocketException {
1094 synchronized (stateLock) {
1095 ensureOpen();
1096 try {
1097 switch (opt) {
1098 case SO_TIMEOUT:
1099 return timeout;
1100 case TCP_NODELAY:
1101 return Net.getSocketOption(fd, StandardSocketOptions.TCP_NODELAY);
1102 case SO_OOBINLINE:
1103 return Net.getSocketOption(fd, ExtendedSocketOption.SO_OOBINLINE);
1104 case SO_LINGER: {
1105 // return "false" when disabled, linger interval when enabled
1106 int i = (int) Net.getSocketOption(fd, StandardSocketOptions.SO_LINGER);
1107 if (i == -1) {
1108 return Boolean.FALSE;
1109 } else {
1110 return i;
1111 }
1112 }
1113 case SO_REUSEADDR:
1114 if (Net.useExclusiveBind()) {
1115 return isReuseAddress;
1116 } else {
1117 return Net.getSocketOption(fd, StandardSocketOptions.SO_REUSEADDR);
1118 }
1119 case SO_BINDADDR:
1120 return Net.localAddress(fd).getAddress();
1121 case SO_SNDBUF:
1122 return Net.getSocketOption(fd, StandardSocketOptions.SO_SNDBUF);
1123 case SO_RCVBUF:
1124 return Net.getSocketOption(fd, StandardSocketOptions.SO_RCVBUF);
1125 case IP_TOS:
1126 return Net.getSocketOption(fd, family(), StandardSocketOptions.IP_TOS);
1127 case SO_KEEPALIVE:
1128 return Net.getSocketOption(fd, StandardSocketOptions.SO_KEEPALIVE);
1129 case SO_REUSEPORT:
1130 if (!Net.isReusePortAvailable())
1131 throw new SocketException("SO_REUSEPORT not supported");
1132 return Net.getSocketOption(fd, StandardSocketOptions.SO_REUSEPORT);
1133 default:
1134 throw new SocketException("Unknown option " + opt);
1135 }
1136 } catch (SocketException e) {
1137 throw e;
1138 } catch (IllegalArgumentException | IOException e) {
1139 throw asSocketException(e);
1140 }
1141 }
1142 }
1143
1144 @Override
1145 protected void shutdownInput() throws IOException {
1146 synchronized (stateLock) {
1147 ensureOpenAndConnected();
1148 if (!isInputClosed) {
1149 Net.shutdown(fd, Net.SHUT_RD);
1150 if (NativeThread.isVirtualThread(readerThread)) {
1151 Poller.stopPoll(fdVal(fd), Net.POLLIN);
1152 }
1153 isInputClosed = true;
1154 }
1155 }
1156 }
1157
1158 @Override
1159 protected void shutdownOutput() throws IOException {
1160 synchronized (stateLock) {
1161 ensureOpenAndConnected();
1162 if (!isOutputClosed) {
1163 Net.shutdown(fd, Net.SHUT_WR);
1164 if (NativeThread.isVirtualThread(writerThread)) {
1165 Poller.stopPoll(fdVal(fd), Net.POLLOUT);
1166 }
1167 isOutputClosed = true;
1168 }
1169 }
1170 }
1171
1172 @Override
1173 protected boolean supportsUrgentData() {
1174 return true;
1175 }
1176
1177 @Override
1178 protected void sendUrgentData(int data) throws IOException {
1179 writeLock.lock();
1180 try {
1181 int n = 0;
1182 FileDescriptor fd = beginWrite();
1183 try {
1184 configureNonBlockingIfNeeded(fd, false);
1185 do {
1186 n = Net.sendOOB(fd, (byte) data);
1187 } while (n == IOStatus.INTERRUPTED && isOpen());
1188 if (n == IOStatus.UNAVAILABLE) {
1189 throw new SocketException("No buffer space available");
1190 }
1191 } finally {
1192 endWrite(n > 0);
1193 }
1194 } finally {
1195 writeLock.unlock();
1196 }
1197 }
1198
1199 /**
1200 * Returns an action to close the given file descriptor.
1201 */
1202 private static Runnable closerFor(FileDescriptor fd) {
1203 return () -> {
1204 try {
1205 nd.close(fd);
1206 } catch (IOException ioe) {
1207 throw new UncheckedIOException(ioe);
1208 }
1209 };
1210 }
1211
1212 /**
1213 * Attempts to acquire the given lock within the given waiting time.
1214 * @return the remaining time in nanoseconds when the lock is acquired, zero
1215 * or less if the lock was not acquired before the timeout expired
1216 */
1217 private static long tryLock(ReentrantLock lock, long timeout, TimeUnit unit) {
1218 assert timeout > 0;
1219 boolean interrupted = false;
1220 long nanos = unit.toNanos(timeout);
1221 long remainingNanos = nanos;
1222 long startNanos = System.nanoTime();
1223 boolean acquired = false;
1224 while (!acquired && (remainingNanos > 0)) {
1225 try {
1226 acquired = lock.tryLock(remainingNanos, NANOSECONDS);
1227 } catch (InterruptedException e) {
1228 interrupted = true;
1229 }
1230 remainingNanos = nanos - (System.nanoTime() - startNanos);
1231 }
1232 if (acquired && remainingNanos <= 0L)
1233 lock.unlock(); // release lock if timeout has expired
1234 if (interrupted)
1235 Thread.currentThread().interrupt();
1236 return remainingNanos;
1237 }
1238
1239 /**
1240 * Creates a SocketException from the given exception.
1241 */
1242 private static SocketException asSocketException(Exception e) {
1243 if (e instanceof SocketException se) {
1244 return se;
1245 } else {
1246 var se = new SocketException(e.getMessage());
1247 se.setStackTrace(e.getStackTrace());
1248 return se;
1249 }
1250 }
1251
1252 /**
1253 * Returns the socket protocol family.
1254 */
1255 private static ProtocolFamily family() {
1256 if (Net.isIPv6Available()) {
1257 return StandardProtocolFamily.INET6;
1258 } else {
1259 return StandardProtocolFamily.INET;
1260 }
1261 }
1262
1263 /**
1264 * Return the file descriptor value.
1265 */
1266 private static int fdVal(FileDescriptor fd) {
1267 return JIOFDA.get(fd);
1268 }
1269
1270 private static final JavaIOFileDescriptorAccess JIOFDA = SharedSecrets.getJavaIOFileDescriptorAccess();
1271 }