UrlValidator.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.validator;

  18. import java.io.Serializable;
  19. import java.util.Arrays;
  20. import java.util.HashSet;
  21. import java.util.Set;
  22. import java.util.regex.Matcher;
  23. import java.util.regex.Pattern;

  24. import org.apache.commons.validator.routines.InetAddressValidator;
  25. import org.apache.commons.validator.util.Flags;

  26. /**
  27.  * <p>Validates URLs.</p>
  28.  * Behavour of validation is modified by passing in options:
  29.  * <ul>
  30.  * <li>ALLOW_2_SLASHES - [FALSE]  Allows double '/' characters in the path
  31.  * component.</li>
  32.  * <li>NO_FRAGMENT- [FALSE]  By default fragments are allowed, if this option is
  33.  * included then fragments are flagged as illegal.</li>
  34.  * <li>ALLOW_ALL_SCHEMES - [FALSE] By default only http, https, and ftp are
  35.  * considered valid schemes.  Enabling this option will let any scheme pass validation.</li>
  36.  * </ul>
  37.  *
  38.  * <p>Originally based in on php script by Debbie Dyer, validation.php v1.2b, Date: 03/07/02,
  39.  * https://javascript.internet.com. However, this validation now bears little resemblance
  40.  * to the php original.</p>
  41.  * <pre>
  42.  *   Example of usage:
  43.  *   Construct a UrlValidator with valid schemes of "http", and "https".
  44.  *
  45.  *    String[] schemes = {"http","https"}.
  46.  *    UrlValidator urlValidator = new UrlValidator(schemes);
  47.  *    if (urlValidator.isValid("ftp://foo.bar.com/")) {
  48.  *       System.out.println("URL is valid");
  49.  *    } else {
  50.  *       System.out.println("URL is invalid");
  51.  *    }
  52.  *
  53.  *    prints "URL is invalid"
  54.  *   If instead the default constructor is used.
  55.  *
  56.  *    UrlValidator urlValidator = new UrlValidator();
  57.  *    if (urlValidator.isValid("ftp://foo.bar.com/")) {
  58.  *       System.out.println("URL is valid");
  59.  *    } else {
  60.  *       System.out.println("URL is invalid");
  61.  *    }
  62.  *
  63.  *   prints out "URL is valid"
  64.  *  </pre>
  65.  *
  66.  * @see
  67.  * <a href="http://www.ietf.org/rfc/rfc2396.txt">
  68.  *  Uniform Resource Identifiers (URI): Generic Syntax
  69.  * </a>
  70.  *
  71.  * @since 1.1
  72.  * @deprecated Use the new UrlValidator in the routines package. This class
  73.  * will be removed in a future release.
  74.  */
  75. @Deprecated
  76. public class UrlValidator implements Serializable {

  77.     private static final long serialVersionUID = 24137157400029593L;

  78.     /**
  79.      * Allows all validly formatted schemes to pass validation instead of
  80.      * supplying a set of valid schemes.
  81.      */
  82.     public static final int ALLOW_ALL_SCHEMES = 1 << 0;

  83.     /**
  84.      * Allow two slashes in the path component of the URL.
  85.      */
  86.     public static final int ALLOW_2_SLASHES = 1 << 1;

  87.     /**
  88.      * Enabling this options disallows any URL fragments.
  89.      */
  90.     public static final int NO_FRAGMENTS = 1 << 2;

  91.     private static final String ALPHA_CHARS = "a-zA-Z";

  92. // NOT USED   private static final String ALPHA_NUMERIC_CHARS = ALPHA_CHARS + "\\d";

  93.     private static final String SPECIAL_CHARS = ";/@&=,.?:+$";

  94.     private static final String VALID_CHARS = "[^\\s" + SPECIAL_CHARS + "]";

  95.     // Drop numeric, and  "+-." for now
  96.     private static final String AUTHORITY_CHARS_REGEX = "\\p{Alnum}\\-\\.";

  97.     private static final String ATOM = VALID_CHARS + '+';

  98.     /**
  99.      * This expression derived/taken from the BNF for URI (RFC2396).
  100.      */
  101.     private static final String URL_REGEX =
  102.             "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?";
  103.     //                                                                      12            3  4          5       6   7        8 9
  104.     private static final Pattern URL_PATTERN = Pattern.compile(URL_REGEX);

  105.     /**
  106.      * Schema/Protocol (ie. http:, ftp:, file:, etc).
  107.      */
  108.     private static final int PARSE_URL_SCHEME = 2;

  109.     /**
  110.      * Includes hostname/ip and port number.
  111.      */
  112.     private static final int PARSE_URL_AUTHORITY = 4;

  113.     private static final int PARSE_URL_PATH = 5;

  114.     private static final int PARSE_URL_QUERY = 7;

  115.     private static final int PARSE_URL_FRAGMENT = 9;

  116.     /**
  117.      * Protocol (ie. http:, ftp:,https:).
  118.      */
  119.     private static final Pattern SCHEME_PATTERN = Pattern.compile("^\\p{Alpha}[\\p{Alnum}\\+\\-\\.]*");

  120.     private static final String AUTHORITY_REGEX =
  121.        "^([" + AUTHORITY_CHARS_REGEX + "]*)(:\\d*)?(.*)?";
  122.     //                                                                            1                          2  3       4
  123.     private static final Pattern AUTHORITY_PATTERN = Pattern.compile(AUTHORITY_REGEX);

  124.     private static final int PARSE_AUTHORITY_HOST_IP = 1;

  125.     private static final int PARSE_AUTHORITY_PORT = 2;

  126.     /**
  127.      * Should always be empty.
  128.      */
  129.     private static final int PARSE_AUTHORITY_EXTRA = 3;

  130.     private static final Pattern PATH_PATTERN = Pattern.compile("^(/[-\\w:@&?=+,.!/~*'%$_;]*)?$");

  131.     private static final Pattern QUERY_PATTERN = Pattern.compile("^(.*)$");

  132.     private static final Pattern LEGAL_ASCII_PATTERN = Pattern.compile("^\\p{ASCII}+$");

  133.     private static final Pattern DOMAIN_PATTERN =
  134.             Pattern.compile("^" + ATOM + "(\\." + ATOM + ")*$");

  135.     private static final Pattern PORT_PATTERN = Pattern.compile("^:(\\d{1,5})$");

  136.     private static final Pattern ATOM_PATTERN = Pattern.compile("^(" + ATOM + ").*?$");

  137.     private static final Pattern ALPHA_PATTERN = Pattern.compile("^[" + ALPHA_CHARS + "]");

  138.     /**
  139.      * Holds the set of current validation options.
  140.      */
  141.     private final Flags options;

  142.     /**
  143.      * The set of schemes that are allowed to be in a URL.
  144.      */
  145.     private final Set<String> allowedSchemes = new HashSet<>();

  146.     /**
  147.      * If no schemes are provided, default to this set.
  148.      */
  149.     protected String[] defaultSchemes = {"http", "https", "ftp"};

  150.     /**
  151.      * Create a UrlValidator with default properties.
  152.      */
  153.     public UrlValidator() {
  154.         this(null);
  155.     }

  156.     /**
  157.      * Initialize a UrlValidator with the given validation options.
  158.      * @param options The options should be set using the public constants declared in
  159.      * this class.  To set multiple options you simply add them together.  For example,
  160.      * ALLOW_2_SLASHES + NO_FRAGMENTS enables both of those options.
  161.      */
  162.     public UrlValidator(final int options) {
  163.         this(null, options);
  164.     }

  165.     /**
  166.      * Behavior of validation is modified by passing in several strings options:
  167.      * @param schemes Pass in one or more URL schemes to consider valid, passing in
  168.      *        a null will default to "http,https,ftp" being valid.
  169.      *        If a non-null schemes is specified then all valid schemes must
  170.      *        be specified. Setting the ALLOW_ALL_SCHEMES option will
  171.      *        ignore the contents of schemes.
  172.      */
  173.     public UrlValidator(final String[] schemes) {
  174.         this(schemes, 0);
  175.     }

  176.     /**
  177.      * Behavour of validation is modified by passing in options:
  178.      * @param schemes The set of valid schemes.
  179.      * @param options The options should be set using the public constants declared in
  180.      * this class.  To set multiple options you simply add them together.  For example,
  181.      * ALLOW_2_SLASHES + NO_FRAGMENTS enables both of those options.
  182.      */
  183.     public UrlValidator(String[] schemes, final int options) {
  184.         this.options = new Flags(options);

  185.         if (this.options.isOn(ALLOW_ALL_SCHEMES)) {
  186.             return;
  187.         }

  188.         if (schemes == null) {
  189.             schemes = this.defaultSchemes;
  190.         }

  191.         this.allowedSchemes.addAll(Arrays.asList(schemes));
  192.     }

  193.     /**
  194.      * Returns the number of times the token appears in the target.
  195.      * @param token Token value to be counted.
  196.      * @param target Target value to count tokens in.
  197.      * @return the number of tokens.
  198.      */
  199.     protected int countToken(final String token, final String target) {
  200.         int tokenIndex = 0;
  201.         int count = 0;
  202.         while (tokenIndex != -1) {
  203.             tokenIndex = target.indexOf(token, tokenIndex);
  204.             if (tokenIndex > -1) {
  205.                 tokenIndex++;
  206.                 count++;
  207.             }
  208.         }
  209.         return count;
  210.     }

  211.     /**
  212.      * <p>Checks if a field has a valid URL address.</p>
  213.      *
  214.      * @param value The value validation is being performed on.  A {@code null}
  215.      * value is considered invalid.
  216.      * @return true if the URL is valid.
  217.      */
  218.     public boolean isValid(final String value) {
  219.         if (value == null) {
  220.             return false;
  221.         }
  222.         if (!LEGAL_ASCII_PATTERN.matcher(value).matches()) {
  223.            return false;
  224.         }

  225.         // Check the whole url address structure
  226.         final Matcher urlMatcher = URL_PATTERN.matcher(value);
  227.         if (!urlMatcher.matches()) {
  228.             return false;
  229.         }

  230.         if (!isValidScheme(urlMatcher.group(PARSE_URL_SCHEME))) {
  231.             return false;
  232.         }

  233.         if (!isValidAuthority(urlMatcher.group(PARSE_URL_AUTHORITY))) {
  234.             return false;
  235.         }

  236.         if (!isValidPath(urlMatcher.group(PARSE_URL_PATH))) {
  237.             return false;
  238.         }

  239.         if (!isValidQuery(urlMatcher.group(PARSE_URL_QUERY))) {
  240.             return false;
  241.         }

  242.         if (!isValidFragment(urlMatcher.group(PARSE_URL_FRAGMENT))) {
  243.             return false;
  244.         }

  245.         return true;
  246.     }

  247.     /**
  248.      * Returns true if the authority is properly formatted.  An authority is the combination
  249.      * of hostname and port.  A {@code null} authority value is considered invalid.
  250.      * @param authority Authority value to validate.
  251.      * @return true if authority (hostname and port) is valid.
  252.      */
  253.     protected boolean isValidAuthority(final String authority) {
  254.         if (authority == null) {
  255.             return false;
  256.         }

  257.         final InetAddressValidator inetAddressValidator =
  258.                 InetAddressValidator.getInstance();

  259.         final Matcher authorityMatcher = AUTHORITY_PATTERN.matcher(authority);
  260.         if (!authorityMatcher.matches()) {
  261.             return false;
  262.         }

  263.         boolean hostname = false;
  264.         // check if authority is IP address or hostname
  265.         String hostIP = authorityMatcher.group(PARSE_AUTHORITY_HOST_IP);
  266.         final boolean ipV4Address = inetAddressValidator.isValid(hostIP);

  267.         if (!ipV4Address) {
  268.             // Domain is hostname name
  269.             hostname = DOMAIN_PATTERN.matcher(hostIP).matches();
  270.         }

  271.         //rightmost hostname will never start with a digit.
  272.         if (hostname) {
  273.             // LOW-TECH FIX FOR VALIDATOR-202
  274.             // TODO: Rewrite to use ArrayList and .add semantics: see VALIDATOR-203
  275.             final char[] chars = hostIP.toCharArray();
  276.             int size = 1;
  277.             for (final char element : chars) {
  278.                 if (element == '.') {
  279.                     size++;
  280.                 }
  281.             }
  282.             final String[] domainSegment = new String[size];
  283.             boolean match = true;
  284.             int segmentCount = 0;
  285.             int segmentLength = 0;

  286.             while (match) {
  287.                 final Matcher atomMatcher = ATOM_PATTERN.matcher(hostIP);
  288.                 match = atomMatcher.matches();
  289.                 if (match) {
  290.                     domainSegment[segmentCount] = atomMatcher.group(1);
  291.                     segmentLength = domainSegment[segmentCount].length() + 1;
  292.                     hostIP =
  293.                             segmentLength >= hostIP.length()
  294.                             ? ""
  295.                             : hostIP.substring(segmentLength);

  296.                     segmentCount++;
  297.                 }
  298.             }
  299.             final String topLevel = domainSegment[segmentCount - 1];
  300.             if (topLevel.length() < 2 || topLevel.length() > 4) { // CHECKSTYLE IGNORE MagicNumber (deprecated code)
  301.                 return false;
  302.             }

  303.             // First letter of top level must be a alpha
  304.             if (!ALPHA_PATTERN.matcher(topLevel.substring(0, 1)).matches()) {
  305.                 return false;
  306.             }

  307.             // Make sure there's a host name preceding the authority.
  308.             if (segmentCount < 2) {
  309.                 return false;
  310.             }
  311.         }

  312.         if (!hostname && !ipV4Address) {
  313.             return false;
  314.         }

  315.         final String port = authorityMatcher.group(PARSE_AUTHORITY_PORT);
  316.         if (port != null && !PORT_PATTERN.matcher(port).matches()) {
  317.             return false;
  318.         }

  319.         final String extra = authorityMatcher.group(PARSE_AUTHORITY_EXTRA);
  320.         if (!GenericValidator.isBlankOrNull(extra)) {
  321.             return false;
  322.         }

  323.         return true;
  324.     }

  325.     /**
  326.      * Returns true if the given fragment is null or fragments are allowed.
  327.      * @param fragment Fragment value to validate.
  328.      * @return true if fragment is valid.
  329.      */
  330.     protected boolean isValidFragment(final String fragment) {
  331.         if (fragment == null) {
  332.             return true;
  333.         }

  334.         return options.isOff(NO_FRAGMENTS);
  335.     }

  336.     /**
  337.      * Returns true if the path is valid.  A {@code null} value is considered invalid.
  338.      * @param path Path value to validate.
  339.      * @return true if path is valid.
  340.      */
  341.     protected boolean isValidPath(final String path) {
  342.         if (path == null) {
  343.             return false;
  344.         }

  345.         if (!PATH_PATTERN.matcher(path).matches()) {
  346.             return false;
  347.         }

  348.         final int slash2Count = countToken("//", path);
  349.         if (options.isOff(ALLOW_2_SLASHES) && slash2Count > 0) {
  350.             return false;
  351.         }

  352.         final int slashCount = countToken("/", path);
  353.         final int dot2Count = countToken("..", path);
  354.         if (dot2Count > 0 && slashCount - slash2Count - 1 <= dot2Count) {
  355.             return false;
  356.         }

  357.         return true;
  358.     }

  359.     /**
  360.      * Returns true if the query is null or it's a properly formatted query string.
  361.      * @param query Query value to validate.
  362.      * @return true if query is valid.
  363.      */
  364.     protected boolean isValidQuery(final String query) {
  365.         if (query == null) {
  366.             return true;
  367.         }

  368.         return QUERY_PATTERN.matcher(query).matches();
  369.     }

  370.     /**
  371.      * Validate scheme. If schemes[] was initialized to a non null,
  372.      * then only those scheme's are allowed.  Note this is slightly different
  373.      * than for the constructor.
  374.      * @param scheme The scheme to validate.  A {@code null} value is considered
  375.      * invalid.
  376.      * @return true if valid.
  377.      */
  378.     protected boolean isValidScheme(final String scheme) {
  379.         if (scheme == null) {
  380.             return false;
  381.         }

  382.         if (!SCHEME_PATTERN.matcher(scheme).matches()) {
  383.             return false;
  384.         }

  385.         if (options.isOff(ALLOW_ALL_SCHEMES) && !allowedSchemes.contains(scheme)) {
  386.             return false;
  387.         }

  388.         return true;
  389.     }
  390. }