Java Code Examples for inet.ipaddr.AddressStringException

The following examples show how to use inet.ipaddr.AddressStringException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: IPAddress   Source File: Validator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public MACAddressProvider validateAddress(MACAddressString fromString) throws AddressStringException {
	String str = fromString.toString();
	MACAddressStringParameters validationOptions = fromString.getValidationOptions();
	ParsedMACAddress pa = new ParsedMACAddress(fromString, str);
	validateMACAddress(validationOptions, str, 0, str.length(), pa);
	AddressParseData addressParseData = pa.getAddressParseData();
	if(addressParseData.isProvidingEmpty()) {
		return MACAddressProvider.EMPTY_PROVIDER;
	} else if(addressParseData.isAll()) {
		return MACAddressProvider.getAllProvider(validationOptions);
	} else {
		checkSegments(
				fromString.toString(),
				fromString.getValidationOptions(),
				pa);
		return pa;
	}
}
 
Example 2
Source Project: IPAddress   Source File: Validator.java    License: Apache License 2.0 6 votes vote down vote up
private static ParsedHostIdentifierStringQualifier parseAddressQualifier(
		CharSequence fullAddr,
		IPAddressStringParameters validationOptions,
		final HostNameParameters hostValidationOptions,
		IPAddressParseData ipAddressParseData,
		int endIndex) throws AddressStringException {
	int qualifierIndex = ipAddressParseData.getQualifierIndex();
	boolean addressIsEmpty = ipAddressParseData.getAddressParseData().isProvidingEmpty();
	IPVersion ipVersion = ipAddressParseData.getProviderIPVersion();
	if(ipAddressParseData.hasPrefixSeparator()) {
		return parsePrefix(fullAddr, null, validationOptions, hostValidationOptions,
				addressIsEmpty, qualifierIndex, endIndex, ipVersion);
	} else if(ipAddressParseData.isZoned()) {
		if(ipAddressParseData.isBase85Zoned() && !ipAddressParseData.isProvidingBase85IPv6()) {
			throw new AddressStringException(fullAddr, qualifierIndex - 1);
		}
		if(addressIsEmpty) {
			throw new AddressStringException(fullAddr, "ipaddress.error.only.zone");
		}
		return parseZone(fullAddr, validationOptions, addressIsEmpty, qualifierIndex, endIndex, ipVersion);
	} 
	return ParsedHost.NO_QUALIFIER;
}
 
Example 3
Source Project: IPAddress   Source File: Validator.java    License: Apache License 2.0 6 votes vote down vote up
private static ParsedHostIdentifierStringQualifier parseHostAddressQualifier(
		CharSequence fullAddr,
		IPAddressStringParameters validationOptions,
		HostNameParameters hostValidationOptions,
		boolean isPrefixed,
		boolean hasPort,
		IPAddressParseData ipAddressParseData,
		int qualifierIndex,
		int endIndex) throws AddressStringException {
	boolean addressIsEmpty = ipAddressParseData.getAddressParseData().isProvidingEmpty();
	IPVersion ipVersion = ipAddressParseData.getProviderIPVersion();
	if(isPrefixed) {
		return parsePrefix(fullAddr, null, validationOptions, hostValidationOptions,
				addressIsEmpty, qualifierIndex, endIndex, ipVersion);
	} else if(ipAddressParseData.isZoned()) {
		if(addressIsEmpty) {
			throw new AddressStringException(fullAddr, "ipaddress.error.only.zone");
		}
		return parseEncodedZone(fullAddr, validationOptions, addressIsEmpty, qualifierIndex, endIndex, ipVersion);
	} else if(hasPort) {//isPort is always false when validating an address
		return parsePortOrService(fullAddr, null, hostValidationOptions, qualifierIndex, endIndex);
	}
	return ParsedHost.NO_QUALIFIER;
}
 
Example 4
Source Project: IPAddress   Source File: Validator.java    License: Apache License 2.0 6 votes vote down vote up
private static ParsedHostIdentifierStringQualifier parseHostNameQualifier(
		final CharSequence fullAddr,
		final IPAddressStringParameters validationOptions,
		final HostNameParameters hostValidationOptions,
		final boolean isPrefixed,
		final boolean isPort,//always false for address
		final boolean addressIsEmpty,
		final int index,
		final int endIndex,
		final IPVersion ipVersion) throws AddressStringException {
	if(isPrefixed) {
		return parsePrefix(fullAddr, null, validationOptions, hostValidationOptions,
				addressIsEmpty, index, endIndex, ipVersion);
	} else if(isPort) {//isPort is always false when validating an address
		return parsePortOrService(fullAddr, null, hostValidationOptions, index, endIndex);
	}
	return ParsedHost.NO_QUALIFIER;
}
 
