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