Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.base/share/classes/sun/net/util/IPAddressUtil.java
41159 views
1
/*
2
* Copyright (c) 2004, 2021, 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.net.util;
27
28
import java.io.IOException;
29
import java.io.UncheckedIOException;
30
import java.net.Inet6Address;
31
import java.net.InetAddress;
32
import java.net.InetSocketAddress;
33
import java.net.NetworkInterface;
34
import java.net.SocketException;
35
import java.net.URL;
36
import java.security.AccessController;
37
import java.security.PrivilegedExceptionAction;
38
import java.security.PrivilegedActionException;
39
import java.util.Arrays;
40
import java.util.List;
41
import java.util.concurrent.ConcurrentHashMap;
42
43
public class IPAddressUtil {
44
private static final int INADDR4SZ = 4;
45
private static final int INADDR16SZ = 16;
46
private static final int INT16SZ = 2;
47
48
/*
49
* Converts IPv4 address in its textual presentation form
50
* into its numeric binary form.
51
*
52
* @param src a String representing an IPv4 address in standard format
53
* @return a byte array representing the IPv4 numeric address
54
*/
55
@SuppressWarnings("fallthrough")
56
public static byte[] textToNumericFormatV4(String src)
57
{
58
byte[] res = new byte[INADDR4SZ];
59
60
long tmpValue = 0;
61
int currByte = 0;
62
boolean newOctet = true;
63
64
int len = src.length();
65
if (len == 0 || len > 15) {
66
return null;
67
}
68
/*
69
* When only one part is given, the value is stored directly in
70
* the network address without any byte rearrangement.
71
*
72
* When a two part address is supplied, the last part is
73
* interpreted as a 24-bit quantity and placed in the right
74
* most three bytes of the network address. This makes the
75
* two part address format convenient for specifying Class A
76
* network addresses as net.host.
77
*
78
* When a three part address is specified, the last part is
79
* interpreted as a 16-bit quantity and placed in the right
80
* most two bytes of the network address. This makes the
81
* three part address format convenient for specifying
82
* Class B net- work addresses as 128.net.host.
83
*
84
* When four parts are specified, each is interpreted as a
85
* byte of data and assigned, from left to right, to the
86
* four bytes of an IPv4 address.
87
*
88
* We determine and parse the leading parts, if any, as single
89
* byte values in one pass directly into the resulting byte[],
90
* then the remainder is treated as a 8-to-32-bit entity and
91
* translated into the remaining bytes in the array.
92
*/
93
for (int i = 0; i < len; i++) {
94
char c = src.charAt(i);
95
if (c == '.') {
96
if (newOctet || tmpValue < 0 || tmpValue > 0xff || currByte == 3) {
97
return null;
98
}
99
res[currByte++] = (byte) (tmpValue & 0xff);
100
tmpValue = 0;
101
newOctet = true;
102
} else {
103
int digit = Character.digit(c, 10);
104
if (digit < 0) {
105
return null;
106
}
107
tmpValue *= 10;
108
tmpValue += digit;
109
newOctet = false;
110
}
111
}
112
if (newOctet || tmpValue < 0 || tmpValue >= (1L << ((4 - currByte) * 8))) {
113
return null;
114
}
115
switch (currByte) {
116
case 0:
117
res[0] = (byte) ((tmpValue >> 24) & 0xff);
118
case 1:
119
res[1] = (byte) ((tmpValue >> 16) & 0xff);
120
case 2:
121
res[2] = (byte) ((tmpValue >> 8) & 0xff);
122
case 3:
123
res[3] = (byte) ((tmpValue >> 0) & 0xff);
124
}
125
return res;
126
}
127
128
/*
129
* Convert IPv6 presentation level address to network order binary form.
130
* credit:
131
* Converted from C code from Solaris 8 (inet_pton)
132
*
133
* Any component of the string following a per-cent % is ignored.
134
*
135
* @param src a String representing an IPv6 address in textual format
136
* @return a byte array representing the IPv6 numeric address
137
*/
138
public static byte[] textToNumericFormatV6(String src)
139
{
140
// Shortest valid string is "::", hence at least 2 chars
141
if (src.length() < 2) {
142
return null;
143
}
144
145
int colonp;
146
char ch;
147
boolean saw_xdigit;
148
int val;
149
char[] srcb = src.toCharArray();
150
byte[] dst = new byte[INADDR16SZ];
151
152
int srcb_length = srcb.length;
153
int pc = src.indexOf ('%');
154
if (pc == srcb_length -1) {
155
return null;
156
}
157
158
if (pc != -1) {
159
srcb_length = pc;
160
}
161
162
colonp = -1;
163
int i = 0, j = 0;
164
/* Leading :: requires some special handling. */
165
if (srcb[i] == ':')
166
if (srcb[++i] != ':')
167
return null;
168
int curtok = i;
169
saw_xdigit = false;
170
val = 0;
171
while (i < srcb_length) {
172
ch = srcb[i++];
173
int chval = Character.digit(ch, 16);
174
if (chval != -1) {
175
val <<= 4;
176
val |= chval;
177
if (val > 0xffff)
178
return null;
179
saw_xdigit = true;
180
continue;
181
}
182
if (ch == ':') {
183
curtok = i;
184
if (!saw_xdigit) {
185
if (colonp != -1)
186
return null;
187
colonp = j;
188
continue;
189
} else if (i == srcb_length) {
190
return null;
191
}
192
if (j + INT16SZ > INADDR16SZ)
193
return null;
194
dst[j++] = (byte) ((val >> 8) & 0xff);
195
dst[j++] = (byte) (val & 0xff);
196
saw_xdigit = false;
197
val = 0;
198
continue;
199
}
200
if (ch == '.' && ((j + INADDR4SZ) <= INADDR16SZ)) {
201
String ia4 = src.substring(curtok, srcb_length);
202
/* check this IPv4 address has 3 dots, i.e. A.B.C.D */
203
int dot_count = 0, index=0;
204
while ((index = ia4.indexOf ('.', index)) != -1) {
205
dot_count ++;
206
index ++;
207
}
208
if (dot_count != 3) {
209
return null;
210
}
211
byte[] v4addr = textToNumericFormatV4(ia4);
212
if (v4addr == null) {
213
return null;
214
}
215
for (int k = 0; k < INADDR4SZ; k++) {
216
dst[j++] = v4addr[k];
217
}
218
saw_xdigit = false;
219
break; /* '\0' was seen by inet_pton4(). */
220
}
221
return null;
222
}
223
if (saw_xdigit) {
224
if (j + INT16SZ > INADDR16SZ)
225
return null;
226
dst[j++] = (byte) ((val >> 8) & 0xff);
227
dst[j++] = (byte) (val & 0xff);
228
}
229
230
if (colonp != -1) {
231
int n = j - colonp;
232
233
if (j == INADDR16SZ)
234
return null;
235
for (i = 1; i <= n; i++) {
236
dst[INADDR16SZ - i] = dst[colonp + n - i];
237
dst[colonp + n - i] = 0;
238
}
239
j = INADDR16SZ;
240
}
241
if (j != INADDR16SZ)
242
return null;
243
byte[] newdst = convertFromIPv4MappedAddress(dst);
244
if (newdst != null) {
245
return newdst;
246
} else {
247
return dst;
248
}
249
}
250
251
/**
252
* @param src a String representing an IPv4 address in textual format
253
* @return a boolean indicating whether src is an IPv4 literal address
254
*/
255
public static boolean isIPv4LiteralAddress(String src) {
256
return textToNumericFormatV4(src) != null;
257
}
258
259
/**
260
* @param src a String representing an IPv6 address in textual format
261
* @return a boolean indicating whether src is an IPv6 literal address
262
*/
263
public static boolean isIPv6LiteralAddress(String src) {
264
return textToNumericFormatV6(src) != null;
265
}
266
267
/*
268
* Convert IPv4-Mapped address to IPv4 address. Both input and
269
* returned value are in network order binary form.
270
*
271
* @param src a String representing an IPv4-Mapped address in textual format
272
* @return a byte array representing the IPv4 numeric address
273
*/
274
public static byte[] convertFromIPv4MappedAddress(byte[] addr) {
275
if (isIPv4MappedAddress(addr)) {
276
byte[] newAddr = new byte[INADDR4SZ];
277
System.arraycopy(addr, 12, newAddr, 0, INADDR4SZ);
278
return newAddr;
279
}
280
return null;
281
}
282
283
/**
284
* Utility routine to check if the InetAddress is an
285
* IPv4 mapped IPv6 address.
286
*
287
* @return a <code>boolean</code> indicating if the InetAddress is
288
* an IPv4 mapped IPv6 address; or false if address is IPv4 address.
289
*/
290
private static boolean isIPv4MappedAddress(byte[] addr) {
291
if (addr.length < INADDR16SZ) {
292
return false;
293
}
294
if ((addr[0] == 0x00) && (addr[1] == 0x00) &&
295
(addr[2] == 0x00) && (addr[3] == 0x00) &&
296
(addr[4] == 0x00) && (addr[5] == 0x00) &&
297
(addr[6] == 0x00) && (addr[7] == 0x00) &&
298
(addr[8] == 0x00) && (addr[9] == 0x00) &&
299
(addr[10] == (byte)0xff) &&
300
(addr[11] == (byte)0xff)) {
301
return true;
302
}
303
return false;
304
}
305
/**
306
* Mapping from unscoped local Inet(6)Address to the same address
307
* including the correct scope-id, determined from NetworkInterface.
308
*/
309
private static final ConcurrentHashMap<InetAddress,InetAddress>
310
cache = new ConcurrentHashMap<>();
311
312
/**
313
* Returns a scoped version of the supplied local, link-local ipv6 address
314
* if that scope-id can be determined from local NetworkInterfaces.
315
* If the address already has a scope-id or if the address is not local, ipv6
316
* or link local, then the original address is returned.
317
*
318
* @param address
319
* @exception SocketException if the given ipv6 link local address is found
320
* on more than one local interface
321
* @return
322
*/
323
public static InetAddress toScopedAddress(InetAddress address)
324
throws SocketException {
325
326
if (address instanceof Inet6Address && address.isLinkLocalAddress()
327
&& ((Inet6Address) address).getScopeId() == 0) {
328
329
InetAddress cached = null;
330
try {
331
cached = cache.computeIfAbsent(address, k -> findScopedAddress(k));
332
} catch (UncheckedIOException e) {
333
throw (SocketException)e.getCause();
334
}
335
return cached != null ? cached : address;
336
} else {
337
return address;
338
}
339
}
340
341
/**
342
* Same as above for InetSocketAddress
343
*/
344
public static InetSocketAddress toScopedAddress(InetSocketAddress address)
345
throws SocketException {
346
InetAddress addr;
347
InetAddress orig = address.getAddress();
348
if ((addr = toScopedAddress(orig)) == orig) {
349
return address;
350
} else {
351
return new InetSocketAddress(addr, address.getPort());
352
}
353
}
354
355
@SuppressWarnings("removal")
356
private static InetAddress findScopedAddress(InetAddress address) {
357
PrivilegedExceptionAction<List<InetAddress>> pa = () -> NetworkInterface.networkInterfaces()
358
.flatMap(NetworkInterface::inetAddresses)
359
.filter(a -> (a instanceof Inet6Address)
360
&& address.equals(a)
361
&& ((Inet6Address) a).getScopeId() != 0)
362
.toList();
363
List<InetAddress> result;
364
try {
365
result = AccessController.doPrivileged(pa);
366
var sz = result.size();
367
if (sz == 0)
368
return null;
369
if (sz > 1)
370
throw new UncheckedIOException(new SocketException(
371
"Duplicate link local addresses: must specify scope-id"));
372
return result.get(0);
373
} catch (PrivilegedActionException pae) {
374
return null;
375
}
376
}
377
378
// See java.net.URI for more details on how to generate these
379
// masks.
380
//
381
// square brackets
382
private static final long L_IPV6_DELIMS = 0x0L; // "[]"
383
private static final long H_IPV6_DELIMS = 0x28000000L; // "[]"
384
// RFC 3986 gen-delims
385
private static final long L_GEN_DELIMS = 0x8400800800000000L; // ":/?#[]@"
386
private static final long H_GEN_DELIMS = 0x28000001L; // ":/?#[]@"
387
// These gen-delims can appear in authority
388
private static final long L_AUTH_DELIMS = 0x400000000000000L; // "@[]:"
389
private static final long H_AUTH_DELIMS = 0x28000001L; // "@[]:"
390
// colon is allowed in userinfo
391
private static final long L_COLON = 0x400000000000000L; // ":"
392
private static final long H_COLON = 0x0L; // ":"
393
// slash should be encoded in authority
394
private static final long L_SLASH = 0x800000000000L; // "/"
395
private static final long H_SLASH = 0x0L; // "/"
396
// backslash should always be encoded
397
private static final long L_BACKSLASH = 0x0L; // "\"
398
private static final long H_BACKSLASH = 0x10000000L; // "\"
399
// ASCII chars 0-31 + 127 - various controls + CRLF + TAB
400
private static final long L_NON_PRINTABLE = 0xffffffffL;
401
private static final long H_NON_PRINTABLE = 0x8000000000000000L;
402
// All of the above
403
private static final long L_EXCLUDE = 0x84008008ffffffffL;
404
private static final long H_EXCLUDE = 0x8000000038000001L;
405
406
private static final char[] OTHERS = {
407
8263,8264,8265,8448,8449,8453,8454,10868,
408
65109,65110,65119,65131,65283,65295,65306,65311,65312
409
};
410
411
// Tell whether the given character is found by the given mask pair
412
public static boolean match(char c, long lowMask, long highMask) {
413
if (c < 64)
414
return ((1L << c) & lowMask) != 0;
415
if (c < 128)
416
return ((1L << (c - 64)) & highMask) != 0;
417
return false; // other non ASCII characters are not filtered
418
}
419
420
// returns -1 if the string doesn't contain any characters
421
// from the mask, the index of the first such character found
422
// otherwise.
423
public static int scan(String s, long lowMask, long highMask) {
424
int i = -1, len;
425
if (s == null || (len = s.length()) == 0) return -1;
426
boolean match = false;
427
while (++i < len && !(match = match(s.charAt(i), lowMask, highMask)));
428
if (match) return i;
429
return -1;
430
}
431
432
public static int scan(String s, long lowMask, long highMask, char[] others) {
433
int i = -1, len;
434
if (s == null || (len = s.length()) == 0) return -1;
435
boolean match = false;
436
char c, c0 = others[0];
437
while (++i < len && !(match = match((c=s.charAt(i)), lowMask, highMask))) {
438
if (c >= c0 && (Arrays.binarySearch(others, c) > -1)) {
439
match = true; break;
440
}
441
}
442
if (match) return i;
443
444
return -1;
445
}
446
447
private static String describeChar(char c) {
448
if (c < 32 || c == 127) {
449
if (c == '\n') return "LF";
450
if (c == '\r') return "CR";
451
return "control char (code=" + (int)c + ")";
452
}
453
if (c == '\\') return "'\\'";
454
return "'" + c + "'";
455
}
456
457
private static String checkUserInfo(String str) {
458
// colon is permitted in user info
459
int index = scan(str, L_EXCLUDE & ~L_COLON,
460
H_EXCLUDE & ~H_COLON);
461
if (index >= 0) {
462
return "Illegal character found in user-info: "
463
+ describeChar(str.charAt(index));
464
}
465
return null;
466
}
467
468
private static String checkHost(String str) {
469
int index;
470
if (str.startsWith("[") && str.endsWith("]")) {
471
str = str.substring(1, str.length() - 1);
472
if (isIPv6LiteralAddress(str)) {
473
index = str.indexOf('%');
474
if (index >= 0) {
475
index = scan(str = str.substring(index),
476
L_NON_PRINTABLE | L_IPV6_DELIMS,
477
H_NON_PRINTABLE | H_IPV6_DELIMS);
478
if (index >= 0) {
479
return "Illegal character found in IPv6 scoped address: "
480
+ describeChar(str.charAt(index));
481
}
482
}
483
return null;
484
}
485
return "Unrecognized IPv6 address format";
486
} else {
487
index = scan(str, L_EXCLUDE, H_EXCLUDE);
488
if (index >= 0) {
489
return "Illegal character found in host: "
490
+ describeChar(str.charAt(index));
491
}
492
}
493
return null;
494
}
495
496
private static String checkAuth(String str) {
497
int index = scan(str,
498
L_EXCLUDE & ~L_AUTH_DELIMS,
499
H_EXCLUDE & ~H_AUTH_DELIMS);
500
if (index >= 0) {
501
return "Illegal character found in authority: "
502
+ describeChar(str.charAt(index));
503
}
504
return null;
505
}
506
507
// check authority of hierarchical URL. Appropriate for
508
// HTTP-like protocol handlers
509
public static String checkAuthority(URL url) {
510
String s, u, h;
511
if (url == null) return null;
512
if ((s = checkUserInfo(u = url.getUserInfo())) != null) {
513
return s;
514
}
515
if ((s = checkHost(h = url.getHost())) != null) {
516
return s;
517
}
518
if (h == null && u == null) {
519
return checkAuth(url.getAuthority());
520
}
521
return null;
522
}
523
524
// minimal syntax checks - deeper check may be performed
525
// by the appropriate protocol handler
526
public static String checkExternalForm(URL url) {
527
String s;
528
if (url == null) return null;
529
int index = scan(s = url.getUserInfo(),
530
L_NON_PRINTABLE | L_SLASH,
531
H_NON_PRINTABLE | H_SLASH);
532
if (index >= 0) {
533
return "Illegal character found in authority: "
534
+ describeChar(s.charAt(index));
535
}
536
if ((s = checkHostString(url.getHost())) != null) {
537
return s;
538
}
539
return null;
540
}
541
542
public static String checkHostString(String host) {
543
if (host == null) return null;
544
int index = scan(host,
545
L_NON_PRINTABLE | L_SLASH,
546
H_NON_PRINTABLE | H_SLASH,
547
OTHERS);
548
if (index >= 0) {
549
return "Illegal character found in host: "
550
+ describeChar(host.charAt(index));
551
}
552
return null;
553
}
554
}
555
556