Example 5
Source Project: IPAddress   Source File: Validator.java    License: Apache License 2.0 6 votes vote down vote up
private static ParsedHostIdentifierStringQualifier parseZone(
		final CharSequence fullAddr, 
		final IPAddressStringParameters validationOptions,
		final boolean addressIsEmpty,
		final int index,
		final int endIndex,
		final IPVersion ipVersion) throws AddressStringException {
	for(int i = index; i < endIndex; i++) {
		char c = fullAddr.charAt(i);
		if(c == IPAddress.PREFIX_LEN_SEPARATOR) {
			CharSequence zone = fullAddr.subSequence(index, i);
			return parsePrefix(fullAddr, zone, validationOptions, null, addressIsEmpty, i + 1, endIndex, ipVersion);
		} else if(c == IPv6Address.SEGMENT_SEPARATOR) {
			throw new AddressStringException(fullAddr, "ipaddress.error.invalid.zone", i);
		}
	}
	return new ParsedHostIdentifierStringQualifier(fullAddr.subSequence(index, endIndex));
}
 
Example 6
Source Project: IPAddress   Source File: Validator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * The digits were stored as a hex value, this switches them to an octal value.
 * 
 * @param currentHexValue
 * @param digitCount
 * @return
 */
// OCTX private static long switchValue8(long currentHexValue, int digitCount) {
private static long switchValue8(long currentHexValue, CharSequence s, int digitCount) throws AddressStringException {
	long result = 0xf & currentHexValue;
	if(result >= 8) {
		throw new AddressStringException(s, "ipaddress.error.ipv4.invalid.octal.digit");
	}
	int shift = 0;
	while(--digitCount > 0) {
		shift += 3;
		currentHexValue >>>= 4;
		long next = 0xf & currentHexValue;
		if(next >= 8) {
			throw new AddressStringException(s, "ipaddress.error.ipv4.invalid.octal.digit");
		}
		result |= next << shift;
	}
	return result;
}
 
Example 7
Source Project: IPAddress   Source File: Validator.java    License: Apache License 2.0 6 votes vote down vote up
private static CharSequence convertReverseDNSIPv4(String str, int suffixStartIndex) throws AddressStringException {
	StringBuilder builder = new StringBuilder(suffixStartIndex);
	int segCount = 0;
	int j = suffixStartIndex;
	for(int i = suffixStartIndex - 1; i > 0; i--) {
		char c1 = str.charAt(i);
		if(c1 == IPv4Address.SEGMENT_SEPARATOR) {
			if(j - i <= 1) {
				throw new AddressStringException(str, i);
			}
			for(int k = i + 1; k < j; k++) {
				builder.append(str.charAt(k));
			}
			builder.append(c1);
			j = i;
			segCount++;
		}
	}
	for(int k = 0; k < j; k++) {
		builder.append(str.charAt(k));
	}
	if(segCount + 1 != IPv4Address.SEGMENT_COUNT) {
		throw new AddressStringException(str, 0);
	}
	return builder;
}
 
Example 8
Source Project: IPAddress   Source File: MACAddressTest.java    License: Apache License 2.0 6 votes vote down vote up
void testContains(String addr1, String addr2, boolean equal) {
		try {
			MACAddress w = createMACAddress(addr1).toAddress();
			MACAddress w2 = createMACAddress(addr2).toAddress();
			if(!w.contains(w2)) {
				addFailure(new Failure("failed " + w2, w));
			} else {
				if(equal ? !w2.contains(w) : w2.contains(w)) {
					addFailure(new Failure("failed " + w, w2));
//					if(equal) {
//						System.out.println("containment: " + !w2.contains(w));
//					} else {
//						System.out.println("containment: " + w2.contains(w));
//					}
				}
			}
		} catch(AddressStringException e) {
			addFailure(new Failure("failed " + e));
		}
		incrementTestCount();
	}
 
Example 9
Source Project: IPAddress   Source File: MACAddressTest.java    License: Apache License 2.0 6 votes vote down vote up
void testDelimitedCount(String str, int expectedCount) {
	Iterator<String> strings = MACAddressString.parseDelimitedSegments(str);
	HashSet<MACAddress> set = new HashSet<MACAddress>();
	int count = 0;
	try {
		while(strings.hasNext()) {
			set.add(createMACAddress(strings.next()).toAddress());
			count++;
		}
		if(count != expectedCount || set.size() != count || count != MACAddressString.countDelimitedAddresses(str)) {
			addFailure(new Failure("count mismatch, count: " + count + " set count: " + set.size() + " calculated count: " + IPAddressString.countDelimitedAddresses(str) + " expected: " + expectedCount));
		}
	} catch (AddressStringException | IncompatibleAddressException e) {
		addFailure(new Failure("threw unexpectedly " + str));
	}
	incrementTestCount();
}
 
Example 10
Source Project: AntiVPN   Source File: ValidationUtil.java    License: MIT License 5 votes vote down vote up
public static boolean isValidIPRange(String range) {
    if (range == null || range.isEmpty()) {
        return false;
    }
    try {
        return new IPAddressString(range).toAddress().isMultiple();
    } catch (AddressStringException ignored) { return false; }
}
 
