58680
|
1 |
/*
|
|
2 |
* Copyright (c) 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.nio.ch;
|
|
27 |
|
|
28 |
import java.io.FileDescriptor;
|
|
29 |
import java.io.IOException;
|
|
30 |
import java.io.UncheckedIOException;
|
|
31 |
import java.lang.invoke.MethodHandles;
|
|
32 |
import java.lang.invoke.VarHandle;
|
|
33 |
import java.net.DatagramPacket;
|
|
34 |
import java.net.InetAddress;
|
|
35 |
import java.net.InetSocketAddress;
|
|
36 |
import java.net.NetworkInterface;
|
|
37 |
import java.net.ProtocolFamily;
|
|
38 |
import java.net.SocketAddress;
|
|
39 |
import java.net.SocketException;
|
|
40 |
import java.net.SocketOption;
|
|
41 |
import java.net.SocketOptions;
|
|
42 |
import java.net.SocketTimeoutException;
|
|
43 |
import java.net.StandardProtocolFamily;
|
|
44 |
import java.net.StandardSocketOptions;
|
|
45 |
import java.nio.ByteBuffer;
|
|
46 |
import java.util.Collections;
|
|
47 |
import java.util.HashSet;
|
|
48 |
import java.util.Objects;
|
|
49 |
import java.util.Set;
|
|
50 |
import java.util.concurrent.locks.ReentrantLock;
|
|
51 |
import jdk.internal.ref.CleanerFactory;
|
|
52 |
import sun.net.PlatformDatagramSocketImpl;
|
|
53 |
import sun.net.ResourceManager;
|
|
54 |
import sun.net.ext.ExtendedSocketOptions;
|
|
55 |
import sun.net.util.IPAddressUtil;
|
|
56 |
import sun.security.action.GetPropertyAction;
|
|
57 |
import static java.net.StandardProtocolFamily.INET6;
|
|
58 |
import static java.util.concurrent.TimeUnit.MILLISECONDS;
|
|
59 |
import static java.util.concurrent.TimeUnit.NANOSECONDS;
|
|
60 |
|
|
61 |
/**
|
|
62 |
* A DatagramSocketImpl based on low-level NIO primitives.
|
|
63 |
*/
|
|
64 |
public class NioDatagramSocketImpl extends PlatformDatagramSocketImpl {
|
|
65 |
|
|
66 |
private static final NativeDispatcher nd = new SocketDispatcher();
|
|
67 |
|
|
68 |
private static final int MAX_PACKET_LEN = 65536;
|
|
69 |
|
|
70 |
private static final ProtocolFamily family = family();
|
|
71 |
|
|
72 |
// Lock held by current reading or connecting thread
|
|
73 |
private final ReentrantLock readLock = new ReentrantLock();
|
|
74 |
|
|
75 |
// Lock held by current writing or connecting thread
|
|
76 |
private final ReentrantLock writeLock = new ReentrantLock();
|
|
77 |
|
|
78 |
// The stateLock for read/changing state
|
|
79 |
private final Object stateLock = new Object();
|
|
80 |
private static final int ST_NEW = 0;
|
|
81 |
private static final int ST_UNCONNECTED = 1;
|
|
82 |
private static final int ST_CONNECTING = 2;
|
|
83 |
private static final int ST_CONNECTED = 3;
|
|
84 |
private static final int ST_CLOSING = 4;
|
|
85 |
private static final int ST_CLOSED = 5;
|
|
86 |
private volatile int state; // need stateLock to change
|
|
87 |
|
|
88 |
// set by create, protected by stateLock
|
|
89 |
private FileDescriptorCloser closer;
|
|
90 |
|
|
91 |
// set to true when the socket is in non-blocking mode
|
|
92 |
private volatile boolean nonBlocking;
|
|
93 |
|
|
94 |
// used by connect/read/write/accept, protected by stateLock
|
|
95 |
private long readerThread;
|
|
96 |
private long writerThread;
|
|
97 |
|
|
98 |
// Binding and remote address (when connected)
|
|
99 |
private InetSocketAddress remoteAddress;
|
|
100 |
|
|
101 |
// receive timeout in millis
|
|
102 |
private volatile int timeout;
|
|
103 |
|
|
104 |
/** Returns true if the socket is open. */
|
|
105 |
private boolean isOpen() {
|
|
106 |
return state < ST_CLOSING;
|
|
107 |
}
|
|
108 |
|
|
109 |
/** Throws SocketException if the socket is not open. */
|
|
110 |
private void ensureOpen() throws SocketException {
|
|
111 |
int state = this.state;
|
|
112 |
if (state == ST_NEW)
|
|
113 |
throw new SocketException("Socket not created");
|
|
114 |
if (state >= ST_CLOSING)
|
|
115 |
throw new SocketException("Socket closed");
|
|
116 |
}
|
|
117 |
|
|
118 |
/**
|
|
119 |
* Returns the socket protocol family.
|
|
120 |
*/
|
|
121 |
private static ProtocolFamily family() {
|
|
122 |
if (Net.isIPv6Available()) {
|
|
123 |
return StandardProtocolFamily.INET6;
|
|
124 |
} else {
|
|
125 |
return StandardProtocolFamily.INET;
|
|
126 |
}
|
|
127 |
}
|
|
128 |
|
|
129 |
@Override
|
|
130 |
protected void create() throws SocketException {
|
|
131 |
synchronized (stateLock) {
|
|
132 |
if (state != ST_NEW)
|
|
133 |
throw new SocketException("Already created");
|
|
134 |
ResourceManager.beforeUdpCreate();
|
|
135 |
FileDescriptor fd;
|
|
136 |
try {
|
|
137 |
fd = Net.socket(false);
|
|
138 |
} catch (IOException ioe) {
|
|
139 |
ResourceManager.afterUdpClose();
|
|
140 |
SocketException se = new SocketException(ioe.getMessage());
|
|
141 |
se.initCause(ioe);
|
|
142 |
throw se;
|
|
143 |
}
|
|
144 |
this.fd = fd;
|
|
145 |
this.closer = FileDescriptorCloser.create(this);
|
|
146 |
this.state = ST_UNCONNECTED;
|
|
147 |
}
|
|
148 |
}
|
|
149 |
|
|
150 |
@Override
|
|
151 |
protected void bind(int port, InetAddress addr) throws SocketException {
|
|
152 |
synchronized (stateLock) {
|
|
153 |
ensureOpen();
|
|
154 |
if (localPort != 0)
|
|
155 |
throw new SocketException("Already bound");
|
|
156 |
try {
|
|
157 |
Net.bind(fd, addr, port);
|
|
158 |
localPort = Net.localAddress(fd).getPort();
|
|
159 |
} catch (SocketException e) {
|
|
160 |
throw e;
|
|
161 |
} catch (IOException ioe) {
|
|
162 |
SocketException se = new SocketException(ioe.getMessage());
|
|
163 |
se.initCause(ioe);
|
|
164 |
throw se;
|
|
165 |
}
|
|
166 |
}
|
|
167 |
}
|
|
168 |
|
|
169 |
@SuppressWarnings("unchecked")
|
|
170 |
private static <E extends Throwable> void sneakyThrow(Throwable e) throws E {
|
|
171 |
throw (E) e;
|
|
172 |
}
|
|
173 |
|
|
174 |
@Override
|
|
175 |
protected int peek(InetAddress i) {
|
|
176 |
DatagramPacket packet = new DatagramPacket(new byte[1], 0, 1);
|
|
177 |
try {
|
|
178 |
receive(packet, true);
|
|
179 |
return packet.getPort();
|
|
180 |
} catch (IOException e) {
|
|
181 |
sneakyThrow(e);
|
|
182 |
throw new InternalError("should not reach here");
|
|
183 |
}
|
|
184 |
}
|
|
185 |
|
|
186 |
@Override
|
|
187 |
protected int peekData(DatagramPacket packet) {
|
|
188 |
try {
|
|
189 |
receive(packet, true);
|
|
190 |
return packet.getPort();
|
|
191 |
} catch (IOException e) {
|
|
192 |
sneakyThrow(e);
|
|
193 |
throw new InternalError("should not reach here");
|
|
194 |
}
|
|
195 |
}
|
|
196 |
|
|
197 |
/**
|
|
198 |
* Disables the current thread for scheduling purposes until the socket is
|
|
199 |
* ready for I/O, or is asynchronously closed, for up to the specified
|
|
200 |
* waiting time.
|
|
201 |
* @throws IOException if an I/O error occurs
|
|
202 |
*/
|
|
203 |
private void park(int event, long nanos) throws IOException {
|
|
204 |
long millis;
|
|
205 |
if (nanos == 0) {
|
|
206 |
millis = -1;
|
|
207 |
} else {
|
|
208 |
millis = NANOSECONDS.toMillis(nanos);
|
|
209 |
}
|
|
210 |
Net.poll(fd, event, millis);
|
|
211 |
}
|
|
212 |
|
|
213 |
/**
|
|
214 |
* Disables the current thread for scheduling purposes until the socket is
|
|
215 |
* ready for I/O or is asynchronously closed.
|
|
216 |
* @throws IOException if an I/O error occurs
|
|
217 |
*/
|
|
218 |
private void park(int event) throws IOException {
|
|
219 |
park(event, 0);
|
|
220 |
}
|
|
221 |
|
|
222 |
/**
|
|
223 |
* Marks the beginning of a write operation that might block.
|
|
224 |
* @throws SocketException if the socket is closed or not connected
|
|
225 |
*/
|
|
226 |
private InetSocketAddress beginWrite() throws SocketException {
|
|
227 |
synchronized (stateLock) {
|
|
228 |
ensureOpen();
|
|
229 |
writerThread = NativeThread.current();
|
|
230 |
return remoteAddress;
|
|
231 |
}
|
|
232 |
}
|
|
233 |
/**
|
|
234 |
* Marks the end of a write operation that may have blocked.
|
|
235 |
*/
|
|
236 |
private void endWrite(boolean completed) throws SocketException {
|
|
237 |
synchronized (stateLock) {
|
|
238 |
writerThread = 0;
|
|
239 |
int state = this.state;
|
|
240 |
if (state == ST_CLOSING)
|
|
241 |
tryFinishClose();
|
|
242 |
if (!completed && state >= ST_CLOSING)
|
|
243 |
throw new SocketException("Socket closed");
|
|
244 |
}
|
|
245 |
}
|
|
246 |
|
|
247 |
/**
|
|
248 |
* Attempts to send bytes from the given byte array, to the given (optional)
|
|
249 |
* address.
|
|
250 |
*/
|
|
251 |
private int trySend(byte[] b, int off, int len, InetAddress address, int port)
|
|
252 |
throws IOException
|
|
253 |
{
|
|
254 |
ByteBuffer src = Util.getTemporaryDirectBuffer(len);
|
|
255 |
assert src.position() == 0 : "Expected source position of 0, in " + src;
|
|
256 |
assert src.remaining() == len : "Expected remaining " + len + ", in " + src;
|
|
257 |
try {
|
|
258 |
src.put(b, off, len);
|
|
259 |
return send0(true, fd, ((DirectBuffer)src).address(), len, address, port);
|
|
260 |
} finally {
|
|
261 |
Util.offerFirstTemporaryDirectBuffer(src);
|
|
262 |
}
|
|
263 |
}
|
|
264 |
|
|
265 |
@Override
|
|
266 |
protected void send(DatagramPacket p) throws IOException {
|
|
267 |
Objects.requireNonNull(p);
|
|
268 |
InetSocketAddress target = Net.checkAddress(p.getSocketAddress());
|
|
269 |
byte[] b = p.getData();
|
|
270 |
int off = p.getOffset();
|
|
271 |
int len = p.getLength();
|
|
272 |
if (len > MAX_PACKET_LEN)
|
|
273 |
len = MAX_PACKET_LEN;
|
|
274 |
|
|
275 |
writeLock.lock();
|
|
276 |
try {
|
|
277 |
int n = 0;
|
|
278 |
InetAddress targetAddress = null;
|
|
279 |
int targetPort = 0;
|
|
280 |
try {
|
|
281 |
SocketAddress remote = beginWrite();
|
|
282 |
if (remote != null) {
|
|
283 |
// connected
|
|
284 |
if (!target.equals(remote)) {
|
|
285 |
String msg = "Connected address and packet address differ";
|
|
286 |
throw new IllegalArgumentException(msg);
|
|
287 |
}
|
|
288 |
} else {
|
|
289 |
// not connected
|
|
290 |
if (target.getAddress().isLinkLocalAddress())
|
|
291 |
target = IPAddressUtil.toScopedAddress(target);
|
|
292 |
targetAddress = target.getAddress();
|
|
293 |
targetPort = target.getPort();
|
|
294 |
}
|
|
295 |
n = trySend(b, off, len, targetAddress, targetPort);
|
|
296 |
while (IOStatus.okayToRetry(n) && isOpen()) {
|
|
297 |
park(Net.POLLOUT);
|
|
298 |
n = trySend(b, off, len, targetAddress, targetPort);
|
|
299 |
}
|
|
300 |
} finally {
|
|
301 |
endWrite(n > 0);
|
|
302 |
assert n >= 0;
|
|
303 |
}
|
|
304 |
} finally {
|
|
305 |
writeLock.unlock();
|
|
306 |
}
|
|
307 |
}
|
|
308 |
|
|
309 |
/**
|
|
310 |
* Configures the socket to blocking mode. This method is a no-op if the
|
|
311 |
* socket is already in blocking mode.
|
|
312 |
* @throws IOException if closed or there is an I/O error changing the mode
|
|
313 |
*/
|
|
314 |
private void configureBlocking() throws IOException {
|
|
315 |
assert readLock.isHeldByCurrentThread();
|
|
316 |
if (nonBlocking) {
|
|
317 |
synchronized (stateLock) {
|
|
318 |
ensureOpen();
|
|
319 |
IOUtil.configureBlocking(fd, true);
|
|
320 |
nonBlocking = false;
|
|
321 |
}
|
|
322 |
}
|
|
323 |
}
|
|
324 |
|
|
325 |
/**
|
|
326 |
* Configures the socket to non-blocking mode. This method is a no-op if the
|
|
327 |
* socket is already in non-blocking mode.
|
|
328 |
* @throws IOException if closed or there is an I/O error changing the mode
|
|
329 |
*/
|
|
330 |
private void configureNonBlocking() throws IOException {
|
|
331 |
assert readLock.isHeldByCurrentThread();
|
|
332 |
if (!nonBlocking) {
|
|
333 |
synchronized (stateLock) {
|
|
334 |
ensureOpen();
|
|
335 |
IOUtil.configureBlocking(fd, false);
|
|
336 |
nonBlocking = true;
|
|
337 |
}
|
|
338 |
}
|
|
339 |
}
|
|
340 |
|
|
341 |
private InetSocketAddress beginRead() throws SocketException {
|
|
342 |
synchronized (stateLock) {
|
|
343 |
ensureOpen();
|
|
344 |
readerThread = NativeThread.current();
|
|
345 |
return remoteAddress;
|
|
346 |
}
|
|
347 |
}
|
|
348 |
|
|
349 |
private void endRead(boolean completed) throws SocketException {
|
|
350 |
synchronized (stateLock) {
|
|
351 |
readerThread = 0;
|
|
352 |
int state = this.state;
|
|
353 |
if (state == ST_CLOSING)
|
|
354 |
tryFinishClose();
|
|
355 |
if (!completed && state >= ST_CLOSING)
|
|
356 |
throw new SocketException("Socket closed");
|
|
357 |
}
|
|
358 |
}
|
|
359 |
|
|
360 |
private InetSocketAddress sender = new InetSocketAddress(0); // Set by receive0
|
|
361 |
|
|
362 |
/**
|
|
363 |
* Attempts to read bytes from the socket into the given byte array.
|
|
364 |
*/
|
|
365 |
private int tryReceive(byte[] b, int off, int len, boolean isPeek)
|
|
366 |
throws IOException
|
|
367 |
{
|
|
368 |
ByteBuffer dst = Util.getTemporaryDirectBuffer(len);
|
|
369 |
assert dst.position() == 0;
|
|
370 |
assert dst.remaining() >= len;
|
|
371 |
try {
|
|
372 |
int n = receive0(fd, ((DirectBuffer)dst).address(), len, isPeek,
|
|
373 |
sender.getAddress(), sender.getPort());
|
|
374 |
assert n <= len : "received:" + n + ", expected len:" + len;
|
|
375 |
if (n > 0) {
|
|
376 |
dst.get(b, off, n);
|
|
377 |
}
|
|
378 |
return n;
|
|
379 |
} finally {
|
|
380 |
Util.offerFirstTemporaryDirectBuffer(dst);
|
|
381 |
}
|
|
382 |
}
|
|
383 |
|
|
384 |
/**
|
|
385 |
* Reads bytes from the socket into the given byte array with a timeout.
|
|
386 |
* @throws SocketTimeoutException if the read timeout elapses
|
|
387 |
*/
|
|
388 |
private int timedReceive(byte[] b, int off, int len, long nanos, boolean isPeek)
|
|
389 |
throws IOException
|
|
390 |
{
|
|
391 |
long startNanos = System.nanoTime();
|
|
392 |
int n = tryReceive(b, off, len, isPeek);
|
|
393 |
while (n == IOStatus.UNAVAILABLE && isOpen()) {
|
|
394 |
long remainingNanos = nanos - (System.nanoTime() - startNanos);
|
|
395 |
if (remainingNanos <= 0) {
|
|
396 |
throw new SocketTimeoutException("Receive timed out");
|
|
397 |
}
|
|
398 |
park(Net.POLLIN, remainingNanos);
|
|
399 |
n = tryReceive(b, off, len, isPeek);
|
|
400 |
}
|
|
401 |
return n;
|
|
402 |
}
|
|
403 |
|
|
404 |
@Override
|
|
405 |
protected void receive(DatagramPacket p) throws IOException {
|
|
406 |
receive(p, false);
|
|
407 |
}
|
|
408 |
|
|
409 |
private void receive(DatagramPacket p, boolean isPeek) throws IOException {
|
|
410 |
Objects.requireNonNull(p);
|
|
411 |
byte[] b = p.getData();
|
|
412 |
int off = p.getOffset();
|
|
413 |
int len = b.length - off;
|
|
414 |
assert len >= 0;
|
|
415 |
if (len > MAX_PACKET_LEN)
|
|
416 |
len = MAX_PACKET_LEN;
|
|
417 |
|
|
418 |
readLock.lock();
|
|
419 |
try {
|
|
420 |
int n = 0;
|
|
421 |
try {
|
|
422 |
SocketAddress remote = beginRead();
|
|
423 |
boolean connected = (remote != null);
|
|
424 |
int timeout = this.timeout;
|
|
425 |
if (timeout > 0) {
|
|
426 |
// receive with timeout
|
|
427 |
configureNonBlocking();
|
|
428 |
long nanos = MILLISECONDS.toNanos(timeout);
|
|
429 |
n = timedReceive(b, off, len, nanos, isPeek);
|
|
430 |
} else {
|
|
431 |
// receive, no timeout
|
|
432 |
n = tryReceive(b, off, len, isPeek);
|
|
433 |
while (IOStatus.okayToRetry(n) && isOpen()) {
|
|
434 |
park(Net.POLLIN);
|
|
435 |
n = tryReceive(b, off, len, isPeek);
|
|
436 |
}
|
|
437 |
}
|
|
438 |
assert n > 0;
|
|
439 |
assert sender != null;
|
|
440 |
if (p.getAddress() == null || !p.getAddress().equals(sender.getAddress()))
|
|
441 |
p.setAddress(sender.getAddress());
|
|
442 |
if (p.getPort() != sender.getPort())
|
|
443 |
p.setPort(sender.getPort());
|
|
444 |
p.setLength(n);
|
|
445 |
} catch (IOException e) {
|
|
446 |
// #### reset packet offset and length! ??
|
|
447 |
throw e;
|
|
448 |
} finally {
|
|
449 |
endRead(n > 0);
|
|
450 |
assert IOStatus.check(n);
|
|
451 |
}
|
|
452 |
} finally {
|
|
453 |
readLock.unlock();
|
|
454 |
}
|
|
455 |
}
|
|
456 |
|
|
457 |
@Override
|
|
458 |
protected void connect(InetAddress address, int port) throws SocketException {
|
|
459 |
readLock.lock();
|
|
460 |
try {
|
|
461 |
writeLock.lock();
|
|
462 |
try {
|
|
463 |
synchronized (stateLock) {
|
|
464 |
ensureOpen();
|
|
465 |
if (state == ST_CONNECTED) {
|
|
466 |
// #### already connected? throw? or connect to new remote
|
|
467 |
}
|
|
468 |
|
|
469 |
int n = Net.connect(family, fd, address, port);
|
|
470 |
if (n <= 0)
|
|
471 |
throw new InternalError("should not reach here");
|
|
472 |
|
|
473 |
remoteAddress = new InetSocketAddress(address, port);
|
|
474 |
state = ST_CONNECTED;
|
|
475 |
|
|
476 |
// refresh local address
|
|
477 |
localPort = Net.localAddress(fd).getPort();
|
|
478 |
|
|
479 |
// flush any packets already received.
|
|
480 |
try {
|
|
481 |
byte[] ba = new byte[1];
|
|
482 |
configureNonBlocking();
|
|
483 |
while (tryReceive(ba, 0, 1, false) > 0) { }
|
|
484 |
} finally {
|
|
485 |
configureBlocking();
|
|
486 |
}
|
|
487 |
}
|
|
488 |
} catch (SocketException e) {
|
|
489 |
throw e;
|
|
490 |
} catch (IOException e) {
|
|
491 |
throw new SocketException(e.getMessage());
|
|
492 |
} finally {
|
|
493 |
writeLock.unlock();
|
|
494 |
}
|
|
495 |
} finally {
|
|
496 |
readLock.unlock();
|
|
497 |
}
|
|
498 |
}
|
|
499 |
|
|
500 |
@Override
|
|
501 |
protected void disconnect() {
|
|
502 |
readLock.lock();
|
|
503 |
try {
|
|
504 |
writeLock.lock();
|
|
505 |
try {
|
|
506 |
synchronized (stateLock) {
|
|
507 |
if (!isOpen() || (state != ST_CONNECTED))
|
|
508 |
return;
|
|
509 |
|
|
510 |
try {
|
|
511 |
disconnect0(fd, family == INET6);
|
|
512 |
|
|
513 |
// no longer connected
|
|
514 |
remoteAddress = null;
|
|
515 |
state = ST_UNCONNECTED;
|
|
516 |
|
|
517 |
// check whether rebind is needed
|
|
518 |
InetSocketAddress isa = Net.localAddress(fd);
|
|
519 |
if (isa.getPort() == 0) {
|
|
520 |
// On Linux, if bound to ephemeral port,
|
|
521 |
// disconnect does not preserve that port.
|
|
522 |
// In this case, try to rebind to the previous port.
|
|
523 |
int port = localPort;
|
|
524 |
Net.bind(family, fd, isa.getAddress(), port);
|
|
525 |
isa = Net.localAddress(fd); // refresh address
|
|
526 |
assert isa.getPort() == port;
|
|
527 |
}
|
|
528 |
|
|
529 |
// refresh local port
|
|
530 |
localPort = isa.getPort();
|
|
531 |
} catch (IOException e) {
|
|
532 |
sneakyThrow(e);
|
|
533 |
throw new InternalError("should not reach here");
|
|
534 |
}
|
|
535 |
}
|
|
536 |
} finally {
|
|
537 |
writeLock.unlock();
|
|
538 |
}
|
|
539 |
} finally {
|
|
540 |
readLock.unlock();
|
|
541 |
}
|
|
542 |
}
|
|
543 |
|
|
544 |
/**
|
|
545 |
* Closes the socket if there are no I/O operations in progress.
|
|
546 |
*/
|
|
547 |
private boolean tryClose() throws IOException {
|
|
548 |
assert Thread.holdsLock(stateLock) && state == ST_CLOSING;
|
|
549 |
if (readerThread == 0 && writerThread == 0) {
|
|
550 |
try {
|
|
551 |
closer.run();
|
|
552 |
} catch (UncheckedIOException ioe) {
|
|
553 |
throw ioe.getCause();
|
|
554 |
} finally {
|
|
555 |
state = ST_CLOSED;
|
|
556 |
}
|
|
557 |
return true;
|
|
558 |
} else {
|
|
559 |
return false;
|
|
560 |
}
|
|
561 |
}
|
|
562 |
|
|
563 |
/**
|
|
564 |
* Invokes tryClose to attempt to close the socket.
|
|
565 |
*
|
|
566 |
* This method is used for deferred closing by I/O operations.
|
|
567 |
*/
|
|
568 |
private void tryFinishClose() {
|
|
569 |
try {
|
|
570 |
tryClose();
|
|
571 |
} catch (IOException ignore) { }
|
|
572 |
}
|
|
573 |
|
|
574 |
/**
|
|
575 |
* Closes the socket. If there are I/O operations in progress then the
|
|
576 |
* socket is pre-closed and the threads are signalled. The socket will be
|
|
577 |
* closed when the last I/O operation aborts.
|
|
578 |
*/
|
|
579 |
@Override
|
|
580 |
protected void close() {
|
|
581 |
synchronized (stateLock) {
|
|
582 |
int state = this.state;
|
|
583 |
if (state >= ST_CLOSING)
|
|
584 |
return;
|
|
585 |
if (state == ST_NEW) {
|
|
586 |
this.state = ST_CLOSED;
|
|
587 |
return;
|
|
588 |
}
|
|
589 |
this.state = ST_CLOSING;
|
|
590 |
|
|
591 |
// Attempt to close the socket. If there are I/O operations in
|
|
592 |
// progress then the socket is pre-closed and the thread(s)
|
|
593 |
// signalled. The last thread will close the file descriptor.
|
|
594 |
try {
|
|
595 |
if (!tryClose()) {
|
|
596 |
nd.preClose(fd);
|
|
597 |
long reader = readerThread;
|
|
598 |
if (reader != 0)
|
|
599 |
NativeThread.signal(reader);
|
|
600 |
long writer = writerThread;
|
|
601 |
if (writer != 0)
|
|
602 |
NativeThread.signal(writer);
|
|
603 |
}
|
|
604 |
} catch (IOException e) {
|
|
605 |
throw new UncheckedIOException(e); // Ugh!
|
|
606 |
}
|
|
607 |
}
|
|
608 |
}
|
|
609 |
|
|
610 |
private static final Set<SocketOption<?>> socketOptions = socketOptions();
|
|
611 |
|
|
612 |
private static Set<SocketOption<?>> socketOptions() {
|
|
613 |
HashSet<SocketOption<?>> options = new HashSet<>();
|
|
614 |
options.add(StandardSocketOptions.SO_SNDBUF);
|
|
615 |
options.add(StandardSocketOptions.SO_RCVBUF);
|
|
616 |
options.add(StandardSocketOptions.SO_REUSEADDR);
|
|
617 |
options.add(StandardSocketOptions.IP_TOS);
|
|
618 |
if (Net.isReusePortAvailable())
|
|
619 |
options.add(StandardSocketOptions.SO_REUSEPORT);
|
|
620 |
options.addAll(ExtendedSocketOptions.datagramSocketOptions());
|
|
621 |
return Collections.unmodifiableSet(options);
|
|
622 |
}
|
|
623 |
|
|
624 |
@Override
|
|
625 |
protected Set<SocketOption<?>> supportedOptions() {
|
|
626 |
return socketOptions;
|
|
627 |
}
|
|
628 |
|
|
629 |
@Override
|
|
630 |
protected <T> void setOption(SocketOption<T> opt, T value) throws IOException {
|
|
631 |
if (!supportedOptions().contains(opt))
|
|
632 |
throw new UnsupportedOperationException("'" + opt + "' not supported");
|
|
633 |
if (!opt.type().isInstance(value))
|
|
634 |
throw new IllegalArgumentException("Invalid value '" + value + "'");
|
|
635 |
synchronized (stateLock) {
|
|
636 |
ensureOpen();
|
|
637 |
if (opt == StandardSocketOptions.IP_TOS) {
|
|
638 |
// maps to IP_TOS or IPV6_TCLASS
|
|
639 |
Net.setSocketOption(fd, family(), opt, value);
|
|
640 |
} else if (opt == StandardSocketOptions.SO_REUSEADDR) {
|
|
641 |
setOption(SocketOptions.SO_REUSEADDR, value);
|
|
642 |
} else if (opt == StandardSocketOptions.SO_REUSEPORT) {
|
|
643 |
setOption(SocketOptions.SO_REUSEPORT, value);
|
|
644 |
} else {
|
|
645 |
// option does not need special handling
|
|
646 |
Net.setSocketOption(fd, opt, value);
|
|
647 |
}
|
|
648 |
}
|
|
649 |
}
|
|
650 |
|
|
651 |
@SuppressWarnings("unchecked")
|
|
652 |
@Override
|
|
653 |
protected <T> T getOption(SocketOption<T> opt) throws IOException {
|
|
654 |
if (!supportedOptions().contains(opt))
|
|
655 |
throw new UnsupportedOperationException("'" + opt + "' not supported");
|
|
656 |
synchronized (stateLock) {
|
|
657 |
ensureOpen();
|
|
658 |
if (opt == StandardSocketOptions.IP_TOS) {
|
|
659 |
return (T) Net.getSocketOption(fd, family(), opt);
|
|
660 |
} else if (opt == StandardSocketOptions.SO_REUSEADDR) {
|
|
661 |
return (T) getOption(SocketOptions.SO_REUSEADDR);
|
|
662 |
} else if (opt == StandardSocketOptions.SO_REUSEPORT) {
|
|
663 |
return (T) getOption(SocketOptions.SO_REUSEPORT);
|
|
664 |
} else {
|
|
665 |
// option does not need special handling
|
|
666 |
return (T) Net.getSocketOption(fd, opt);
|
|
667 |
}
|
|
668 |
}
|
|
669 |
}
|
|
670 |
|
|
671 |
private static boolean booleanValue(Object value, String desc)
|
|
672 |
throws SocketException
|
|
673 |
{
|
|
674 |
if (!(value instanceof Boolean))
|
|
675 |
throw new SocketException("Bad value for " + desc);
|
|
676 |
return (boolean) value;
|
|
677 |
}
|
|
678 |
|
|
679 |
private static int intValue(Object value, String desc) throws SocketException {
|
|
680 |
if (!(value instanceof Integer))
|
|
681 |
throw new SocketException("Bad value for " + desc);
|
|
682 |
return (int) value;
|
|
683 |
}
|
|
684 |
|
|
685 |
@Override
|
|
686 |
public void setOption(int opt, Object value) throws SocketException {
|
|
687 |
synchronized (stateLock) {
|
|
688 |
ensureOpen();
|
|
689 |
try {
|
|
690 |
switch (opt) {
|
|
691 |
case SO_TIMEOUT: {
|
|
692 |
int i = intValue(value, "SO_TIMEOUT");
|
|
693 |
if (i < 0)
|
|
694 |
throw new IllegalArgumentException("timeout < 0");
|
|
695 |
timeout = i;
|
|
696 |
break;
|
|
697 |
}
|
|
698 |
case IP_TOS: {
|
|
699 |
int i = intValue(value, "IP_TOS");
|
|
700 |
Net.setSocketOption(fd, family, StandardSocketOptions.IP_TOS, i);
|
|
701 |
break;
|
|
702 |
}
|
|
703 |
case SO_REUSEADDR: {
|
|
704 |
boolean b = booleanValue(value, "SO_REUSEADDR");
|
|
705 |
Net.setSocketOption(fd, StandardSocketOptions.SO_REUSEADDR, b);
|
|
706 |
break;
|
|
707 |
}
|
|
708 |
case SO_BROADCAST: {
|
|
709 |
boolean b = booleanValue(value, "SO_BROADCAST");
|
|
710 |
Net.setSocketOption(fd, StandardSocketOptions.SO_BROADCAST, b);
|
|
711 |
break;
|
|
712 |
}
|
|
713 |
case SO_BINDADDR: {
|
|
714 |
throw new SocketException("Cannot re-bind Socket");
|
|
715 |
}
|
|
716 |
case SO_RCVBUF: {
|
|
717 |
int i = intValue(value, "SO_RCVBUF");
|
|
718 |
if (i <= 0)
|
|
719 |
throw new SocketException("SO_RCVBUF <= 0");
|
|
720 |
Net.setSocketOption(fd, StandardSocketOptions.SO_RCVBUF, i);
|
|
721 |
break;
|
|
722 |
}
|
|
723 |
case SO_SNDBUF: {
|
|
724 |
int i = intValue(value, "SO_SNDBUF");
|
|
725 |
if (i <= 0)
|
|
726 |
throw new SocketException("SO_SNDBUF <= 0");
|
|
727 |
Net.setSocketOption(fd, StandardSocketOptions.SO_SNDBUF, i);
|
|
728 |
break;
|
|
729 |
}
|
|
730 |
case SO_REUSEPORT: {
|
|
731 |
if (!Net.isReusePortAvailable())
|
|
732 |
throw new UnsupportedOperationException("SO_REUSEPORT not supported");
|
|
733 |
boolean b = booleanValue(value, "SO_REUSEPORT");
|
|
734 |
Net.setSocketOption(fd, StandardSocketOptions.SO_REUSEPORT, b);
|
|
735 |
break;
|
|
736 |
}
|
|
737 |
default:
|
|
738 |
throw new SocketException("unknown option: " + opt);
|
|
739 |
}
|
|
740 |
} catch (SocketException e) {
|
|
741 |
throw e;
|
|
742 |
} catch (IllegalArgumentException | IOException e) {
|
|
743 |
throw new SocketException(e.getMessage());
|
|
744 |
}
|
|
745 |
}
|
|
746 |
}
|
|
747 |
|
|
748 |
@Override
|
|
749 |
public Object getOption(int opt) throws SocketException {
|
|
750 |
synchronized (stateLock) {
|
|
751 |
ensureOpen();
|
|
752 |
try {
|
|
753 |
switch (opt) {
|
|
754 |
case SO_TIMEOUT:
|
|
755 |
return timeout;
|
|
756 |
case IP_TOS:
|
|
757 |
return Net.getSocketOption(fd, family(), StandardSocketOptions.IP_TOS);
|
|
758 |
case SO_BINDADDR:
|
|
759 |
return Net.localAddress(fd).getAddress();
|
|
760 |
case SO_RCVBUF:
|
|
761 |
return Net.getSocketOption(fd, StandardSocketOptions.SO_RCVBUF);
|
|
762 |
case SO_SNDBUF:
|
|
763 |
return Net.getSocketOption(fd, StandardSocketOptions.SO_SNDBUF);
|
|
764 |
case SO_REUSEADDR:
|
|
765 |
return Net.getSocketOption(fd, StandardSocketOptions.SO_REUSEADDR);
|
|
766 |
case SO_BROADCAST:
|
|
767 |
return Net.getSocketOption(fd, StandardSocketOptions.SO_BROADCAST);
|
|
768 |
case SO_REUSEPORT:
|
|
769 |
if (!Net.isReusePortAvailable())
|
|
770 |
throw new UnsupportedOperationException("SO_REUSEPORT not supported");
|
|
771 |
return Net.getSocketOption(fd, StandardSocketOptions.SO_REUSEPORT);
|
|
772 |
default:
|
|
773 |
throw new SocketException("Unknown option " + opt);
|
|
774 |
}
|
|
775 |
} catch (SocketException e) {
|
|
776 |
throw e;
|
|
777 |
} catch (IllegalArgumentException | IOException e) {
|
|
778 |
throw new SocketException(e.getMessage());
|
|
779 |
}
|
|
780 |
}
|
|
781 |
}
|
|
782 |
|
|
783 |
/**
|
|
784 |
* A task that closes a DatagramSocketImpl's file descriptor. The task is
|
|
785 |
* run when the NioDatagramSocketImpl is explicitly closed or when the
|
|
786 |
* NioDatagramSocketImpl becomes phantom reachable.
|
|
787 |
*/
|
|
788 |
private static class FileDescriptorCloser implements Runnable {
|
|
789 |
private static final VarHandle CLOSED;
|
|
790 |
static {
|
|
791 |
try {
|
|
792 |
MethodHandles.Lookup l = MethodHandles.lookup();
|
|
793 |
CLOSED = l.findVarHandle(FileDescriptorCloser.class,
|
|
794 |
"closed",
|
|
795 |
boolean.class);
|
|
796 |
} catch (Exception e) {
|
|
797 |
throw new InternalError(e);
|
|
798 |
}
|
|
799 |
}
|
|
800 |
private volatile boolean closed; // accessed through VarHandle
|
|
801 |
private final FileDescriptor fd;
|
|
802 |
|
|
803 |
FileDescriptorCloser(FileDescriptor fd) { this.fd = fd; }
|
|
804 |
|
|
805 |
static FileDescriptorCloser create(NioDatagramSocketImpl impl) {
|
|
806 |
assert Thread.holdsLock(impl.stateLock);
|
|
807 |
var closer = new FileDescriptorCloser(impl.fd);
|
|
808 |
CleanerFactory.cleaner().register(impl, closer);
|
|
809 |
return closer;
|
|
810 |
}
|
|
811 |
|
|
812 |
@Override
|
|
813 |
public void run() {
|
|
814 |
if (CLOSED.compareAndSet(this, false, true)) {
|
|
815 |
try {
|
|
816 |
nd.close(fd);
|
|
817 |
} catch (IOException ioe) {
|
|
818 |
throw new UncheckedIOException(ioe);
|
|
819 |
} finally {
|
|
820 |
ResourceManager.afterUdpClose();
|
|
821 |
}
|
|
822 |
}
|
|
823 |
}
|
|
824 |
}
|
|
825 |
|
|
826 |
@Deprecated
|
|
827 |
@Override
|
|
828 |
protected void setTTL(byte ttl) {
|
|
829 |
throw new InternalError("should not reach here");
|
|
830 |
}
|
|
831 |
|
|
832 |
@Deprecated
|
|
833 |
@Override
|
|
834 |
protected byte getTTL() {
|
|
835 |
throw new InternalError("should not reach here");
|
|
836 |
}
|
|
837 |
|
|
838 |
@Override
|
|
839 |
protected void setTimeToLive(int ttl) {
|
|
840 |
throw new InternalError("should not reach here");
|
|
841 |
}
|
|
842 |
|
|
843 |
@Override
|
|
844 |
protected int getTimeToLive() {
|
|
845 |
throw new InternalError("should not reach here");
|
|
846 |
}
|
|
847 |
|
|
848 |
@Override
|
|
849 |
protected void join(InetAddress inetaddr) {
|
|
850 |
throw new InternalError("should not reach here");
|
|
851 |
}
|
|
852 |
|
|
853 |
@Override
|
|
854 |
protected void leave(InetAddress inetaddr) {
|
|
855 |
throw new InternalError("should not reach here");
|
|
856 |
}
|
|
857 |
|
|
858 |
@Override
|
|
859 |
protected void joinGroup(SocketAddress mcastaddr, NetworkInterface netIf) {
|
|
860 |
throw new InternalError("should not reach here");
|
|
861 |
}
|
|
862 |
|
|
863 |
@Override
|
|
864 |
protected void leaveGroup(SocketAddress mcastaddr, NetworkInterface netIf) {
|
|
865 |
throw new InternalError("should not reach here");
|
|
866 |
}
|
|
867 |
|
|
868 |
/** Set if the native connect() call is not to be used */
|
|
869 |
private static final boolean connectDisabled =
|
|
870 |
GetPropertyAction.privilegedGetProperty("os.name").contains("OS X");
|
|
871 |
|
|
872 |
@Override
|
|
873 |
public boolean nativeConnectDisabled() {
|
|
874 |
return connectDisabled;
|
|
875 |
}
|
|
876 |
|
|
877 |
// -- Native methods --
|
|
878 |
|
|
879 |
private static native void initIDs();
|
|
880 |
|
|
881 |
private native int receive0(FileDescriptor fd,
|
|
882 |
long address,
|
|
883 |
int len,
|
|
884 |
boolean isPeek,
|
|
885 |
InetAddress cachedSenderAddress,
|
|
886 |
int cachedSenderPort)
|
|
887 |
throws IOException;
|
|
888 |
|
|
889 |
private static native int send0(boolean preferIPv6,
|
|
890 |
FileDescriptor fd,
|
|
891 |
long address,
|
|
892 |
int len,
|
|
893 |
InetAddress addr,
|
|
894 |
int port)
|
|
895 |
throws IOException;
|
|
896 |
|
|
897 |
private static native void disconnect0(FileDescriptor fd,
|
|
898 |
boolean isIPv6)
|
|
899 |
throws IOException;
|
|
900 |
|
|
901 |
static {
|
|
902 |
IOUtil.load();
|
|
903 |
initIDs();
|
|
904 |
}
|
|
905 |
}
|