001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.openstreetmap.josm.data.validation.routines;
018
019import java.util.ArrayList;
020import java.util.Arrays;
021import java.util.List;
022
023import org.openstreetmap.josm.tools.Utils;
024
025/**
026 * <p><b>InetAddress</b> validation and conversion routines (<code>java.net.InetAddress</code>).</p>
027 *
028 * <p>This class provides methods to validate a candidate IP address.
029 *
030 * <p>
031 * This class is a Singleton; you can retrieve the instance via the {@link #getInstance()} method.
032 * </p>
033 *
034 * @version $Revision: 1741724 $
035 * @since Validator 1.4
036 */
037public class InetAddressValidator extends AbstractValidator {
038
039    private static final int IPV4_MAX_OCTET_VALUE = 255;
040
041    private static final int MAX_UNSIGNED_SHORT = 0xffff;
042
043    private static final int BASE_16 = 16;
044
045    private static final String IPV4_REGEX =
046            "^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$";
047
048    // Max number of hex groups (separated by :) in an IPV6 address
049    private static final int IPV6_MAX_HEX_GROUPS = 8;
050
051    // Max hex digits in each IPv6 group
052    private static final int IPV6_MAX_HEX_DIGITS_PER_GROUP = 4;
053
054    /**
055     * Singleton instance of this class.
056     */
057    private static final InetAddressValidator VALIDATOR = new InetAddressValidator();
058
059    /** IPv4 RegexValidator */
060    private final RegexValidator ipv4Validator = new RegexValidator(IPV4_REGEX);
061
062    /**
063     * Returns the singleton instance of this validator.
064     * @return the singleton instance of this validator
065     */
066    public static InetAddressValidator getInstance() {
067        return VALIDATOR;
068    }
069
070    /**
071     * Checks if the specified string is a valid IP address.
072     * @param inetAddress the string to validate
073     * @return true if the string validates as an IP address
074     */
075    @Override
076    public boolean isValid(String inetAddress) {
077        return isValidInet4Address(inetAddress) || isValidInet6Address(inetAddress);
078    }
079
080    @Override
081    public String getValidatorName() {
082        return null;
083    }
084
085    /**
086     * Validates an IPv4 address. Returns true if valid.
087     * @param inet4Address the IPv4 address to validate
088     * @return true if the argument contains a valid IPv4 address
089     */
090    public boolean isValidInet4Address(String inet4Address) {
091        // verify that address conforms to generic IPv4 format
092        String[] groups = ipv4Validator.match(inet4Address);
093
094        if (groups == null) {
095            return false;
096        }
097
098        // verify that address subgroups are legal
099        for (String ipSegment : groups) {
100            if (Utils.isEmpty(ipSegment)) {
101                return false;
102            }
103
104            int iIpSegment = 0;
105
106            try {
107                iIpSegment = Integer.parseInt(ipSegment);
108            } catch (NumberFormatException e) {
109                return false;
110            }
111
112            if (iIpSegment > IPV4_MAX_OCTET_VALUE) {
113                return false;
114            }
115
116            if (ipSegment.length() > 1 && ipSegment.startsWith("0")) {
117                return false;
118            }
119
120        }
121
122        return true;
123    }
124
125    /**
126     * Validates an IPv6 address. Returns true if valid.
127     * @param inet6Address the IPv6 address to validate
128     * @return true if the argument contains a valid IPv6 address
129     *
130     * @since 1.4.1
131     */
132    public boolean isValidInet6Address(String inet6Address) {
133        boolean containsCompressedZeroes = inet6Address.contains("::");
134        if (containsCompressedZeroes && (inet6Address.indexOf("::") != inet6Address.lastIndexOf("::"))) {
135            return false;
136        }
137        if ((inet6Address.startsWith(":") && !inet6Address.startsWith("::"))
138                || (inet6Address.endsWith(":") && !inet6Address.endsWith("::"))) {
139            return false;
140        }
141        String[] octets = inet6Address.split(":");
142        if (containsCompressedZeroes) {
143            List<String> octetList = new ArrayList<>(Arrays.asList(octets));
144            if (inet6Address.endsWith("::")) {
145                // String.split() drops ending empty segments
146                octetList.add("");
147            } else if (inet6Address.startsWith("::") && !octetList.isEmpty()) {
148                octetList.remove(0);
149            }
150            octets = octetList.toArray(new String[0]);
151        }
152        if (octets.length > IPV6_MAX_HEX_GROUPS) {
153            return false;
154        }
155        int validOctets = 0;
156        int emptyOctets = 0;
157        for (int index = 0; index < octets.length; index++) {
158            String octet = octets[index];
159            if (octet.length() == 0) {
160                emptyOctets++;
161                if (emptyOctets > 1) {
162                    return false;
163                }
164            } else {
165                emptyOctets = 0;
166                if (octet.contains(".")) { // contains is Java 1.5+
167                    if (!inet6Address.endsWith(octet)) {
168                        return false;
169                    }
170                    if (index > octets.length - 1 || index > 6) { // CHECKSTYLE IGNORE MagicNumber
171                        // IPV4 occupies last two octets
172                        return false;
173                    }
174                    if (!isValidInet4Address(octet)) {
175                        return false;
176                    }
177                    validOctets += 2;
178                    continue;
179                }
180                if (octet.length() > IPV6_MAX_HEX_DIGITS_PER_GROUP) {
181                    return false;
182                }
183                int octetInt = 0;
184                try {
185                    octetInt = Integer.parseInt(octet, BASE_16);
186                } catch (NumberFormatException e) {
187                    return false;
188                }
189                if (octetInt < 0 || octetInt > MAX_UNSIGNED_SHORT) {
190                    return false;
191                }
192            }
193            validOctets++;
194        }
195        return validOctets >= IPV6_MAX_HEX_GROUPS || containsCompressedZeroes;
196    }
197}