Example 11
Source Project: AntiVPN   Source File: ValidationUtil.java    License: MIT License 5 votes vote down vote up
public static boolean isValidIp(String ip) {
    if (ip == null || ip.isEmpty()) {
        return false;
    }
    try {
        return !new IPAddressString(ip).toAddress().isMultiple();
    } catch (AddressStringException ignored) { return false; }
}
 
Example 12
Source Project: IPAddress   Source File: Validator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public IPAddressProvider validateAddress(IPAddressString fromString) throws AddressStringException {
	String str = fromString.toString();
	IPAddressStringParameters validationOptions = fromString.getValidationOptions();
	ParsedIPAddress pa = new ParsedIPAddress(fromString, str, validationOptions);
	validateIPAddress(validationOptions, str, 0, str.length(), pa, false);
	return chooseProvider(fromString, str, validationOptions, pa,
		parseAddressQualifier(str, validationOptions, null, pa, str.length()));
}
 
Example 13
Source Project: IPAddress   Source File: Validator.java    License: Apache License 2.0 5 votes vote down vote up
private static void validateIPAddress(
		final IPAddressStringParameters validationOptions,
		final CharSequence str,
		final int strStartIndex,
		int strEndIndex,
		IPAddressParseData parseData,
		boolean isEmbeddedIPv4) throws AddressStringException {
	validateAddress(validationOptions, null, str, strStartIndex, strEndIndex, parseData, null, isEmbeddedIPv4);
}
 
Example 14
Source Project: IPAddress   Source File: Validator.java    License: Apache License 2.0 5 votes vote down vote up
private static void validateMACAddress(
		final MACAddressStringParameters validationOptions,
		final String str,
		final int strStartIndex,
		int strEndIndex,
		MACAddressParseData parseData) throws AddressStringException {
	validateAddress(null, validationOptions, str, strStartIndex, strEndIndex, null, parseData, false);
}
 
Example 15
Source Project: IPAddress   Source File: Validator.java    License: Apache License 2.0 5 votes vote down vote up
static int validatePrefixImpl(CharSequence fullAddr, IPVersion version) throws AddressStringException {
	ParsedHostIdentifierStringQualifier qualifier = validatePrefix(fullAddr, null, DEFAULT_PREFIX_OPTIONS, null, 0, fullAddr.length(), version);
	if(qualifier == null) {
		throw new AddressStringException(fullAddr.toString(), "ipaddress.error.invalidCIDRPrefix");
	}
	return qualifier.getNetworkPrefixLength();
}
 
Example 16
Source Project: IPAddress   Source File: Validator.java    License: Apache License 2.0 5 votes vote down vote up
private static void checkSingleWildcard(CharSequence str, int start, int end, int digitsEnd, AddressStringFormatParameters options) throws AddressStringException {
	if(!options.rangeOptions.allowsSingleWildcard()) {
		throw new AddressStringException(str, "ipaddress.error.no.single.wildcard");
	}
	for(int k = digitsEnd; k < end; k++) {
		if(str.charAt(k) != IPAddress.SEGMENT_SQL_SINGLE_WILDCARD) {
			throw new AddressStringException(str, "ipaddress.error.single.wildcard.order");
		}
	}
}
 
Example 17
Source Project: IPAddress   Source File: Validator.java    License: Apache License 2.0 5 votes vote down vote up
private static void switchSingleWildcard10(long currentValueHex, CharSequence s, int start, int end, int numSingleWildcards, AddressParseData parseData, int parsedSegIndex, int leadingZeroStartIndex, AddressStringFormatParameters options) throws AddressStringException {
	int digitsEnd = end - numSingleWildcards;
	checkSingleWildcard(s, start, end, digitsEnd, options);
	long lower;
	if(start < digitsEnd) { 
		lower = switchValue10(currentValueHex, s, digitsEnd - start);
	} else {
		lower = 0;
	}
	long upper;
	switch(numSingleWildcards) {
		case 1:
			lower *= 10;
			upper = lower + 9;
			break;
		case 2:
			lower *= 100;
			upper = lower + 99;
			break;
		case 3:
			lower *= 1000;
			upper = lower + 999;
			break;
		default:
			long power = (long) Math.pow(10, numSingleWildcards);
			lower *= power;
			upper = lower + power - 1;
	}
	int radix = 10;
	assignAttributesValuesFlags(start, end, leadingZeroStartIndex, start, end, leadingZeroStartIndex,
			parseData, parsedSegIndex, lower, upper, AddressParseData.KEY_SINGLE_WILDCARD | radix, radix);
}
 
