Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/jdk17u
Path: blob/master/src/java.base/share/classes/sun/net/util/IPAddressUtil.java
67770 views
1
/*
2
* Copyright (c) 2004, 2022, 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 sun.security.action.GetPropertyAction;
29
30
import java.io.UncheckedIOException;
31
import java.net.Inet6Address;
32
import java.net.InetAddress;
33
import java.net.InetSocketAddress;
34
import java.net.NetworkInterface;
35
import java.net.SocketException;
36
import java.net.URL;
37
import java.nio.CharBuffer;
38
import java.security.AccessController;
39
import java.security.PrivilegedExceptionAction;
40
import java.security.PrivilegedActionException;
41
import java.util.Arrays;
42
import java.util.List;
43
import java.util.concurrent.ConcurrentHashMap;
44
45
public class IPAddressUtil {
46
private static final int INADDR4SZ = 4;
47
private static final int INADDR16SZ = 16;
48
private static final int INT16SZ = 2;
49
50
/*
51
* Converts IPv4 address in its textual presentation form
52
* into its numeric binary form.
53
*
54
* @param src a String representing an IPv4 address in standard format
55
* @return a byte array representing the IPv4 numeric address
56
*/
57
@SuppressWarnings("fallthrough")
58
public static byte[] textToNumericFormatV4(String src)
59
{
60
byte[] res = new byte[INADDR4SZ];
61
62
long tmpValue = 0;
63
int currByte = 0;
64
boolean newOctet = true;
65
66
int len = src.length();
67
if (len == 0 || len > 15) {
68
return null;
69
}
70
/*
71
* When only one part is given, the value is stored directly in
72
* the network address without any byte rearrangement.
73
*
74
* When a two part address is supplied, the last part is
75
* interpreted as a 24-bit quantity and placed in the right
76
* most three bytes of the network address. This makes the
77
* two part address format convenient for specifying Class A
78
* network addresses as net.host.
79
*
80
* When a three part address is specified, the last part is
81
* interpreted as a 16-bit quantity and placed in the right
82
* most two bytes of the network address. This makes the
83
* three part address format convenient for specifying
84
* Class B net- work addresses as 128.net.host.
85
*
86
* When four parts are specified, each is interpreted as a
87
* byte of data and assigned, from left to right, to the
88
* four bytes of an IPv4 address.
89
*
90
* We determine and parse the leading parts, if any, as single
91
* byte values in one pass directly into the resulting byte[],
92
* then the remainder is treated as a 8-to-32-bit entity and
93
* translated into the remaining bytes in the array.
94
*/
95
for (int i = 0; i < len; i++) {
96
char c = src.charAt(i);
97
if (c == '.') {
98
if (newOctet || tmpValue < 0 || tmpValue > 0xff || currByte == 3) {
99
return null;
100
}
101
res[currByte++] = (byte) (tmpValue & 0xff);
102
tmpValue = 0;
103
newOctet = true;
104
} else {
105
int digit = digit(c, 10);
106
if (digit < 0) {
107
return null;
108
}
109
tmpValue *= 10;
110
tmpValue += digit;
111
newOctet = false;
112
}
113
}
114
if (newOctet || tmpValue < 0 || tmpValue >= (1L << ((4 - currByte) * 8))) {
115
return null;
116
}
117
switch (currByte) {
118
case 0:
119
res[0] = (byte) ((tmpValue >> 24) & 0xff);
120
case 1:
121
res[1] = (byte) ((tmpValue >> 16) & 0xff);
122
case 2:
123
res[2] = (byte) ((tmpValue >> 8) & 0xff);
124
case 3:
125
res[3] = (byte) ((tmpValue >> 0) & 0xff);
126
}
127
return res;
128
}
129
130
/**
131
* Validates if input string is a valid IPv4 address literal.
132
* If the "jdk.net.allowAmbiguousIPAddressLiterals" system property is set
133
* to {@code false}, or is not set then validation of the address string is performed as follows:
134
* If string can't be parsed by following IETF IPv4 address string literals
135
* formatting style rules (default one), but can be parsed by following BSD formatting
136
* style rules, the IPv4 address string content is treated as ambiguous and
137
* {@code IllegalArgumentException} is thrown.
138
*
139
* @param src input string
140
* @return bytes array if string is a valid IPv4 address string
141
* @throws IllegalArgumentException if "jdk.net.allowAmbiguousIPAddressLiterals" SP is set to
142
* "false" and IPv4 address string {@code "src"} is ambiguous
143
*/
144
public static byte[] validateNumericFormatV4(String src) {
145
byte[] parsedBytes = textToNumericFormatV4(src);
146
if (!ALLOW_AMBIGUOUS_IPADDRESS_LITERALS_SP_VALUE
147
&& parsedBytes == null && isBsdParsableV4(src)) {
148
throw new IllegalArgumentException("Invalid IP address literal: " + src);
149
}
150
return parsedBytes;
151
}
152
153
/*
154
* Convert IPv6 presentation level address to network order binary form.
155
* credit:
156
* Converted from C code from Solaris 8 (inet_pton)
157
*
158
* Any component of the string following a per-cent % is ignored.
159
*
160
* @param src a String representing an IPv6 address in textual format
161
* @return a byte array representing the IPv6 numeric address
162
*/
163
public static byte[] textToNumericFormatV6(String src)
164
{
165
// Shortest valid string is "::", hence at least 2 chars
166
if (src.length() < 2) {
167
return null;
168
}
169
170
int colonp;
171
char ch;
172
boolean saw_xdigit;
173
int val;
174
char[] srcb = src.toCharArray();
175
byte[] dst = new byte[INADDR16SZ];
176
177
int srcb_length = srcb.length;
178
int pc = src.indexOf ('%');
179
if (pc == srcb_length -1) {
180
return null;
181
}
182
183
if (pc != -1) {
184
srcb_length = pc;
185
}
186
187
colonp = -1;
188
int i = 0, j = 0;
189
/* Leading :: requires some special handling. */
190
if (srcb[i] == ':')
191
if (srcb[++i] != ':')
192
return null;
193
int curtok = i;
194
saw_xdigit = false;
195
val = 0;
196
while (i < srcb_length) {
197
ch = srcb[i++];
198
int chval = digit(ch, 16);
199
if (chval != -1) {
200
val <<= 4;
201
val |= chval;
202
if (val > 0xffff)
203
return null;
204
saw_xdigit = true;
205
continue;
206
}
207
if (ch == ':') {
208
curtok = i;
209
if (!saw_xdigit) {
210
if (colonp != -1)
211
return null;
212
colonp = j;
213
continue;
214
} else if (i == srcb_length) {
215
return null;
216
}
217
if (j + INT16SZ > INADDR16SZ)
218
return null;
219
dst[j++] = (byte) ((val >> 8) & 0xff);
220
dst[j++] = (byte) (val & 0xff);
221
saw_xdigit = false;
222
val = 0;
223
continue;
224
}
225
if (ch == '.' && ((j + INADDR4SZ) <= INADDR16SZ)) {
226
String ia4 = src.substring(curtok, srcb_length);
227
/* check this IPv4 address has 3 dots, i.e. A.B.C.D */
228
int dot_count = 0, index=0;
229
while ((index = ia4.indexOf ('.', index)) != -1) {
230
dot_count ++;
231
index ++;
232
}
233
if (dot_count != 3) {
234
return null;
235
}
236
byte[] v4addr = textToNumericFormatV4(ia4);
237
if (v4addr == null) {
238
return null;
239
}
240
for (int k = 0; k < INADDR4SZ; k++) {
241
dst[j++] = v4addr[k];
242
}
243
saw_xdigit = false;
244
break; /* '\0' was seen by inet_pton4(). */
245
}
246
return null;
247
}
248
if (saw_xdigit) {
249
if (j + INT16SZ > INADDR16SZ)
250
return null;
251
dst[j++] = (byte) ((val >> 8) & 0xff);
252
dst[j++] = (byte) (val & 0xff);
253
}
254
255
if (colonp != -1) {
256
int n = j - colonp;
257
258
if (j == INADDR16SZ)
259
return null;
260
for (i = 1; i <= n; i++) {
261
dst[INADDR16SZ - i] = dst[colonp + n - i];
262
dst[colonp + n - i] = 0;
263
}
264
j = INADDR16SZ;
265
}
266
if (j != INADDR16SZ)
267
return null;
268
byte[] newdst = convertFromIPv4MappedAddress(dst);
269
if (newdst != null) {
270
return newdst;
271
} else {
272
return dst;
273
}
274
}
275
276
/**
277
* @param src a String representing an IPv4 address in textual format
278
* @return a boolean indicating whether src is an IPv4 literal address
279
*/
280
public static boolean isIPv4LiteralAddress(String src) {
281
return textToNumericFormatV4(src) != null;
282
}
283
284
/**
285
* @param src a String representing an IPv6 address in textual format
286
* @return a boolean indicating whether src is an IPv6 literal address
287
*/
288
public static boolean isIPv6LiteralAddress(String src) {
289
return textToNumericFormatV6(src) != null;
290
}
291
292
/*
293
* Convert IPv4-Mapped address to IPv4 address. Both input and
294
* returned value are in network order binary form.
295
*
296
* @param src a String representing an IPv4-Mapped address in textual format
297
* @return a byte array representing the IPv4 numeric address
298
*/
299
public static byte[] convertFromIPv4MappedAddress(byte[] addr) {
300
if (isIPv4MappedAddress(addr)) {
301
byte[] newAddr = new byte[INADDR4SZ];
302
System.arraycopy(addr, 12, newAddr, 0, INADDR4SZ);
303
return newAddr;
304
}
305
return null;
306
}
307
308
/**
309
* Utility routine to check if the InetAddress is an
310
* IPv4 mapped IPv6 address.
311
*
312
* @return a <code>boolean</code> indicating if the InetAddress is
313
* an IPv4 mapped IPv6 address; or false if address is IPv4 address.
314
*/
315
private static boolean isIPv4MappedAddress(byte[] addr) {
316
if (addr.length < INADDR16SZ) {
317
return false;
318
}
319
if ((addr[0] == 0x00) && (addr[1] == 0x00) &&
320
(addr[2] == 0x00) && (addr[3] == 0x00) &&
321
(addr[4] == 0x00) && (addr[5] == 0x00) &&
322
(addr[6] == 0x00) && (addr[7] == 0x00) &&
323
(addr[8] == 0x00) && (addr[9] == 0x00) &&
324
(addr[10] == (byte)0xff) &&
325
(addr[11] == (byte)0xff)) {
326
return true;
327
}
328
return false;
329
}
330
/**
331
* Mapping from unscoped local Inet(6)Address to the same address
332
* including the correct scope-id, determined from NetworkInterface.
333
*/
334
private static final ConcurrentHashMap<InetAddress,InetAddress>
335
cache = new ConcurrentHashMap<>();
336
337
/**
338
* Returns a scoped version of the supplied local, link-local ipv6 address
339
* if that scope-id can be determined from local NetworkInterfaces.
340
* If the address already has a scope-id or if the address is not local, ipv6
341
* or link local, then the original address is returned.
342
*
343
* @param address
344
* @exception SocketException if the given ipv6 link local address is found
345
* on more than one local interface
346
* @return
347
*/
348
public static InetAddress toScopedAddress(InetAddress address)
349
throws SocketException {
350
351
if (address instanceof Inet6Address && address.isLinkLocalAddress()
352
&& ((Inet6Address) address).getScopeId() == 0) {
353
354
InetAddress cached = null;
355
try {
356
cached = cache.computeIfAbsent(address, k -> findScopedAddress(k));
357
} catch (UncheckedIOException e) {
358
throw (SocketException)e.getCause();
359
}
360
return cached != null ? cached : address;
361
} else {
362
return address;
363
}
364
}
365
366
/**
367
* Same as above for InetSocketAddress
368
*/
369
public static InetSocketAddress toScopedAddress(InetSocketAddress address)
370
throws SocketException {
371
InetAddress addr;
372
InetAddress orig = address.getAddress();
373
if ((addr = toScopedAddress(orig)) == orig) {
374
return address;
375
} else {
376
return new InetSocketAddress(addr, address.getPort());
377
}
378
}
379
380
@SuppressWarnings("removal")
381
private static InetAddress findScopedAddress(InetAddress address) {
382
PrivilegedExceptionAction<List<InetAddress>> pa = () -> NetworkInterface.networkInterfaces()
383
.flatMap(NetworkInterface::inetAddresses)
384
.filter(a -> (a instanceof Inet6Address)
385
&& address.equals(a)
386
&& ((Inet6Address) a).getScopeId() != 0)
387
.toList();
388
List<InetAddress> result;
389
try {
390
result = AccessController.doPrivileged(pa);
391
var sz = result.size();
392
if (sz == 0)
393
return null;
394
if (sz > 1)
395
throw new UncheckedIOException(new SocketException(
396
"Duplicate link local addresses: must specify scope-id"));
397
return result.get(0);
398
} catch (PrivilegedActionException pae) {
399
return null;
400
}
401
}
402
403
// See java.net.URI for more details on how to generate these
404
// masks.
405
//
406
// square brackets
407
private static final long L_IPV6_DELIMS = 0x0L; // "[]"
408
private static final long H_IPV6_DELIMS = 0x28000000L; // "[]"
409
// RFC 3986 gen-delims
410
private static final long L_GEN_DELIMS = 0x8400800800000000L; // ":/?#[]@"
411
private static final long H_GEN_DELIMS = 0x28000001L; // ":/?#[]@"
412
// These gen-delims can appear in authority
413
private static final long L_AUTH_DELIMS = 0x400000000000000L; // "@[]:"
414
private static final long H_AUTH_DELIMS = 0x28000001L; // "@[]:"
415
// colon is allowed in userinfo
416
private static final long L_COLON = 0x400000000000000L; // ":"
417
private static final long H_COLON = 0x0L; // ":"
418
// slash should be encoded in authority
419
private static final long L_SLASH = 0x800000000000L; // "/"
420
private static final long H_SLASH = 0x0L; // "/"
421
// backslash should always be encoded
422
private static final long L_BACKSLASH = 0x0L; // "\"
423
private static final long H_BACKSLASH = 0x10000000L; // "\"
424
// ASCII chars 0-31 + 127 - various controls + CRLF + TAB
425
private static final long L_NON_PRINTABLE = 0xffffffffL;
426
private static final long H_NON_PRINTABLE = 0x8000000000000000L;
427
// All of the above
428
private static final long L_EXCLUDE = 0x84008008ffffffffL;
429
private static final long H_EXCLUDE = 0x8000000038000001L;
430
431
private static final char[] OTHERS = {
432
8263,8264,8265,8448,8449,8453,8454,10868,
433
65109,65110,65119,65131,65283,65295,65306,65311,65312
434
};
435
436
// Tell whether the given character is found by the given mask pair
437
public static boolean match(char c, long lowMask, long highMask) {
438
if (c < 64)
439
return ((1L << c) & lowMask) != 0;
440
if (c < 128)
441
return ((1L << (c - 64)) & highMask) != 0;
442
return false; // other non ASCII characters are not filtered
443
}
444
445
// returns -1 if the string doesn't contain any characters
446
// from the mask, the index of the first such character found
447
// otherwise.
448
public static int scan(String s, long lowMask, long highMask) {
449
int i = -1, len;
450
if (s == null || (len = s.length()) == 0) return -1;
451
boolean match = false;
452
while (++i < len && !(match = match(s.charAt(i), lowMask, highMask)));
453
if (match) return i;
454
return -1;
455
}
456
457
public static int scan(String s, long lowMask, long highMask, char[] others) {
458
int i = -1, len;
459
if (s == null || (len = s.length()) == 0) return -1;
460
boolean match = false;
461
char c, c0 = others[0];
462
while (++i < len && !(match = match((c=s.charAt(i)), lowMask, highMask))) {
463
if (c >= c0 && (Arrays.binarySearch(others, c) > -1)) {
464
match = true; break;
465
}
466
}
467
if (match) return i;
468
469
return -1;
470
}
471
472
private static String describeChar(char c) {
473
if (c < 32 || c == 127) {
474
if (c == '\n') return "LF";
475
if (c == '\r') return "CR";
476
return "control char (code=" + (int)c + ")";
477
}
478
if (c == '\\') return "'\\'";
479
return "'" + c + "'";
480
}
481
482
private static String checkUserInfo(String str) {
483
// colon is permitted in user info
484
int index = scan(str, L_EXCLUDE & ~L_COLON,
485
H_EXCLUDE & ~H_COLON);
486
if (index >= 0) {
487
return "Illegal character found in user-info: "
488
+ describeChar(str.charAt(index));
489
}
490
return null;
491
}
492
493
private static String checkHost(String str) {
494
int index;
495
if (str.startsWith("[") && str.endsWith("]")) {
496
str = str.substring(1, str.length() - 1);
497
if (isIPv6LiteralAddress(str)) {
498
index = str.indexOf('%');
499
if (index >= 0) {
500
index = scan(str = str.substring(index),
501
L_NON_PRINTABLE | L_IPV6_DELIMS,
502
H_NON_PRINTABLE | H_IPV6_DELIMS);
503
if (index >= 0) {
504
return "Illegal character found in IPv6 scoped address: "
505
+ describeChar(str.charAt(index));
506
}
507
}
508
return null;
509
}
510
return "Unrecognized IPv6 address format";
511
} else {
512
index = scan(str, L_EXCLUDE, H_EXCLUDE);
513
if (index >= 0) {
514
return "Illegal character found in host: "
515
+ describeChar(str.charAt(index));
516
}
517
}
518
return null;
519
}
520
521
private static String checkAuth(String str) {
522
int index = scan(str,
523
L_EXCLUDE & ~L_AUTH_DELIMS,
524
H_EXCLUDE & ~H_AUTH_DELIMS);
525
if (index >= 0) {
526
return "Illegal character found in authority: "
527
+ describeChar(str.charAt(index));
528
}
529
return null;
530
}
531
532
// check authority of hierarchical URL. Appropriate for
533
// HTTP-like protocol handlers
534
public static String checkAuthority(URL url) {
535
String s, u, h;
536
if (url == null) return null;
537
if ((s = checkUserInfo(u = url.getUserInfo())) != null) {
538
return s;
539
}
540
if ((s = checkHost(h = url.getHost())) != null) {
541
return s;
542
}
543
if (h == null && u == null) {
544
return checkAuth(url.getAuthority());
545
}
546
return null;
547
}
548
549
// minimal syntax checks - deeper check may be performed
550
// by the appropriate protocol handler
551
public static String checkExternalForm(URL url) {
552
String s;
553
if (url == null) return null;
554
int index = scan(s = url.getUserInfo(),
555
L_NON_PRINTABLE | L_SLASH,
556
H_NON_PRINTABLE | H_SLASH);
557
if (index >= 0) {
558
return "Illegal character found in authority: "
559
+ describeChar(s.charAt(index));
560
}
561
if ((s = checkHostString(url.getHost())) != null) {
562
return s;
563
}
564
return null;
565
}
566
567
public static String checkHostString(String host) {
568
if (host == null) return null;
569
int index = scan(host,
570
L_NON_PRINTABLE | L_SLASH,
571
H_NON_PRINTABLE | H_SLASH,
572
OTHERS);
573
if (index >= 0) {
574
return "Illegal character found in host: "
575
+ describeChar(host.charAt(index));
576
}
577
return null;
578
}
579
580
/**
581
* Returns the numeric value of the character {@code ch} in the
582
* specified radix.
583
*
584
* @param ch the character to be converted.
585
* @param radix the radix.
586
* @return the numeric value represented by the character in the
587
* specified radix.
588
*/
589
public static int digit(char ch, int radix) {
590
if (ALLOW_AMBIGUOUS_IPADDRESS_LITERALS_SP_VALUE) {
591
return Character.digit(ch, radix);
592
} else {
593
return parseAsciiDigit(ch, radix);
594
}
595
}
596
597
/**
598
* Try to parse String as IPv4 address literal by following
599
* BSD-style formatting rules.
600
*
601
* @param input input string
602
* @return {@code true} if input string is parsable as IPv4 address literal,
603
* {@code false} otherwise.
604
*/
605
public static boolean isBsdParsableV4(String input) {
606
char firstSymbol = input.charAt(0);
607
// Check if first digit is not a decimal digit
608
if (parseAsciiDigit(firstSymbol, DECIMAL) == -1) {
609
return false;
610
}
611
612
// Last character is dot OR is not a supported digit: [0-9,A-F,a-f]
613
char lastSymbol = input.charAt(input.length() - 1);
614
if (lastSymbol == '.' || parseAsciiHexDigit(lastSymbol) == -1) {
615
return false;
616
}
617
618
// Parse IP address fields
619
CharBuffer charBuffer = CharBuffer.wrap(input);
620
int fieldNumber = 0;
621
while (charBuffer.hasRemaining()) {
622
long fieldValue = -1L;
623
// Try to parse fields in all supported radixes
624
for (int radix : SUPPORTED_RADIXES) {
625
fieldValue = parseV4FieldBsd(radix, charBuffer, fieldNumber);
626
if (fieldValue >= 0) {
627
fieldNumber++;
628
break;
629
} else if (fieldValue == TERMINAL_PARSE_ERROR) {
630
return false;
631
}
632
}
633
// If field can't be parsed as one of supported radixes stop
634
// parsing
635
if (fieldValue < 0) {
636
return false;
637
}
638
}
639
return true;
640
}
641
642
/**
643
* Method tries to parse IP address field that starts from {@linkplain CharBuffer#position()
644
* current position} of the provided character buffer.
645
* <p>
646
* This method supports three {@code "radix"} values to decode field values in
647
* {@code "HEXADECIMAL (radix=16)"}, {@code "DECIMAL (radix=10)"} and
648
* {@code "OCTAL (radix=8)"} radixes.
649
* <p>
650
* If {@code -1} value is returned the char buffer position is reset to the value
651
* it was before it was called.
652
* <p>
653
* Method returns {@code -2} if formatting illegal for all supported {@code radix}
654
* values is observed, and there is no point in checking other radix values.
655
* That includes the following cases:<ul>
656
* <li>Two subsequent dots are observer
657
* <li>Number of dots more than 3
658
* <li>Field value exceeds max allowed
659
* <li>Character is not a valid digit for the requested {@code radix} value, given
660
* that a field has the radix specific prefix
661
* </ul>
662
*
663
* @param radix digits encoding radix to use for parsing. Valid values: 8, 10, 16.
664
* @param buffer {@code CharBuffer} with position set to the field's fist character
665
* @param fieldNumber parsed field number
666
* @return {@code CANT_PARSE_IN_RADIX} if field can not be parsed in requested {@code radix}.
667
* {@code TERMINAL_PARSE_ERROR} if field can't be parsed and the whole parse process should be terminated.
668
* Parsed field value otherwise.
669
*/
670
private static long parseV4FieldBsd(int radix, CharBuffer buffer, int fieldNumber) {
671
int initialPos = buffer.position();
672
long val = 0;
673
int digitsCount = 0;
674
if (!checkPrefix(buffer, radix)) {
675
val = CANT_PARSE_IN_RADIX;
676
}
677
boolean dotSeen = false;
678
while (buffer.hasRemaining() && val != CANT_PARSE_IN_RADIX && !dotSeen) {
679
char c = buffer.get();
680
if (c == '.') {
681
dotSeen = true;
682
// Fail if 4 dots in IP address string.
683
// fieldNumber counter starts from 0, therefore 3
684
if (fieldNumber == 3) {
685
// Terminal state, can stop parsing: too many fields
686
return TERMINAL_PARSE_ERROR;
687
}
688
// Check for literals with two dots, like '1.2..3', '1.2.3..'
689
if (digitsCount == 0) {
690
// Terminal state, can stop parsing: dot with no digits
691
return TERMINAL_PARSE_ERROR;
692
}
693
if (val > 255) {
694
// Terminal state, can stop parsing: too big value for an octet
695
return TERMINAL_PARSE_ERROR;
696
}
697
} else {
698
int dv = parseAsciiDigit(c, radix);
699
if (dv >= 0) {
700
digitsCount++;
701
val *= radix;
702
val += dv;
703
} else {
704
// Spotted digit can't be parsed in the requested 'radix'.
705
// The order in which radixes are checked - hex, octal, decimal:
706
// - if symbol is not a valid digit in hex radix - terminal
707
// - if symbol is not a valid digit in octal radix, and given
708
// that octal prefix was observed before - terminal
709
// - if symbol is not a valid digit in decimal radix - terminal
710
return TERMINAL_PARSE_ERROR;
711
}
712
}
713
}
714
if (val == CANT_PARSE_IN_RADIX) {
715
buffer.position(initialPos);
716
} else if (!dotSeen) {
717
// It is the last field - check its value
718
// This check will ensure that address strings with less
719
// than 4 fields, i.e. A, A.B and A.B.C address types
720
// contain value less then the allowed maximum for the last field.
721
long maxValue = (1L << ((4 - fieldNumber) * 8)) - 1;
722
if (val > maxValue) {
723
// Terminal state, can stop parsing: last field value exceeds its
724
// allowed value
725
return TERMINAL_PARSE_ERROR;
726
}
727
}
728
return val;
729
}
730
731
// This method moves the position of the supplied CharBuffer by analysing the digit prefix
732
// symbols if any.
733
// The caller should reset the position when method returns false.
734
private static boolean checkPrefix(CharBuffer buffer, int radix) {
735
return switch (radix) {
736
case OCTAL -> isOctalFieldStart(buffer);
737
case DECIMAL -> isDecimalFieldStart(buffer);
738
case HEXADECIMAL -> isHexFieldStart(buffer);
739
default -> throw new AssertionError("Not supported radix");
740
};
741
}
742
743
// This method always moves the position of the supplied CharBuffer
744
// removing the octal prefix symbols '0'.
745
// The caller should reset the position when method returns false.
746
private static boolean isOctalFieldStart(CharBuffer cb) {
747
// .0<EOS> is not treated as octal field
748
if (cb.remaining() < 2) {
749
return false;
750
}
751
752
// Fetch two first characters
753
int position = cb.position();
754
char first = cb.get();
755
char second = cb.get();
756
757
// Return false if the first char is not octal prefix '0' or second is a
758
// field separator - parseV4FieldBsd will reset position to start of the field.
759
// '.0.' fields will be successfully parsed in decimal radix.
760
boolean isOctalPrefix = first == '0' && second != '.';
761
762
// If the prefix looks like octal - consume '0', otherwise 'false' is returned
763
// and caller will reset the buffer position.
764
if (isOctalPrefix) {
765
cb.position(position + 1);
766
}
767
return isOctalPrefix;
768
}
769
770
// This method doesn't move the position of the supplied CharBuffer
771
private static boolean isDecimalFieldStart(CharBuffer cb) {
772
return cb.hasRemaining();
773
}
774
775
// This method always moves the position of the supplied CharBuffer
776
// removing the hexadecimal prefix symbols '0x'.
777
// The caller should reset the position when method returns false.
778
private static boolean isHexFieldStart(CharBuffer cb) {
779
if (cb.remaining() < 2) {
780
return false;
781
}
782
char first = cb.get();
783
char second = cb.get();
784
return first == '0' && (second == 'x' || second == 'X');
785
}
786
787
// Parse ASCII digit in given radix
788
private static int parseAsciiDigit(char c, int radix) {
789
assert radix == OCTAL || radix == DECIMAL || radix == HEXADECIMAL;
790
if (radix == HEXADECIMAL) {
791
return parseAsciiHexDigit(c);
792
}
793
int val = c - '0';
794
return (val < 0 || val >= radix) ? -1 : val;
795
}
796
797
// Parse ASCII digit in hexadecimal radix
798
private static int parseAsciiHexDigit(char digit) {
799
char c = Character.toLowerCase(digit);
800
if (c >= 'a' && c <= 'f') {
801
return c - 'a' + 10;
802
}
803
return parseAsciiDigit(c, DECIMAL);
804
}
805
806
// Supported radixes
807
private static final int HEXADECIMAL = 16;
808
private static final int DECIMAL = 10;
809
private static final int OCTAL = 8;
810
// Order in which field formats are exercised to parse one IP address textual field
811
private static final int[] SUPPORTED_RADIXES = new int[]{HEXADECIMAL, OCTAL, DECIMAL};
812
813
// BSD parser's return values
814
private final static long CANT_PARSE_IN_RADIX = -1L;
815
private final static long TERMINAL_PARSE_ERROR = -2L;
816
817
private static final String ALLOW_AMBIGUOUS_IPADDRESS_LITERALS_SP = "jdk.net.allowAmbiguousIPAddressLiterals";
818
private static final boolean ALLOW_AMBIGUOUS_IPADDRESS_LITERALS_SP_VALUE = Boolean.valueOf(
819
GetPropertyAction.privilegedGetProperty(ALLOW_AMBIGUOUS_IPADDRESS_LITERALS_SP, "false"));
820
}
821
822