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