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