Example 18
Source Project: IPAddress   Source File: Validator.java    License: Apache License 2.0 5 votes vote down vote up
private static void switchSingleWildcard8(long currentValueHex, CharSequence s, int start, int end, int numSingleWildcards, AddressParseData parseData, int parsedSegIndex, int leadingZeroStartIndex, AddressStringFormatParameters options) throws AddressStringException {
	int digitsEnd = end - numSingleWildcards;
	checkSingleWildcard(s, start, end, digitsEnd, options);
	long lower, upper;
	if(start < digitsEnd) {
		lower = switchValue8(currentValueHex, s, digitsEnd - start);
	} else {
		lower = 0;
	}
	switch(numSingleWildcards) {
		case 1:
			lower <<= 3;
			upper = lower | 07;
			break;
		case 2:
			lower <<= 6;
			upper = lower | 077;
			break;
		case 3:
			lower <<= 9;
			upper = lower | 0777;
			break;
		default:
			int shift = numSingleWildcards * 3;
			lower <<= shift;
			upper = lower | ~(~0L << shift);
			break;
	}
	int radix = 8;
	assignAttributesValuesFlags(start, end, leadingZeroStartIndex, start, end, leadingZeroStartIndex,
			parseData, parsedSegIndex, lower, upper, AddressParseData.KEY_SINGLE_WILDCARD | radix, radix);
}
 
Example 19
Source Project: IPAddress   Source File: Validator.java    License: Apache License 2.0 5 votes vote down vote up
private static void assignSingleWildcard16(long lower, CharSequence s, int start, int end, int numSingleWildcards, AddressParseData parseData, int parsedSegIndex, int leadingZeroStartIndex, AddressStringFormatParameters options) throws AddressStringException {
	int digitsEnd = end - numSingleWildcards;
	checkSingleWildcard(s, start, end, digitsEnd, options);
	int shift = numSingleWildcards << 2;
	lower <<= shift;
	long upper = lower | ~(~0L << shift);
	assignAttributesValuesFlags(start, end, leadingZeroStartIndex, start, end, leadingZeroStartIndex,
			parseData, parsedSegIndex, lower, upper, AddressParseData.KEY_SINGLE_WILDCARD);
}
 
Example 20
Source Project: IPAddress   Source File: Validator.java    License: Apache License 2.0 5 votes vote down vote up
private static long switchValue10(long currentHexValue, CharSequence s, int digitCount) throws AddressStringException {
	long result = 0xf & currentHexValue;
	if(result >= 10) {
		throw new AddressStringException(s, "ipaddress.error.ipv4.invalid.decimal.digit");
	}
	if(--digitCount > 0) {
		int factor = 10;
		while(true) {
			currentHexValue >>>= 4;
			long next = 0xf & currentHexValue;
			if(next >= 10) {
				throw new AddressStringException(s, "ipaddress.error.ipv4.invalid.decimal.digit");
			}
			result += next * factor;
			if(--digitCount == 0) {
				break;
			}
			if(factor == 10) {
				factor = 100;
			} else if(factor == 100) {
				factor = 1000;
			} else {
				factor *= 10;
			}
		}
	}
	return result;
}
 
Example 21
Source Project: IPAddress   Source File: MACAddressTest.java    License: Apache License 2.0 5 votes vote down vote up
boolean isNotExpected(boolean expectedPass, MACAddressString addr) {
	try {
		addr.validate();
		return !expectedPass;
	} catch(AddressStringException e) {
		return expectedPass;
	}
}
 
Example 22
Source Project: IPAddress   Source File: MACAddressTest.java    License: Apache License 2.0 5 votes vote down vote up
void testNotContains(String cidr1, String cidr2) {
	try {
		MACAddress w = createMACAddress(cidr1).toAddress();
		MACAddress w2 = createMACAddress(cidr2).toAddress();
		if(w.contains(w2)) {
			addFailure(new Failure("failed " + w2, w));
		} else if(w2.contains(w)) {
			addFailure(new Failure("failed " + w, w2));
		}
	} catch(AddressStringException e) {
		addFailure(new Failure("failed " + e, new MACAddressString(cidr1)));
	}
	incrementTestCount();
}
 
