Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.base/windows/native/libnet/net_util_md.c
41119 views
1
/*
2
* Copyright (c) 1997, 2020, 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
#include "net_util.h"
26
27
#include "java_net_InetAddress.h"
28
#include "java_net_SocketOptions.h"
29
30
// Taken from mstcpip.h in Windows SDK 8.0 or newer.
31
#define SIO_LOOPBACK_FAST_PATH _WSAIOW(IOC_VENDOR,16)
32
33
#ifndef IPTOS_TOS_MASK
34
#define IPTOS_TOS_MASK 0x1e
35
#endif
36
#ifndef IPTOS_PREC_MASK
37
#define IPTOS_PREC_MASK 0xe0
38
#endif
39
40
/* true if SO_RCVTIMEO is supported */
41
jboolean isRcvTimeoutSupported = JNI_TRUE;
42
43
/*
44
* Table of Windows Sockets errors, the specific exception we
45
* throw for the error, and the error text.
46
*
47
* Note that this table excludes OS dependent errors.
48
*
49
* Latest list of Windows Sockets errors can be found at :-
50
* http://msdn.microsoft.com/library/psdk/winsock/errors_3wc2.htm
51
*/
52
static struct {
53
int errCode;
54
const char *exc;
55
const char *errString;
56
} const winsock_errors[] = {
57
{ WSAEACCES, 0, "Permission denied" },
58
{ WSAEADDRINUSE, "BindException", "Address already in use" },
59
{ WSAEADDRNOTAVAIL, "BindException", "Cannot assign requested address" },
60
{ WSAEAFNOSUPPORT, 0, "Address family not supported by protocol family" },
61
{ WSAEALREADY, 0, "Operation already in progress" },
62
{ WSAECONNABORTED, 0, "Software caused connection abort" },
63
{ WSAECONNREFUSED, "ConnectException", "Connection refused" },
64
{ WSAECONNRESET, 0, "Connection reset by peer" },
65
{ WSAEDESTADDRREQ, 0, "Destination address required" },
66
{ WSAEFAULT, 0, "Bad address" },
67
{ WSAEHOSTDOWN, 0, "Host is down" },
68
{ WSAEHOSTUNREACH, "NoRouteToHostException", "No route to host" },
69
{ WSAEINPROGRESS, 0, "Operation now in progress" },
70
{ WSAEINTR, 0, "Interrupted function call" },
71
{ WSAEINVAL, 0, "Invalid argument" },
72
{ WSAEISCONN, 0, "Socket is already connected" },
73
{ WSAEMFILE, 0, "Too many open files" },
74
{ WSAEMSGSIZE, 0, "The message is larger than the maximum supported by the underlying transport" },
75
{ WSAENETDOWN, 0, "Network is down" },
76
{ WSAENETRESET, 0, "Network dropped connection on reset" },
77
{ WSAENETUNREACH, 0, "Network is unreachable" },
78
{ WSAENOBUFS, 0, "No buffer space available (maximum connections reached?)" },
79
{ WSAENOPROTOOPT, 0, "Bad protocol option" },
80
{ WSAENOTCONN, 0, "Socket is not connected" },
81
{ WSAENOTSOCK, 0, "Socket operation on nonsocket" },
82
{ WSAEOPNOTSUPP, 0, "Operation not supported" },
83
{ WSAEPFNOSUPPORT, 0, "Protocol family not supported" },
84
{ WSAEPROCLIM, 0, "Too many processes" },
85
{ WSAEPROTONOSUPPORT, 0, "Protocol not supported" },
86
{ WSAEPROTOTYPE, 0, "Protocol wrong type for socket" },
87
{ WSAESHUTDOWN, 0, "Cannot send after socket shutdown" },
88
{ WSAESOCKTNOSUPPORT, 0, "Socket type not supported" },
89
{ WSAETIMEDOUT, "ConnectException", "Connection timed out" },
90
{ WSATYPE_NOT_FOUND, 0, "Class type not found" },
91
{ WSAEWOULDBLOCK, 0, "Resource temporarily unavailable" },
92
{ WSAHOST_NOT_FOUND, 0, "Host not found" },
93
{ WSA_NOT_ENOUGH_MEMORY, 0, "Insufficient memory available" },
94
{ WSANOTINITIALISED, 0, "Successful WSAStartup not yet performed" },
95
{ WSANO_DATA, 0, "Valid name, no data record of requested type" },
96
{ WSANO_RECOVERY, 0, "This is a nonrecoverable error" },
97
{ WSASYSNOTREADY, 0, "Network subsystem is unavailable" },
98
{ WSATRY_AGAIN, 0, "Nonauthoritative host not found" },
99
{ WSAVERNOTSUPPORTED, 0, "Winsock.dll version out of range" },
100
{ WSAEDISCON, 0, "Graceful shutdown in progress" },
101
{ WSA_OPERATION_ABORTED, 0, "Overlapped operation aborted" },
102
};
103
104
/*
105
* Initialize Windows Sockets API support
106
*/
107
BOOL WINAPI
108
DllMain(HINSTANCE hinst, DWORD reason, LPVOID reserved)
109
{
110
WSADATA wsadata;
111
112
switch (reason) {
113
case DLL_PROCESS_ATTACH:
114
if (WSAStartup(MAKEWORD(2,2), &wsadata) != 0) {
115
return FALSE;
116
}
117
break;
118
119
case DLL_PROCESS_DETACH:
120
WSACleanup();
121
break;
122
123
default:
124
break;
125
}
126
return TRUE;
127
}
128
129
void platformInit() {}
130
131
/*
132
* Since winsock doesn't have the equivalent of strerror(errno)
133
* use table to lookup error text for the error.
134
*/
135
JNIEXPORT void JNICALL
136
NET_ThrowNew(JNIEnv *env, int errorNum, char *msg)
137
{
138
int i;
139
int table_size = sizeof(winsock_errors) /
140
sizeof(winsock_errors[0]);
141
char exc[256];
142
char fullMsg[256];
143
char *excP = NULL;
144
145
/*
146
* If exception already throw then don't overwrite it.
147
*/
148
if ((*env)->ExceptionOccurred(env)) {
149
return;
150
}
151
152
/*
153
* Default message text if not provided
154
*/
155
if (!msg) {
156
msg = "no further information";
157
}
158
159
/*
160
* Check table for known winsock errors
161
*/
162
i=0;
163
while (i < table_size) {
164
if (errorNum == winsock_errors[i].errCode) {
165
break;
166
}
167
i++;
168
}
169
170
/*
171
* If found get pick the specific exception and error
172
* message corresponding to this error.
173
*/
174
if (i < table_size) {
175
excP = (char *)winsock_errors[i].exc;
176
jio_snprintf(fullMsg, sizeof(fullMsg), "%s: %s",
177
(char *)winsock_errors[i].errString, msg);
178
} else {
179
jio_snprintf(fullMsg, sizeof(fullMsg),
180
"Unrecognized Windows Sockets error: %d: %s",
181
errorNum, msg);
182
183
}
184
185
/*
186
* Throw SocketException if no specific exception for this
187
* error.
188
*/
189
if (excP == NULL) {
190
excP = "SocketException";
191
}
192
sprintf(exc, "%s%s", JNU_JAVANETPKG, excP);
193
JNU_ThrowByName(env, exc, fullMsg);
194
}
195
196
void
197
NET_ThrowCurrent(JNIEnv *env, char *msg)
198
{
199
NET_ThrowNew(env, WSAGetLastError(), msg);
200
}
201
202
void
203
NET_ThrowByNameWithLastError(JNIEnv *env, const char *name,
204
const char *defaultDetail) {
205
JNU_ThrowByNameWithMessageAndLastError(env, name, defaultDetail);
206
}
207
208
jfieldID
209
NET_GetFileDescriptorID(JNIEnv *env)
210
{
211
jclass cls = (*env)->FindClass(env, "java/io/FileDescriptor");
212
CHECK_NULL_RETURN(cls, NULL);
213
return (*env)->GetFieldID(env, cls, "fd", "I");
214
}
215
216
jint IPv4_supported()
217
{
218
/* TODO: properly check for IPv4 support on Windows */
219
return JNI_TRUE;
220
}
221
222
jint IPv6_supported()
223
{
224
SOCKET s = socket(AF_INET6, SOCK_STREAM, 0) ;
225
if (s == INVALID_SOCKET) {
226
return JNI_FALSE;
227
}
228
closesocket(s);
229
230
return JNI_TRUE;
231
}
232
233
jint reuseport_supported()
234
{
235
/* SO_REUSEPORT is not supported on Windows */
236
return JNI_FALSE;
237
}
238
239
/* call NET_MapSocketOptionV6 for the IPv6 fd only
240
* and NET_MapSocketOption for the IPv4 fd
241
*/
242
JNIEXPORT int JNICALL
243
NET_MapSocketOptionV6(jint cmd, int *level, int *optname) {
244
245
switch (cmd) {
246
case java_net_SocketOptions_IP_MULTICAST_IF:
247
case java_net_SocketOptions_IP_MULTICAST_IF2:
248
*level = IPPROTO_IPV6;
249
*optname = IPV6_MULTICAST_IF;
250
return 0;
251
252
case java_net_SocketOptions_IP_MULTICAST_LOOP:
253
*level = IPPROTO_IPV6;
254
*optname = IPV6_MULTICAST_LOOP;
255
return 0;
256
}
257
return NET_MapSocketOption (cmd, level, optname);
258
}
259
260
/*
261
* Map the Java level socket option to the platform specific
262
* level and option name.
263
*/
264
265
JNIEXPORT int JNICALL
266
NET_MapSocketOption(jint cmd, int *level, int *optname) {
267
268
typedef struct {
269
jint cmd;
270
int level;
271
int optname;
272
} sockopts;
273
274
static sockopts opts[] = {
275
{ java_net_SocketOptions_TCP_NODELAY, IPPROTO_TCP, TCP_NODELAY },
276
{ java_net_SocketOptions_SO_OOBINLINE, SOL_SOCKET, SO_OOBINLINE },
277
{ java_net_SocketOptions_SO_LINGER, SOL_SOCKET, SO_LINGER },
278
{ java_net_SocketOptions_SO_SNDBUF, SOL_SOCKET, SO_SNDBUF },
279
{ java_net_SocketOptions_SO_RCVBUF, SOL_SOCKET, SO_RCVBUF },
280
{ java_net_SocketOptions_SO_KEEPALIVE, SOL_SOCKET, SO_KEEPALIVE },
281
{ java_net_SocketOptions_SO_REUSEADDR, SOL_SOCKET, SO_REUSEADDR },
282
{ java_net_SocketOptions_SO_BROADCAST, SOL_SOCKET, SO_BROADCAST },
283
{ java_net_SocketOptions_IP_MULTICAST_IF, IPPROTO_IP, IP_MULTICAST_IF },
284
{ java_net_SocketOptions_IP_MULTICAST_LOOP, IPPROTO_IP, IP_MULTICAST_LOOP },
285
{ java_net_SocketOptions_IP_TOS, IPPROTO_IP, IP_TOS },
286
287
};
288
289
290
int i;
291
292
/*
293
* Map the Java level option to the native level
294
*/
295
for (i=0; i<(int)(sizeof(opts) / sizeof(opts[0])); i++) {
296
if (cmd == opts[i].cmd) {
297
*level = opts[i].level;
298
*optname = opts[i].optname;
299
return 0;
300
}
301
}
302
303
/* not found */
304
return -1;
305
}
306
307
308
/*
309
* Wrapper for setsockopt dealing with Windows specific issues :-
310
*
311
* IP_TOS and IP_MULTICAST_LOOP can't be set on some Windows
312
* editions.
313
*
314
* The value for the type-of-service (TOS) needs to be masked
315
* to get consistent behaviour with other operating systems.
316
*/
317
JNIEXPORT int JNICALL
318
NET_SetSockOpt(int s, int level, int optname, const void *optval,
319
int optlen)
320
{
321
int rv = 0;
322
int parg = 0;
323
int plen = sizeof(parg);
324
325
if (level == IPPROTO_IP && optname == IP_TOS) {
326
int *tos = (int *)optval;
327
*tos &= (IPTOS_TOS_MASK | IPTOS_PREC_MASK);
328
}
329
330
if (optname == SO_REUSEADDR) {
331
/*
332
* Do not set SO_REUSEADDE if SO_EXCLUSIVEADDUSE is already set
333
*/
334
rv = NET_GetSockOpt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char *)&parg, &plen);
335
if (rv == 0 && parg == 1) {
336
return rv;
337
}
338
}
339
340
rv = setsockopt(s, level, optname, optval, optlen);
341
342
if (rv == SOCKET_ERROR) {
343
/*
344
* IP_TOS & IP_MULTICAST_LOOP can't be set on some versions
345
* of Windows.
346
*/
347
if ((WSAGetLastError() == WSAENOPROTOOPT) &&
348
(level == IPPROTO_IP) &&
349
(optname == IP_TOS || optname == IP_MULTICAST_LOOP)) {
350
rv = 0;
351
}
352
353
/*
354
* IP_TOS can't be set on unbound UDP sockets.
355
*/
356
if ((WSAGetLastError() == WSAEINVAL) &&
357
(level == IPPROTO_IP) &&
358
(optname == IP_TOS)) {
359
rv = 0;
360
}
361
}
362
363
return rv;
364
}
365
366
/*
367
* Wrapper for setsockopt dealing with Windows specific issues :-
368
*
369
* IP_TOS is not supported on some versions of Windows so
370
* instead return the default value for the OS.
371
*/
372
JNIEXPORT int JNICALL
373
NET_GetSockOpt(int s, int level, int optname, void *optval,
374
int *optlen)
375
{
376
int rv;
377
378
if (level == IPPROTO_IPV6 && optname == IPV6_TCLASS) {
379
int *intopt = (int *)optval;
380
*intopt = 0;
381
*optlen = sizeof(*intopt);
382
return 0;
383
}
384
385
rv = getsockopt(s, level, optname, optval, optlen);
386
387
388
/*
389
* IPPROTO_IP/IP_TOS is not supported on some Windows
390
* editions so return the default type-of-service
391
* value.
392
*/
393
if (rv == SOCKET_ERROR) {
394
395
if (WSAGetLastError() == WSAENOPROTOOPT &&
396
level == IPPROTO_IP && optname == IP_TOS) {
397
398
*((int *)optval) = 0;
399
rv = 0;
400
}
401
}
402
403
return rv;
404
}
405
406
JNIEXPORT int JNICALL
407
NET_SocketAvailable(int s, int *pbytes) {
408
u_long arg;
409
if (ioctlsocket((SOCKET)s, FIONREAD, &arg) == SOCKET_ERROR) {
410
return -1;
411
} else {
412
*pbytes = (int) arg;
413
return 0;
414
}
415
}
416
417
/*
418
* Sets SO_ECLUSIVEADDRUSE if SO_REUSEADDR is not already set.
419
*/
420
void setExclusiveBind(int fd) {
421
int parg = 0;
422
int plen = sizeof(parg);
423
int rv = 0;
424
rv = NET_GetSockOpt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&parg, &plen);
425
if (rv == 0 && parg == 0) {
426
parg = 1;
427
rv = NET_SetSockOpt(fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char*)&parg, plen);
428
}
429
}
430
431
/*
432
* Wrapper for bind winsock call - transparent converts an
433
* error related to binding to a port that has exclusive access
434
* into an error indicating the port is in use (facilitates
435
* better error reporting).
436
*
437
* Should be only called by the wrapper method NET_WinBind
438
*/
439
JNIEXPORT int JNICALL
440
NET_Bind(int s, SOCKETADDRESS *sa, int len)
441
{
442
int rv = 0;
443
rv = bind(s, &sa->sa, len);
444
445
if (rv == SOCKET_ERROR) {
446
/*
447
* If bind fails with WSAEACCES it means that a privileged
448
* process has done an exclusive bind (NT SP4/2000/XP only).
449
*/
450
if (WSAGetLastError() == WSAEACCES) {
451
WSASetLastError(WSAEADDRINUSE);
452
}
453
}
454
455
return rv;
456
}
457
458
/*
459
* Wrapper for NET_Bind call. Sets SO_EXCLUSIVEADDRUSE
460
* if required, and then calls NET_BIND
461
*/
462
JNIEXPORT int JNICALL
463
NET_WinBind(int s, SOCKETADDRESS *sa, int len, jboolean exclBind)
464
{
465
if (exclBind == JNI_TRUE)
466
setExclusiveBind(s);
467
return NET_Bind(s, sa, len);
468
}
469
470
JNIEXPORT int JNICALL
471
NET_SocketClose(int fd) {
472
struct linger l = {0, 0};
473
int ret = 0;
474
int len = sizeof (l);
475
if (getsockopt(fd, SOL_SOCKET, SO_LINGER, (char *)&l, &len) == 0) {
476
if (l.l_onoff == 0) {
477
shutdown(fd, SD_SEND);
478
}
479
}
480
ret = closesocket (fd);
481
return ret;
482
}
483
484
JNIEXPORT int JNICALL
485
NET_Timeout(int fd, long timeout) {
486
int ret;
487
fd_set tbl;
488
struct timeval t;
489
t.tv_sec = timeout / 1000;
490
t.tv_usec = (timeout % 1000) * 1000;
491
FD_ZERO(&tbl);
492
FD_SET(fd, &tbl);
493
ret = select (fd + 1, &tbl, 0, 0, &t);
494
return ret;
495
}
496
497
498
/*
499
* differs from NET_Timeout() as follows:
500
*
501
* If timeout = -1, it blocks forever.
502
*
503
* returns 1 or 2 depending if only one or both sockets
504
* fire at same time.
505
*
506
* *fdret is (one of) the active fds. If both sockets
507
* fire at same time, *fdret = fd always.
508
*/
509
JNIEXPORT int JNICALL
510
NET_Timeout2(int fd, int fd1, long timeout, int *fdret) {
511
int ret;
512
fd_set tbl;
513
struct timeval t, *tP = &t;
514
if (timeout == -1) {
515
tP = 0;
516
} else {
517
t.tv_sec = timeout / 1000;
518
t.tv_usec = (timeout % 1000) * 1000;
519
}
520
FD_ZERO(&tbl);
521
FD_SET(fd, &tbl);
522
FD_SET(fd1, &tbl);
523
ret = select (0, &tbl, 0, 0, tP);
524
switch (ret) {
525
case 0:
526
return 0; /* timeout */
527
case 1:
528
if (FD_ISSET (fd, &tbl)) {
529
*fdret= fd;
530
} else {
531
*fdret= fd1;
532
}
533
return 1;
534
case 2:
535
*fdret= fd;
536
return 2;
537
}
538
return -1;
539
}
540
541
542
void dumpAddr (char *str, void *addr) {
543
struct sockaddr_in6 *a = (struct sockaddr_in6 *)addr;
544
int family = a->sin6_family;
545
printf ("%s\n", str);
546
if (family == AF_INET) {
547
struct sockaddr_in *him = (struct sockaddr_in *)addr;
548
printf ("AF_INET: port %d: %x\n", ntohs(him->sin_port),
549
ntohl(him->sin_addr.s_addr));
550
} else {
551
int i;
552
struct in6_addr *in = &a->sin6_addr;
553
printf ("AF_INET6 ");
554
printf ("port %d ", ntohs (a->sin6_port));
555
printf ("flow %d ", a->sin6_flowinfo);
556
printf ("addr ");
557
for (i=0; i<7; i++) {
558
printf ("%04x:", ntohs(in->s6_words[i]));
559
}
560
printf ("%04x", ntohs(in->s6_words[7]));
561
printf (" scope %d\n", a->sin6_scope_id);
562
}
563
}
564
565
/* Macro, which cleans-up the iv6bind structure,
566
* closes the two sockets (if open),
567
* and returns SOCKET_ERROR. Used in NET_BindV6 only.
568
*/
569
570
#define CLOSE_SOCKETS_AND_RETURN do { \
571
if (fd != -1) { \
572
closesocket (fd); \
573
fd = -1; \
574
} \
575
if (ofd != -1) { \
576
closesocket (ofd); \
577
ofd = -1; \
578
} \
579
if (close_fd != -1) { \
580
closesocket (close_fd); \
581
close_fd = -1; \
582
} \
583
if (close_ofd != -1) { \
584
closesocket (close_ofd); \
585
close_ofd = -1; \
586
} \
587
b->ipv4_fd = b->ipv6_fd = -1; \
588
return SOCKET_ERROR; \
589
} while(0)
590
591
/*
592
* if ipv6 is available, call NET_BindV6 to bind to the required address/port.
593
* Because the same port number may need to be reserved in both v4 and v6 space,
594
* this may require socket(s) to be re-opened. Therefore, all of this information
595
* is passed in and returned through the ipv6bind structure.
596
*
597
* If the request is to bind to a specific address, then this (by definition) means
598
* only bind in either v4 or v6, and this is just the same as normal. ie. a single
599
* call to bind() will suffice. The other socket is closed in this case.
600
*
601
* The more complicated case is when the requested address is ::0 or 0.0.0.0.
602
*
603
* Two further cases:
604
* 2. If the requested port is 0 (ie. any port) then we try to bind in v4 space
605
* first with a wild-card port argument. We then try to bind in v6 space
606
* using the returned port number. If this fails, we repeat the process
607
* until a free port common to both spaces becomes available.
608
*
609
* 3. If the requested port is a specific port, then we just try to get that
610
* port in both spaces, and if it is not free in both, then the bind fails.
611
*
612
* On failure, sockets are closed and an error returned with CLOSE_SOCKETS_AND_RETURN
613
*/
614
615
JNIEXPORT int JNICALL
616
NET_BindV6(struct ipv6bind *b, jboolean exclBind) {
617
int fd=-1, ofd=-1, rv, len;
618
/* need to defer close until new sockets created */
619
int close_fd=-1, close_ofd=-1;
620
SOCKETADDRESS oaddr; /* other address to bind */
621
int family = b->addr->sa.sa_family;
622
int ofamily;
623
u_short port; /* requested port parameter */
624
u_short bound_port;
625
626
if (family == AF_INET && (b->addr->sa4.sin_addr.s_addr != INADDR_ANY)) {
627
/* bind to v4 only */
628
int ret;
629
ret = NET_WinBind((int)b->ipv4_fd, b->addr,
630
sizeof(SOCKETADDRESS), exclBind);
631
if (ret == SOCKET_ERROR) {
632
CLOSE_SOCKETS_AND_RETURN;
633
}
634
closesocket (b->ipv6_fd);
635
b->ipv6_fd = -1;
636
return 0;
637
}
638
if (family == AF_INET6 && (!IN6_IS_ADDR_ANY(&b->addr->sa6.sin6_addr))) {
639
/* bind to v6 only */
640
int ret;
641
ret = NET_WinBind((int)b->ipv6_fd, b->addr,
642
sizeof(SOCKETADDRESS), exclBind);
643
if (ret == SOCKET_ERROR) {
644
CLOSE_SOCKETS_AND_RETURN;
645
}
646
closesocket (b->ipv4_fd);
647
b->ipv4_fd = -1;
648
return 0;
649
}
650
651
/* We need to bind on both stacks, with the same port number */
652
653
memset (&oaddr, 0, sizeof(oaddr));
654
if (family == AF_INET) {
655
ofamily = AF_INET6;
656
fd = (int)b->ipv4_fd;
657
ofd = (int)b->ipv6_fd;
658
port = (u_short)GET_PORT (b->addr);
659
IN6ADDR_SETANY(&oaddr.sa6);
660
oaddr.sa6.sin6_port = port;
661
} else {
662
ofamily = AF_INET;
663
ofd = (int)b->ipv4_fd;
664
fd = (int)b->ipv6_fd;
665
port = (u_short)GET_PORT (b->addr);
666
oaddr.sa4.sin_family = AF_INET;
667
oaddr.sa4.sin_port = port;
668
oaddr.sa4.sin_addr.s_addr = INADDR_ANY;
669
}
670
671
rv = NET_WinBind(fd, b->addr, sizeof(SOCKETADDRESS), exclBind);
672
if (rv == SOCKET_ERROR) {
673
CLOSE_SOCKETS_AND_RETURN;
674
}
675
676
/* get the port and set it in the other address */
677
len = sizeof(SOCKETADDRESS);
678
if (getsockname(fd, (struct sockaddr *)b->addr, &len) == -1) {
679
CLOSE_SOCKETS_AND_RETURN;
680
}
681
bound_port = GET_PORT (b->addr);
682
SET_PORT (&oaddr, bound_port);
683
if ((rv = NET_WinBind(ofd, &oaddr,
684
sizeof(SOCKETADDRESS), exclBind)) == SOCKET_ERROR) {
685
int retries;
686
int sotype, arglen=sizeof(sotype);
687
688
/* no retries unless, the request was for any free port */
689
690
if (port != 0) {
691
CLOSE_SOCKETS_AND_RETURN;
692
}
693
694
getsockopt(fd, SOL_SOCKET, SO_TYPE, (void *)&sotype, &arglen);
695
696
#define SOCK_RETRIES 50
697
/* 50 is an arbitrary limit, just to ensure that this
698
* cannot be an endless loop. Would expect socket creation to
699
* succeed sooner.
700
*/
701
for (retries = 0; retries < SOCK_RETRIES; retries ++) {
702
int len;
703
close_fd = fd; fd = -1;
704
close_ofd = ofd; ofd = -1;
705
b->ipv4_fd = SOCKET_ERROR;
706
b->ipv6_fd = SOCKET_ERROR;
707
708
/* create two new sockets */
709
fd = (int)socket (family, sotype, 0);
710
if (fd == SOCKET_ERROR) {
711
CLOSE_SOCKETS_AND_RETURN;
712
}
713
ofd = (int)socket (ofamily, sotype, 0);
714
if (ofd == SOCKET_ERROR) {
715
CLOSE_SOCKETS_AND_RETURN;
716
}
717
718
/* bind random port on first socket */
719
SET_PORT (&oaddr, 0);
720
rv = NET_WinBind(ofd, &oaddr, sizeof(SOCKETADDRESS), exclBind);
721
if (rv == SOCKET_ERROR) {
722
CLOSE_SOCKETS_AND_RETURN;
723
}
724
/* close the original pair of sockets before continuing */
725
closesocket (close_fd);
726
closesocket (close_ofd);
727
close_fd = close_ofd = -1;
728
729
/* bind new port on second socket */
730
len = sizeof(SOCKETADDRESS);
731
if (getsockname(ofd, &oaddr.sa, &len) == -1) {
732
CLOSE_SOCKETS_AND_RETURN;
733
}
734
bound_port = GET_PORT (&oaddr);
735
SET_PORT (b->addr, bound_port);
736
rv = NET_WinBind(fd, b->addr, sizeof(SOCKETADDRESS), exclBind);
737
738
if (rv != SOCKET_ERROR) {
739
if (family == AF_INET) {
740
b->ipv4_fd = fd;
741
b->ipv6_fd = ofd;
742
} else {
743
b->ipv4_fd = ofd;
744
b->ipv6_fd = fd;
745
}
746
return 0;
747
}
748
}
749
CLOSE_SOCKETS_AND_RETURN;
750
}
751
return 0;
752
}
753
754
/**
755
* Enables SIO_LOOPBACK_FAST_PATH
756
*/
757
JNIEXPORT jint JNICALL
758
NET_EnableFastTcpLoopback(int fd) {
759
int enabled = 1;
760
DWORD result_byte_count = -1;
761
int result = WSAIoctl(fd,
762
SIO_LOOPBACK_FAST_PATH,
763
&enabled,
764
sizeof(enabled),
765
NULL,
766
0,
767
&result_byte_count,
768
NULL,
769
NULL);
770
return result == SOCKET_ERROR ? WSAGetLastError() : 0;
771
}
772
773
int
774
IsWindows10RS3OrGreater() {
775
OSVERSIONINFOEXW osvi = { sizeof(osvi), 0, 0, 0, 0, {0}, 0, 0 };
776
DWORDLONG const cond_mask = VerSetConditionMask(
777
VerSetConditionMask(
778
VerSetConditionMask(
779
0, VER_MAJORVERSION, VER_GREATER_EQUAL),
780
VER_MINORVERSION, VER_GREATER_EQUAL),
781
VER_BUILDNUMBER, VER_GREATER_EQUAL);
782
783
osvi.dwMajorVersion = HIBYTE(_WIN32_WINNT_WIN10);
784
osvi.dwMinorVersion = LOBYTE(_WIN32_WINNT_WIN10);
785
osvi.dwBuildNumber = 16299; // RS3 (Redstone 3)
786
787
return VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_BUILDNUMBER, cond_mask) != 0;
788
}
789
790
/**
791
* Shortens the default Windows socket
792
* connect timeout. Recommended for usage
793
* on the loopback adapter only.
794
*/
795
JNIEXPORT jint JNICALL
796
NET_EnableFastTcpLoopbackConnect(int fd) {
797
TCP_INITIAL_RTO_PARAMETERS rto = {
798
TCP_INITIAL_RTO_UNSPECIFIED_RTT, // Use the default or overriden by the Administrator
799
1 // Minimum possible value before Windows 10 RS3
800
};
801
802
/**
803
* In Windows 10 RS3+ we can use the no retransmissions flag to
804
* completely remove the timeout delay, which is fixed to 500ms
805
* if Windows receives RST when the destination port is not open.
806
*/
807
if (IsWindows10RS3OrGreater()) {
808
rto.MaxSynRetransmissions = TCP_INITIAL_RTO_NO_SYN_RETRANSMISSIONS;
809
}
810
811
DWORD result_byte_count = -1;
812
int result = WSAIoctl(fd, // descriptor identifying a socket
813
SIO_TCP_INITIAL_RTO, // dwIoControlCode
814
&rto, // pointer to TCP_INITIAL_RTO_PARAMETERS structure
815
sizeof(rto), // size, in bytes, of the input buffer
816
NULL, // pointer to output buffer
817
0, // size of output buffer
818
&result_byte_count, // number of bytes returned
819
NULL, // OVERLAPPED structure
820
NULL); // completion routine
821
return (result == SOCKET_ERROR) ? WSAGetLastError() : 0;
822
}
823
824
/**
825
* See net_util.h for documentation
826
*/
827
JNIEXPORT int JNICALL
828
NET_InetAddressToSockaddr(JNIEnv *env, jobject iaObj, int port,
829
SOCKETADDRESS *sa, int *len,
830
jboolean v4MappedAddress)
831
{
832
jint family = getInetAddress_family(env, iaObj);
833
JNU_CHECK_EXCEPTION_RETURN(env, -1);
834
memset((char *)sa, 0, sizeof(SOCKETADDRESS));
835
836
if (ipv6_available() &&
837
!(family == java_net_InetAddress_IPv4 &&
838
v4MappedAddress == JNI_FALSE))
839
{
840
jbyte caddr[16];
841
jint address;
842
unsigned int scopeid = 0;
843
844
if (family == java_net_InetAddress_IPv4) {
845
// convert to IPv4-mapped address
846
memset((char *)caddr, 0, 16);
847
address = getInetAddress_addr(env, iaObj);
848
JNU_CHECK_EXCEPTION_RETURN(env, -1);
849
if (address == INADDR_ANY) {
850
/* we would always prefer IPv6 wildcard address
851
* caddr[10] = 0xff;
852
* caddr[11] = 0xff; */
853
} else {
854
caddr[10] = 0xff;
855
caddr[11] = 0xff;
856
caddr[12] = ((address >> 24) & 0xff);
857
caddr[13] = ((address >> 16) & 0xff);
858
caddr[14] = ((address >> 8) & 0xff);
859
caddr[15] = (address & 0xff);
860
}
861
} else {
862
getInet6Address_ipaddress(env, iaObj, (char *)caddr);
863
scopeid = getInet6Address_scopeid(env, iaObj);
864
}
865
sa->sa6.sin6_port = (u_short)htons((u_short)port);
866
memcpy((void *)&sa->sa6.sin6_addr, caddr, sizeof(struct in6_addr));
867
sa->sa6.sin6_family = AF_INET6;
868
sa->sa6.sin6_scope_id = scopeid;
869
if (len != NULL) {
870
*len = sizeof(struct sockaddr_in6);
871
}
872
} else {
873
jint address;
874
if (family != java_net_InetAddress_IPv4) {
875
JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "Protocol family unavailable");
876
return -1;
877
}
878
address = getInetAddress_addr(env, iaObj);
879
JNU_CHECK_EXCEPTION_RETURN(env, -1);
880
sa->sa4.sin_port = htons((short)port);
881
sa->sa4.sin_addr.s_addr = (u_long)htonl(address);
882
sa->sa4.sin_family = AF_INET;
883
if (len != NULL) {
884
*len = sizeof(struct sockaddr_in);
885
}
886
}
887
return 0;
888
}
889
890
int
891
NET_IsIPv4Mapped(jbyte* caddr) {
892
int i;
893
for (i = 0; i < 10; i++) {
894
if (caddr[i] != 0x00) {
895
return 0; /* false */
896
}
897
}
898
899
if (((caddr[10] & 0xff) == 0xff) && ((caddr[11] & 0xff) == 0xff)) {
900
return 1; /* true */
901
}
902
return 0; /* false */
903
}
904
905
int
906
NET_IPv4MappedToIPv4(jbyte* caddr) {
907
return ((caddr[12] & 0xff) << 24) | ((caddr[13] & 0xff) << 16) | ((caddr[14] & 0xff) << 8)
908
| (caddr[15] & 0xff);
909
}
910
911
int
912
NET_IsEqual(jbyte* caddr1, jbyte* caddr2) {
913
int i;
914
for (i = 0; i < 16; i++) {
915
if (caddr1[i] != caddr2[i]) {
916
return 0; /* false */
917
}
918
}
919
return 1;
920
}
921
922
/**
923
* Wrapper for select/poll with timeout on a single file descriptor.
924
*
925
* flags (defined in net_util_md.h can be any combination of
926
* NET_WAIT_READ, NET_WAIT_WRITE & NET_WAIT_CONNECT.
927
*
928
* The function will return when either the socket is ready for one
929
* of the specified operation or the timeout expired.
930
*
931
* It returns the time left from the timeout, or -1 if it expired.
932
*/
933
934
jint
935
NET_Wait(JNIEnv *env, jint fd, jint flags, jint timeout)
936
{
937
jlong prevTime = JVM_CurrentTimeMillis(env, 0);
938
jint read_rv;
939
940
while (1) {
941
jlong newTime;
942
fd_set rd, wr, ex;
943
struct timeval t;
944
945
t.tv_sec = timeout / 1000;
946
t.tv_usec = (timeout % 1000) * 1000;
947
948
FD_ZERO(&rd);
949
FD_ZERO(&wr);
950
FD_ZERO(&ex);
951
if (flags & NET_WAIT_READ) {
952
FD_SET(fd, &rd);
953
}
954
if (flags & NET_WAIT_WRITE) {
955
FD_SET(fd, &wr);
956
}
957
if (flags & NET_WAIT_CONNECT) {
958
FD_SET(fd, &wr);
959
FD_SET(fd, &ex);
960
}
961
962
errno = 0;
963
read_rv = select(fd+1, &rd, &wr, &ex, &t);
964
965
newTime = JVM_CurrentTimeMillis(env, 0);
966
timeout -= (jint)(newTime - prevTime);
967
if (timeout <= 0) {
968
return read_rv > 0 ? 0 : -1;
969
}
970
newTime = prevTime;
971
972
if (read_rv > 0) {
973
break;
974
}
975
976
977
} /* while */
978
979
return timeout;
980
}
981
982
int NET_Socket (int domain, int type, int protocol) {
983
SOCKET sock;
984
sock = socket (domain, type, protocol);
985
if (sock != INVALID_SOCKET) {
986
SetHandleInformation((HANDLE)(uintptr_t)sock, HANDLE_FLAG_INHERIT, FALSE);
987
}
988
return (int)sock;
989
}
990
991