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.apache.commons.validator.routines;
018
019import java.io.Serializable;
020import java.util.Collections;
021import java.util.HashSet;
022import java.util.Locale;
023import java.util.Set;
024import java.util.regex.Matcher;
025import java.util.regex.Pattern;
026
027/**
028 * <p><b>URL Validation</b> routines.</p>
029 * Behavior of validation is modified by passing in options:
030 * <ul>
031 * <li>ALLOW_2_SLASHES - [FALSE]  Allows double '/' characters in the path
032 * component.</li>
033 * <li>NO_FRAGMENT- [FALSE]  By default fragments are allowed, if this option is
034 * included then fragments are flagged as illegal.</li>
035 * <li>ALLOW_ALL_SCHEMES - [FALSE] By default only http, https, and ftp are
036 * considered valid schemes.  Enabling this option will let any scheme pass validation.</li>
037 * </ul>
038 *
039 * <p>Originally based in on php script by Debbie Dyer, validation.php v1.2b, Date: 03/07/02,
040 * http://javascript.internet.com. However, this validation now bears little resemblance
041 * to the php original.</p>
042 * <pre>
043 *   Example of usage:
044 *   Construct a UrlValidator with valid schemes of "http", and "https".
045 *
046 *    String[] schemes = {"http","https"}.
047 *    UrlValidator urlValidator = new UrlValidator(schemes);
048 *    if (urlValidator.isValid("ftp://foo.bar.com/")) {
049 *       System.out.println("url is valid");
050 *    } else {
051 *       System.out.println("url is invalid");
052 *    }
053 *
054 *    prints "url is invalid"
055 *   If instead the default constructor is used.
056 *
057 *    UrlValidator urlValidator = new UrlValidator();
058 *    if (urlValidator.isValid("ftp://foo.bar.com/")) {
059 *       System.out.println("url is valid");
060 *    } else {
061 *       System.out.println("url is invalid");
062 *    }
063 *
064 *   prints out "url is valid"
065 *  </pre>
066 *
067 * @see
068 * <a href="http://www.ietf.org/rfc/rfc2396.txt">
069 *  Uniform Resource Identifiers (URI): Generic Syntax
070 * </a>
071 *
072 * @version $Revision: 1649932 $
073 * @since Validator 1.4
074 */
075public class UrlValidator implements Serializable {
076
077    private static final long serialVersionUID = 7557161713937335013L;
078
079    /**
080     * Allows all validly formatted schemes to pass validation instead of
081     * supplying a set of valid schemes.
082     */
083    public static final long ALLOW_ALL_SCHEMES = 1 << 0;
084
085    /**
086     * Allow two slashes in the path component of the URL.
087     */
088    public static final long ALLOW_2_SLASHES = 1 << 1;
089
090    /**
091     * Enabling this options disallows any URL fragments.
092     */
093    public static final long NO_FRAGMENTS = 1 << 2;
094
095    /**
096     * Allow local URLs, such as http://localhost/ or http://machine/ .
097     * This enables a broad-brush check, for complex local machine name
098     *  validation requirements you should create your validator with
099     *  a {@link RegexValidator} instead ({@link #UrlValidator(RegexValidator, long)})
100     */
101    public static final long ALLOW_LOCAL_URLS = 1 << 3;
102
103    /**
104     * This expression derived/taken from the BNF for URI (RFC2396).
105     */
106    private static final String URL_REGEX =
107            "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?";
108    //        12            3  4          5       6   7        8 9
109    private static final Pattern URL_PATTERN = Pattern.compile(URL_REGEX);
110
111    /**
112     * Schema/Protocol (ie. http:, ftp:, file:, etc).
113     */
114    private static final int PARSE_URL_SCHEME = 2;
115
116    /**
117     * Includes hostname/ip and port number.
118     */
119    private static final int PARSE_URL_AUTHORITY = 4;
120
121    private static final int PARSE_URL_PATH = 5;
122
123    private static final int PARSE_URL_QUERY = 7;
124
125    private static final int PARSE_URL_FRAGMENT = 9;
126
127    /**
128     * Protocol scheme (e.g. http, ftp, https).
129     */
130    private static final String SCHEME_REGEX = "^\\p{Alpha}[\\p{Alnum}\\+\\-\\.]*";
131    private static final Pattern SCHEME_PATTERN = Pattern.compile(SCHEME_REGEX);
132
133    // Drop numeric, and  "+-." for now
134    // TODO does not allow for optional userinfo. 
135    // Validation of character set is done by isValidAuthority
136    private static final String AUTHORITY_CHARS_REGEX = "\\p{Alnum}\\-\\.";
137
138    private static final String AUTHORITY_REGEX =
139            "^([" + AUTHORITY_CHARS_REGEX + "]*)(:\\d*)?(.*)?";
140    //        1                                 2       3
141    private static final Pattern AUTHORITY_PATTERN = Pattern.compile(AUTHORITY_REGEX);
142
143    private static final int PARSE_AUTHORITY_HOST_IP = 1;
144
145    private static final int PARSE_AUTHORITY_PORT = 2;
146
147    /**
148     * Should always be empty. The code currently allows spaces.
149     */
150    private static final int PARSE_AUTHORITY_EXTRA = 3;
151
152    private static final String PATH_REGEX = "^(/[-\\w:@&?=+,.!/~*'%$_;\\(\\)]*)?$";
153    private static final Pattern PATH_PATTERN = Pattern.compile(PATH_REGEX);
154
155    private static final String QUERY_REGEX = "^(.*)$";
156    private static final Pattern QUERY_PATTERN = Pattern.compile(QUERY_REGEX);
157
158    private static final String PORT_REGEX = "^:(\\d{1,5})$";
159    private static final Pattern PORT_PATTERN = Pattern.compile(PORT_REGEX);
160
161    /**
162     * Holds the set of current validation options.
163     */
164    private final long options;
165
166    /**
167     * The set of schemes that are allowed to be in a URL.
168     */
169    private final Set allowedSchemes; // Must be lower-case
170
171    /**
172     * Regular expressions used to manually validate authorities if IANA
173     * domain name validation isn't desired.
174     */
175    private final RegexValidator authorityValidator;
176
177    /**
178     * If no schemes are provided, default to this set.
179     */
180    private static final String[] DEFAULT_SCHEMES = {"http", "https", "ftp"}; // Must be lower-case
181
182    /**
183     * Singleton instance of this class with default schemes and options.
184     */
185    private static final UrlValidator DEFAULT_URL_VALIDATOR = new UrlValidator();
186
187    /**
188     * Returns the singleton instance of this class with default schemes and options.
189     * @return singleton instance with default schemes and options
190     */
191    public static UrlValidator getInstance() {
192        return DEFAULT_URL_VALIDATOR;
193    }
194
195    /**
196     * Create a UrlValidator with default properties.
197     */
198    public UrlValidator() {
199        this(null);
200    }
201
202    /**
203     * Behavior of validation is modified by passing in several strings options:
204     * @param schemes Pass in one or more url schemes to consider valid, passing in
205     *        a null will default to "http,https,ftp" being valid.
206     *        If a non-null schemes is specified then all valid schemes must
207     *        be specified. Setting the ALLOW_ALL_SCHEMES option will
208     *        ignore the contents of schemes.
209     */
210    public UrlValidator(String[] schemes) {
211        this(schemes, 0L);
212    }
213
214    /**
215     * Initialize a UrlValidator with the given validation options.
216     * @param options The options should be set using the public constants declared in
217     * this class.  To set multiple options you simply add them together.  For example,
218     * ALLOW_2_SLASHES + NO_FRAGMENTS enables both of those options.
219     */
220    public UrlValidator(long options) {
221        this(null, null, options);
222    }
223
224    /**
225     * Behavior of validation is modified by passing in options:
226     * @param schemes The set of valid schemes. Ignored if the ALLOW_ALL_SCHEMES option is set.
227     * @param options The options should be set using the public constants declared in
228     * this class.  To set multiple options you simply add them together.  For example,
229     * ALLOW_2_SLASHES + NO_FRAGMENTS enables both of those options.
230     */
231    public UrlValidator(String[] schemes, long options) {
232        this(schemes, null, options);
233    }
234
235    /**
236     * Initialize a UrlValidator with the given validation options.
237     * @param authorityValidator Regular expression validator used to validate the authority part
238     * This allows the user to override the standard set of domains.
239     * @param options Validation options. Set using the public constants of this class.
240     * To set multiple options, simply add them together:
241     * <p><code>ALLOW_2_SLASHES + NO_FRAGMENTS</code></p>
242     * enables both of those options.
243     */
244    public UrlValidator(RegexValidator authorityValidator, long options) {
245        this(null, authorityValidator, options);
246    }
247
248    /**
249     * Customizable constructor. Validation behavior is modifed by passing in options.
250     * @param schemes the set of valid schemes. Ignored if the ALLOW_ALL_SCHEMES option is set.
251     * @param authorityValidator Regular expression validator used to validate the authority part
252     * @param options Validation options. Set using the public constants of this class.
253     * To set multiple options, simply add them together:
254     * <p><code>ALLOW_2_SLASHES + NO_FRAGMENTS</code></p>
255     * enables both of those options.
256     */
257    public UrlValidator(String[] schemes, RegexValidator authorityValidator, long options) {
258        this.options = options;
259
260        if (isOn(ALLOW_ALL_SCHEMES)) {
261            allowedSchemes = Collections.EMPTY_SET;
262        } else {
263            if (schemes == null) {
264                schemes = DEFAULT_SCHEMES;
265            }
266            allowedSchemes = new HashSet(schemes.length);
267            for(int i=0; i < schemes.length; i++) {
268                allowedSchemes.add(schemes[i].toLowerCase(Locale.ENGLISH));
269            }
270        }
271
272        this.authorityValidator = authorityValidator;
273    }
274
275    /**
276     * <p>Checks if a field has a valid url address.</p>
277     *
278     * Note that the method calls #isValidAuthority()
279     * which checks that the domain is valid.
280     *
281     * @param value The value validation is being performed on.  A <code>null</code>
282     * value is considered invalid.
283     * @return true if the url is valid.
284     */
285    public boolean isValid(String value) {
286        if (value == null) {
287            return false;
288        }
289
290        // Check the whole url address structure
291        Matcher urlMatcher = URL_PATTERN.matcher(value);
292        if (!urlMatcher.matches()) {
293            return false;
294        }
295
296        String scheme = urlMatcher.group(PARSE_URL_SCHEME);
297        if (!isValidScheme(scheme)) {
298            return false;
299        }
300
301        String authority = urlMatcher.group(PARSE_URL_AUTHORITY);
302        if ("file".equals(scheme) && "".equals(authority)) {
303            // Special case - file: allows an empty authority
304        } else {
305            // Validate the authority
306            if (!isValidAuthority(authority)) {
307                return false;
308            }
309        }
310
311        if (!isValidPath(urlMatcher.group(PARSE_URL_PATH))) {
312            return false;
313        }
314
315        if (!isValidQuery(urlMatcher.group(PARSE_URL_QUERY))) {
316            return false;
317        }
318
319        if (!isValidFragment(urlMatcher.group(PARSE_URL_FRAGMENT))) {
320            return false;
321        }
322
323        return true;
324    }
325
326    /**
327     * Validate scheme. If schemes[] was initialized to a non null,
328     * then only those schemes are allowed.
329     * Otherwise the default schemes are "http", "https", "ftp".
330     * Matching is case-blind.
331     * @param scheme The scheme to validate.  A <code>null</code> value is considered
332     * invalid.
333     * @return true if valid.
334     */
335    protected boolean isValidScheme(String scheme) {
336        if (scheme == null) {
337            return false;
338        }
339
340        // TODO could be removed if external schemes were checked in the ctor before being stored
341        if (!SCHEME_PATTERN.matcher(scheme).matches()) {
342            return false;
343        }
344
345        if (isOff(ALLOW_ALL_SCHEMES) && !allowedSchemes.contains(scheme.toLowerCase(Locale.ENGLISH))) {
346            return false;
347        }
348
349        return true;
350    }
351
352    /**
353     * Returns true if the authority is properly formatted.  An authority is the combination
354     * of hostname and port.  A <code>null</code> authority value is considered invalid.
355     * Note: this implementation validates the domain unless a RegexValidator was provided.
356     * If a RegexValidator was supplied and it matches, then the authority is regarded
357     * as valid with no further checks, otherwise the method checks against the
358     * AUTHORITY_PATTERN and the DomainValidator (ALLOW_LOCAL_URLS)
359     * @param authority Authority value to validate, alllows IDN
360     * @return true if authority (hostname and port) is valid.
361     */
362    protected boolean isValidAuthority(String authority) {
363        if (authority == null) {
364            return false;
365        }
366
367        // check manual authority validation if specified
368        if (authorityValidator != null && authorityValidator.isValid(authority)) {
369            return true;
370        }
371        // convert to ASCII if possible
372        final String authorityASCII = DomainValidator.unicodeToASCII(authority);
373
374        Matcher authorityMatcher = AUTHORITY_PATTERN.matcher(authorityASCII);
375        if (!authorityMatcher.matches()) {
376            return false;
377        }
378
379        String hostLocation = authorityMatcher.group(PARSE_AUTHORITY_HOST_IP);
380        // check if authority is hostname or IP address:
381        // try a hostname first since that's much more likely
382        DomainValidator domainValidator = DomainValidator.getInstance(isOn(ALLOW_LOCAL_URLS));
383        if (!domainValidator.isValid(hostLocation)) {
384            // try an IP address
385            InetAddressValidator inetAddressValidator =
386                InetAddressValidator.getInstance();
387            if (!inetAddressValidator.isValid(hostLocation)) {
388                // isn't either one, so the URL is invalid
389                return false;
390            }
391        }
392
393        String port = authorityMatcher.group(PARSE_AUTHORITY_PORT);
394        if (port != null && !PORT_PATTERN.matcher(port).matches()) {
395            return false;
396        }
397
398        String extra = authorityMatcher.group(PARSE_AUTHORITY_EXTRA);
399        if (extra != null && extra.trim().length() > 0){
400            return false;
401        }
402
403        return true;
404    }
405
406    /**
407     * Returns true if the path is valid.  A <code>null</code> value is considered invalid.
408     * @param path Path value to validate.
409     * @return true if path is valid.
410     */
411    protected boolean isValidPath(String path) {
412        if (path == null) {
413            return false;
414        }
415
416        if (!PATH_PATTERN.matcher(path).matches()) {
417            return false;
418        }
419
420        int slash2Count = countToken("//", path);
421        if (isOff(ALLOW_2_SLASHES) && (slash2Count > 0)) {
422            return false;
423        }
424
425        int slashCount = countToken("/", path);
426        int dot2Count = countToken("..", path);
427        if (dot2Count > 0 && (slashCount - slash2Count - 1) <= dot2Count) {
428            return false;
429        }
430
431        return true;
432    }
433
434    /**
435     * Returns true if the query is null or it's a properly formatted query string.
436     * @param query Query value to validate.
437     * @return true if query is valid.
438     */
439    protected boolean isValidQuery(String query) {
440        if (query == null) {
441            return true;
442        }
443
444        return QUERY_PATTERN.matcher(query).matches();
445    }
446
447    /**
448     * Returns true if the given fragment is null or fragments are allowed.
449     * @param fragment Fragment value to validate.
450     * @return true if fragment is valid.
451     */
452    protected boolean isValidFragment(String fragment) {
453        if (fragment == null) {
454            return true;
455        }
456
457        return isOff(NO_FRAGMENTS);
458    }
459
460    /**
461     * Returns the number of times the token appears in the target.
462     * @param token Token value to be counted.
463     * @param target Target value to count tokens in.
464     * @return the number of tokens.
465     */
466    protected int countToken(String token, String target) {
467        int tokenIndex = 0;
468        int count = 0;
469        while (tokenIndex != -1) {
470            tokenIndex = target.indexOf(token, tokenIndex);
471            if (tokenIndex > -1) {
472                tokenIndex++;
473                count++;
474            }
475        }
476        return count;
477    }
478
479    /**
480     * Tests whether the given flag is on.  If the flag is not a power of 2
481     * (ie. 3) this tests whether the combination of flags is on.
482     *
483     * @param flag Flag value to check.
484     *
485     * @return whether the specified flag value is on.
486     */
487    private boolean isOn(long flag) {
488        return (options & flag) > 0;
489    }
490
491    /**
492     * Tests whether the given flag is off.  If the flag is not a power of 2
493     * (ie. 3) this tests whether the combination of flags is off.
494     *
495     * @param flag Flag value to check.
496     *
497     * @return whether the specified flag value is off.
498     */
499    private boolean isOff(long flag) {
500        return (options & flag) == 0;
501    }
502}