Example 23
Source Project: IPAddress   Source File: Validator.java    License: Apache License 2.0 4 votes vote down vote up
private static void checkSegments(
		final String fullAddr,
		final MACAddressStringParameters validationOptions,
		final ParsedMACAddress parseData) throws AddressStringException {
	MACFormat format = parseData.getFormat();
	if(format != null) {
		AddressParseData addressParseData = parseData.getAddressParseData();
		boolean hasWildcardSeparator = addressParseData.hasWildcard() && validationOptions.getFormatParameters().allowWildcardedSeparator;
		//note that too many segments is checked inside the general parsing method
		int segCount = addressParseData.getSegmentCount();
		if(format == MACFormat.DOTTED) {
			if(segCount <= MACAddress.MEDIA_ACCESS_CONTROL_DOTTED_SEGMENT_COUNT && validationOptions.addressSize != AddressSize.EUI64) {
				if(!hasWildcardSeparator && segCount != MACAddress.MEDIA_ACCESS_CONTROL_DOTTED_SEGMENT_COUNT) {
					throw new AddressStringException(fullAddr, "ipaddress.error.too.few.segments");
				}
			} else if(!hasWildcardSeparator && segCount < MACAddress.MEDIA_ACCESS_CONTROL_DOTTED_64_SEGMENT_COUNT) {
				throw new AddressStringException(fullAddr, "ipaddress.error.too.few.segments");
			} else {
				parseData.setExtended(true);
			}
		} else if(segCount > 2) {
			if(segCount <= MACAddress.MEDIA_ACCESS_CONTROL_SEGMENT_COUNT && validationOptions.addressSize != AddressSize.EUI64) {
				if(!hasWildcardSeparator && segCount != MACAddress.MEDIA_ACCESS_CONTROL_SEGMENT_COUNT) {
					throw new AddressStringException(fullAddr, "ipaddress.error.too.few.segments");
				}
			} else if(!hasWildcardSeparator && segCount < MACAddress.EXTENDED_UNIQUE_IDENTIFIER_64_SEGMENT_COUNT) {
				throw new AddressStringException(fullAddr, "ipaddress.error.too.few.segments");
			} else {
				parseData.setExtended(true);
			}
			if(parseData.getFormat() == MACFormat.DASHED) {
				int max = MACAddress.MAX_VALUE_PER_SEGMENT;
				int maxChars = MACAddressSegment.MAX_CHARS;
				for(int i = 0; i < segCount; i++) {
					checkMaxValues(
							fullAddr,
							addressParseData,
							i,
							validationOptions.getFormatParameters(),
							max,
							maxChars,
							maxChars);
				}
			}
		} else {
			if(parseData.getFormat() == MACFormat.DASHED) {
				//for single segment, we have already counted the exact number of hex digits
				//for double segment, we have already counted the exact number of hex digits in some cases and not others.
				//Basically, for address like a-b we have already counted the exact number of hex digits,
				//for addresses starting with a|b- or a-b| we have not,
				//but rather than figure out which are checked out which not it's just as quick to check them all here
				if(parseData.isDoubleSegment()) {
					MACAddressStringFormatParameters params = validationOptions.getFormatParameters();
					checkMaxValues(fullAddr, addressParseData, 0, params, MAC_MAX_TRIPLE, MAC_DOUBLE_SEGMENT_DIGIT_COUNT, MAC_DOUBLE_SEGMENT_DIGIT_COUNT);
					if(parseData.isExtended()) {
						checkMaxValues(fullAddr, addressParseData, 1, params, MAC_MAX_QUINTUPLE, MAC_EXTENDED_DOUBLE_SEGMENT_DIGIT_COUNT, MAC_EXTENDED_DOUBLE_SEGMENT_DIGIT_COUNT);
					} else {
						checkMaxValues(fullAddr, addressParseData, 1, params, MAC_MAX_TRIPLE, MAC_DOUBLE_SEGMENT_DIGIT_COUNT, MAC_DOUBLE_SEGMENT_DIGIT_COUNT);
					}
				}
			} else if(!hasWildcardSeparator) {
				throw new AddressStringException(fullAddr, "ipaddress.error.too.few.segments");
			}
			if(validationOptions.addressSize == AddressSize.EUI64) {
				parseData.setExtended(true);
			}
		}
	} //else single segment
}
 
Example 24
Source Project: IPAddress   Source File: Validator.java    License: Apache License 2.0 4 votes vote down vote up
private static IPAddressProvider chooseProvider(
		final HostIdentifierString originator,
		final CharSequence fullAddr,
		final IPAddressStringParameters validationOptions,
		final ParsedIPAddress parseData,
		final ParsedHostIdentifierStringQualifier qualifier) throws AddressStringException {
	IPVersion version = parseData.getProviderIPVersion();
	if(version == null) {
		version = qualifier.inferVersion(validationOptions);
		IPVersion optionsVersion = validationOptions.inferVersion();
		if(version == null) {
			parseData.setVersion(version = optionsVersion);
		} else if(optionsVersion != null && !version.equals(optionsVersion)) {
			throw new AddressStringException(fullAddr, version == IPVersion.IPV6 ? "ipaddress.error.ipv6" : "ipaddress.error.ipv4");
		}
		AddressParseData addressParseData = parseData.getAddressParseData();
		if(addressParseData.isProvidingEmpty()) {
			Integer networkPrefixLength = qualifier.getNetworkPrefixLength();
			if(networkPrefixLength != null) {
				int prefLen = networkPrefixLength;
				if(validationOptions == IPAddressString.DEFAULT_VALIDATION_OPTIONS && networkPrefixLength <= IPv6Address.BIT_COUNT) {
					int index = version == null ? 0 : version.isIPv4() ? 1 : 2;
					MaskCreator cached[] = MASK_CACHE[index];
					if(cached == null) {
						MASK_CACHE[index] = cached = new MaskCreator[IPv6Address.BIT_COUNT + 1];
					}
					MaskCreator result = cached[prefLen];
					if(result == null) {
						cached[prefLen] = result = new MaskCreator(networkPrefixLength, version, IPAddressString.DEFAULT_VALIDATION_OPTIONS);
					}
					return result;
				}
				return new MaskCreator(networkPrefixLength, version, validationOptions);
			} else {
				//Note: we do not support loopback with zone, it seems the loopback is never associated with a link-local zone
				if(validationOptions.emptyIsLoopback) {
					if(validationOptions == IPAddressString.DEFAULT_VALIDATION_OPTIONS) {
						return LOOPBACK_CACHE;
					}
					return new LoopbackCreator(validationOptions);
				}
				return IPAddressProvider.EMPTY_PROVIDER;
			}
		} else { //isAll
			//We also need the AllCreator to use the equivalent prefix length, much like in ParsedIPAddress
			return new AllCreator(qualifier, version, originator, validationOptions);
		}
	} else {
		if(parseData.isZoned() && version.isIPv4()) {
			throw new AddressStringException(fullAddr, "ipaddress.error.only.ipv6.has.zone");
		}
		parseData.setQualifier(qualifier);
		checkSegments(fullAddr, validationOptions, parseData);
		return parseData;
	}
}
 
Example 25
Source Project: IPAddress   Source File: Validator.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public int validatePrefix(CharSequence fullAddr, IPVersion version) throws AddressStringException {
	return validatePrefixImpl(fullAddr, version);
}
 
Example 26
Source Project: IPAddress   Source File: Validator.java    License: Apache License 2.0 4 votes vote down vote up
private static ParsedHostIdentifierStringQualifier parsePortOrService(
		final CharSequence fullAddr,
		final CharSequence zone,
		final HostNameParameters validationOptions,
		final int index,
		final int endIndex) throws AddressStringException {
	boolean isPort = true, hasLetter = false, hasDigits = false, isAll = false;
	int charCount = 0, lastHyphen = -1, result = 0;
	
	int charArray[] = chars;
	for(int i = index; i < endIndex; i++) {
		char c = fullAddr.charAt(i);
		if(c >= '1' && c <= '9') {
			if(isPort) {
				hasDigits = true;
				result = result * 10 + charArray[c];
			}
			++charCount;
		} else if(c == '0') {
			if(isPort && hasDigits) {
				result *= 10;
			} 
			++charCount;
		} else {
			//http://www.iana.org/assignments/port-numbers
			//valid service name chars:
			//https://tools.ietf.org/html/rfc6335#section-5.1
			//https://tools.ietf.org/html/rfc6335#section-10.1
			isPort = false;
			boolean isHyphen = false;
			if((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (isHyphen = (c == '-')) || (isAll = (c == Address.SEGMENT_WILDCARD))) {
				if(isHyphen) {
					if(i == index) {
						throw new AddressStringException(fullAddr.toString(), "ipaddress.host.error.invalid.service.hyphen.start");
					} else if(i - 1 == lastHyphen) {
						throw new AddressStringException(fullAddr.toString(), "ipaddress.host.error.invalid.service.hyphen.consecutive");
					} else if(i == endIndex - 1) {
						throw new AddressStringException(fullAddr.toString(), "ipaddress.host.error.invalid.service.hyphen.end");
					}
					lastHyphen = i;
				} else if(isAll) {
					if(i > index) {
						throw new AddressStringException(fullAddr.toString(), i, true);
					} else if(i + 1 < endIndex) {
						throw new AddressStringException(fullAddr.toString(), i + 1, true);
					}
					hasLetter = true;
					++charCount;
					break;
				} else {
					hasLetter = true;
				}
				++charCount;
			} else {
				throw new AddressStringException(fullAddr.toString(), "ipaddress.host.error.invalid.port.service", i);
			}
		}
	}
	if(isPort) {
		if(!validationOptions.allowPort) {
			throw new AddressStringException(fullAddr.toString(), "ipaddress.host.error.port");
		} else if(result == 0) {
			throw new AddressStringException(fullAddr.toString(), "ipaddress.host.error.invalidPort.no.digits");
		} else if(result > 65535) {
			throw new AddressStringException(fullAddr.toString(), "ipaddress.host.error.invalidPort.too.large");
		}
		return new ParsedHostIdentifierStringQualifier(zone, result);
	} else if(!validationOptions.allowService) {
		throw new AddressStringException(fullAddr.toString(), "ipaddress.host.error.service");
	} else if(charCount == 0) {
		throw new AddressStringException(fullAddr.toString(), "ipaddress.host.error.invalidService.no.chars");
	} else if(charCount > 15) {
		throw new AddressStringException(fullAddr.toString(), "ipaddress.host.error.invalidService.too.long");
	} else if(!hasLetter) {
		throw new AddressStringException(fullAddr.toString(), "ipaddress.host.error.invalidService.no.letter");
	}
	CharSequence service = fullAddr.subSequence(index, endIndex);
	return new ParsedHostIdentifierStringQualifier(zone, service);
}
 
Example 27
Source Project: IPAddress   Source File: Validator.java    License: Apache License 2.0 4 votes vote down vote up
private static ParsedHostIdentifierStringQualifier validatePrefix(
		final CharSequence fullAddr,
		final CharSequence zone,
		final IPAddressStringParameters validationOptions,
		final HostNameParameters hostValidationOptions,
		final int index,
		final int endIndex,
		final IPVersion ipVersion) throws AddressStringException {
	if(index == fullAddr.length()) {
		return null;
	}
	boolean isPrefix = true;
	int prefixEndIndex = endIndex;
	int leadingZeros = 0;
	boolean hasDigits = false;
	int result = 0;
	int charArray[] = chars;
	ParsedHostIdentifierStringQualifier portQualifier = null;
	for(int i = index; i < endIndex; i++) {
		char c = fullAddr.charAt(i);
		if(c >= '1' && c <= '9') {
			hasDigits = true;
			result = result * 10 + charArray[c];
		} else if(c == '0') {
			if(hasDigits) {
				result *= 10;
			} else {
				++leadingZeros;
			}
		} else if(c == HostName.PORT_SEPARATOR && hostValidationOptions != null && 
				(hostValidationOptions.allowPort || hostValidationOptions.allowService) && i > index) {
			//check if we have a port or service.  If not, possibly an IPv6 mask.  
			//Also, parsing for port first (rather than prefix) allows us to call parseValidatedPrefix with the knowledge that whatever is supplied can only be a prefix.
			try {
				portQualifier = parsePortOrService(fullAddr, zone, hostValidationOptions, i + 1, endIndex);
				prefixEndIndex = i;
				break;
			} catch(AddressStringException e) {
				return null;
			}
		} else {
			isPrefix = false;
			break;
		}
	}
	//we treat as a prefix if all the characters were digits, even if there were too many, unless the mask options allow for inet_aton single segment
	if(isPrefix) {
		ParsedHostIdentifierStringQualifier prefixQualifier = parseValidatedPrefix(result, fullAddr, 
				zone, validationOptions, hostValidationOptions, index, prefixEndIndex, prefixEndIndex - index /* digitCount */, leadingZeros, ipVersion);
		if(portQualifier != null) {
			portQualifier.overridePrefix(prefixQualifier);
			return portQualifier;
		}
		return prefixQualifier;
	}
	return null;
}
 
Example 28
Source Project: IPAddress   Source File: Validator.java    License: Apache License 2.0 4 votes vote down vote up
private static ParsedHostIdentifierStringQualifier parsePrefix(
		final CharSequence fullAddr,
		final CharSequence zone,
		final IPAddressStringParameters validationOptions,
		final HostNameParameters hostValidationOptions,
		final boolean addressIsEmpty,
		final int index,
		final int endIndex,
		final IPVersion ipVersion) throws AddressStringException {
	if(validationOptions.allowPrefix) {
		ParsedHostIdentifierStringQualifier qualifier = validatePrefix(fullAddr, zone, validationOptions, hostValidationOptions,
				index, endIndex, ipVersion);
		if(qualifier != null) {
			return qualifier;
		}
	}
	if(addressIsEmpty) {
		//PREFIX_ONLY must have a prefix and not a mask - we don't allow /255.255.0.0
		throw new AddressStringException(fullAddr, "ipaddress.error.invalid.mask.address.empty");
	} else if(validationOptions.allowMask) {
		try {
			//check for a mask
			//check if we need a new validation options for the mask
			IPAddressStringParameters maskOptions = toMaskOptions(validationOptions, ipVersion);
			ParsedIPAddress pa = new ParsedIPAddress(null, fullAddr, maskOptions);
			validateIPAddress(maskOptions, fullAddr, index, endIndex, pa, false);
			AddressParseData maskParseData = pa.getAddressParseData();
			if(maskParseData.isProvidingEmpty()) {
				throw new AddressStringException(fullAddr, "ipaddress.error.invalid.mask.empty");
			} else if(maskParseData.isAll()) {
				throw new AddressStringException(fullAddr, "ipaddress.error.invalid.mask.wildcard");
			}
			checkSegments(fullAddr, maskOptions, pa);
			int maskEndIndex = maskParseData.getAddressEndIndex();
			if(maskEndIndex != endIndex) { // 1.2.3.4/ or 1.2.3.4// or 1.2.3.4/%
				throw new AddressStringException(fullAddr, "ipaddress.error.invalid.mask.extra.chars", maskEndIndex + 1);
			}
			IPVersion maskVersion = pa.getProviderIPVersion();
			if(maskVersion.isIPv4() && maskParseData.getSegmentCount() == 1 && !maskParseData.hasWildcard() && !validationOptions.getIPv4Parameters().inet_aton_single_segment_mask) {//1.2.3.4/33 where 33 is an aton_inet single segment address and not a prefix length
				throw new AddressStringException(fullAddr, "ipaddress.error.mask.single.segment");
			} else if(ipVersion != null && (maskVersion.isIPv4() != ipVersion.isIPv4() || maskVersion.isIPv6() != ipVersion.isIPv6())) {
				//note that this also covers the cases of non-standard addresses in the mask, ie mask neither ipv4 or ipv6
				throw new AddressStringException(fullAddr, "ipaddress.error.ipMismatch");
			}
			return new ParsedHostIdentifierStringQualifier(pa, zone);
		} catch(AddressStringException e) {
			throw new AddressStringException(fullAddr, "ipaddress.error.invalidCIDRPrefixOrMask", e);
		}
	}
	throw new AddressStringException(fullAddr, 
			validationOptions.allowPrefix ? "ipaddress.error.invalidCIDRPrefixOrMask" : "ipaddress.error.CIDRNotAllowed");
}
 
Example 29
Source Project: IPAddress   Source File: Validator.java    License: Apache License 2.0 4 votes vote down vote up
private static ParsedHostIdentifierStringQualifier parseEncodedZone(
		final CharSequence fullAddr, 
		final IPAddressStringParameters validationOptions,
		final boolean addressIsEmpty,
		final int index,
		final int endIndex,
		final IPVersion ipVersion) throws AddressStringException {
	StringBuilder result = null;
	for(int i = index; i < endIndex; i++) {
		char c = fullAddr.charAt(i);
		//we are in here when we have a square bracketed host like [::1]
		//not if we have a HostName with no brackets
		
		//https://tools.ietf.org/html/rfc6874
		//https://tools.ietf.org/html/rfc4007#section-11.7
		if(c == IPv6Address.ZONE_SEPARATOR) {
			if(i + 2 >= endIndex) {
				throw new AddressStringException(fullAddr, "ipaddress.error.invalid.zone.encoding", i);
			}
			//percent encoded
			if(result == null) {
				result = new StringBuilder(endIndex - index);
				result.append(fullAddr, index, i);
			}
			int charArray[] = chars;
			c = (char) (charArray[fullAddr.charAt(++i)] << 4);
			c |= charArray[fullAddr.charAt(++i)];
		} else if(c == IPAddress.PREFIX_LEN_SEPARATOR) {
			CharSequence zone = result != null ? result : fullAddr.subSequence(index, i);
			return parsePrefix(fullAddr, zone, validationOptions, null, addressIsEmpty, i + 1, endIndex, ipVersion);
		} else if(isReserved(c)) {
			throw new AddressStringException(fullAddr, "ipaddress.error.invalid.zone", i);
		}
		if(result != null) {
			result.append(c);
		}
	}
	if(result == null) {
		return new ParsedHostIdentifierStringQualifier(fullAddr.subSequence(index, endIndex));
	}
	return new ParsedHostIdentifierStringQualifier(result);
}
 
Example 30
Source Project: IPAddress   Source File: Validator.java    License: Apache License 2.0 4 votes vote down vote up
private static CharSequence convertReverseDNSIPv6(String str, int suffixStartIndex) throws AddressStringException {
	StringBuilder builder = new StringBuilder(suffixStartIndex);
	StringBuilder low = new StringBuilder();
	StringBuilder high = new StringBuilder();
	int segCount = 0;
	for(int i = suffixStartIndex - 1; i >= 0; ) {
		boolean isRange = false;
		for(int j = 0; j < 4; j++) {
			char c1 = str.charAt(i--);
			if(i >= 0) {
				char c2 = str.charAt(i--);
				if(c2 == IPv4Address.SEGMENT_SEPARATOR) {
					if(c1 == IPAddress.SEGMENT_WILDCARD) {
						isRange = true;
						low.append('0');
						high.append('f');
					} else {
						if(isRange) {
							throw new AddressStringException(str, i + 1);
						}
						low.append(c1);
						high.append(c1);
					}
				} else if(c2 == IPAddress.RANGE_SEPARATOR) {
					high.append(c1);
					if(i >= 1) {
						c2 = str.charAt(i--);
						low.append(c2);
						boolean isFullRange = (c2 == '0' && c1 == 'f');
						if(isRange && !isFullRange) {
							throw new AddressStringException(str, i + 1);
						}
						c2 = str.charAt(i--);
						if(c2 != IPv4Address.SEGMENT_SEPARATOR) {
							throw new AddressStringException(str, i + 1);
						}
					} else {
						throw new AddressStringException(str, i);
					}
					isRange = true;
				} else {
					throw new AddressStringException(str, i + 1);
				}
			} else if(j < 3) {
				throw new AddressStringException(str, i + 1);
			} else {
				if(c1 == IPAddress.SEGMENT_WILDCARD) {
					isRange = true;
					low.append('0');
					high.append('f');
				} else {
					if(isRange) {
						throw new AddressStringException(str, 0);
					}
					low.append(c1);
					high.append(c1);
				}
			}
		}
		segCount++;
		if(builder.length() > 0) {
			builder.append(IPv6Address.SEGMENT_SEPARATOR);
		}
		builder.append(low);
		if(isRange) {
			builder.append(IPAddress.RANGE_SEPARATOR).append(high);
		}
		low.setLength(0);
		high.setLength(0);
	}
	if(segCount != IPv6Address.SEGMENT_COUNT) {
		throw new AddressStringException(str, 0);
	}
	return builder;
}