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;
018
019import java.io.Serializable;
020import java.util.Arrays;
021import java.util.HashSet;
022import java.util.Set;
023import java.util.regex.Matcher;
024import java.util.regex.Pattern;
025
026import org.apache.commons.validator.routines.InetAddressValidator;
027import org.apache.commons.validator.util.Flags;
028
029/**
030 * <p>Validates URLs.</p>
031 * Behavour of validation is modified by passing in options:
032 * <ul>
033 * <li>ALLOW_2_SLASHES - [FALSE]  Allows double '/' characters in the path
034 * component.</li>
035 * <li>NO_FRAGMENT- [FALSE]  By default fragments are allowed, if this option is
036 * included then fragments are flagged as illegal.</li>
037 * <li>ALLOW_ALL_SCHEMES - [FALSE] By default only http, https, and ftp are
038 * considered valid schemes.  Enabling this option will let any scheme pass validation.</li>
039 * </ul>
040 *
041 * <p>Originally based in on php script by Debbie Dyer, validation.php v1.2b, Date: 03/07/02,
042 * http://javascript.internet.com. However, this validation now bears little resemblance
043 * to the php original.</p>
044 * <pre>
045 *   Example of usage:
046 *   Construct a UrlValidator with valid schemes of "http", and "https".
047 *
048 *    String[] schemes = {"http","https"}.
049 *    UrlValidator urlValidator = new UrlValidator(schemes);
050 *    if (urlValidator.isValid("ftp://foo.bar.com/")) {
051 *       System.out.println("url is valid");
052 *    } else {
053 *       System.out.println("url is invalid");
054 *    }
055 *
056 *    prints "url is invalid"
057 *   If instead the default constructor is used.
058 *
059 *    UrlValidator urlValidator = new UrlValidator();
060 *    if (urlValidator.isValid("ftp://foo.bar.com/")) {
061 *       System.out.println("url is valid");
062 *    } else {
063 *       System.out.println("url is invalid");
064 *    }
065 *
066 *   prints out "url is valid"
067 *  </pre>
068 *
069 * @see
070 * <a href="http://www.ietf.org/rfc/rfc2396.txt">
071 *  Uniform Resource Identifiers (URI): Generic Syntax
072 * </a>
073 *
074 * @version $Revision: 1649191 $
075 * @since Validator 1.1
076 * @deprecated Use the new UrlValidator in the routines package. This class
077 * will be removed in a future release.
078 */
079public class UrlValidator implements Serializable {
080
081    private static final long serialVersionUID = 24137157400029593L;
082
083    /**
084     * Allows all validly formatted schemes to pass validation instead of
085     * supplying a set of valid schemes.
086     */
087    public static final int ALLOW_ALL_SCHEMES = 1 << 0;
088
089    /**
090     * Allow two slashes in the path component of the URL.
091     */
092    public static final int ALLOW_2_SLASHES = 1 << 1;
093
094    /**
095     * Enabling this options disallows any URL fragments.
096     */
097    public static final int NO_FRAGMENTS = 1 << 2;
098
099    private static final String ALPHA_CHARS = "a-zA-Z";
100
101// NOT USED   private static final String ALPHA_NUMERIC_CHARS = ALPHA_CHARS + "\\d";
102
103    private static final String SPECIAL_CHARS = ";/@&=,.?:+$";
104
105    private static final String VALID_CHARS = "[^\\s" + SPECIAL_CHARS + "]";
106
107    // Drop numeric, and  "+-." for now
108    private static final String AUTHORITY_CHARS_REGEX = "\\p{Alnum}\\-\\.";
109
110    private static final String ATOM = VALID_CHARS + '+';
111
112    /**
113     * This expression derived/taken from the BNF for URI (RFC2396).
114     */
115    private static final String URL_REGEX =
116            "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?";
117    //                                                                      12            3  4          5       6   7        8 9
118    private static final Pattern URL_PATTERN = Pattern.compile(URL_REGEX);
119
120    /**
121     * Schema/Protocol (ie. http:, ftp:, file:, etc).
122     */
123    private static final int PARSE_URL_SCHEME = 2;
124
125    /**
126     * Includes hostname/ip and port number.
127     */
128    private static final int PARSE_URL_AUTHORITY = 4;
129
130    private static final int PARSE_URL_PATH = 5;
131
132    private static final int PARSE_URL_QUERY = 7;
133
134    private static final int PARSE_URL_FRAGMENT = 9;
135
136    /**
137     * Protocol (ie. http:, ftp:,https:).
138     */
139    private static final Pattern SCHEME_PATTERN = Pattern.compile("^\\p{Alpha}[\\p{Alnum}\\+\\-\\.]*");
140
141    private static final String AUTHORITY_REGEX =
142       "^([" + AUTHORITY_CHARS_REGEX + "]*)(:\\d*)?(.*)?";
143    //                                                                            1                          2  3       4
144    private static final Pattern AUTHORITY_PATTERN = Pattern.compile(AUTHORITY_REGEX);
145
146    private static final int PARSE_AUTHORITY_HOST_IP = 1;
147
148    private static final int PARSE_AUTHORITY_PORT = 2;
149
150    /**
151     * Should always be empty.
152     */
153    private static final int PARSE_AUTHORITY_EXTRA = 3;
154
155    private static final Pattern PATH_PATTERN = Pattern.compile("^(/[-\\w:@&?=+,.!/~*'%$_;]*)?$");
156
157    private static final Pattern QUERY_PATTERN = Pattern.compile("^(.*)$");
158
159    private static final Pattern LEGAL_ASCII_PATTERN = Pattern.compile("^\\p{ASCII}+$");
160
161    private static final Pattern DOMAIN_PATTERN =
162            Pattern.compile("^" + ATOM + "(\\." + ATOM + ")*$");
163
164    private static final Pattern PORT_PATTERN = Pattern.compile("^:(\\d{1,5})$");
165
166    private static final Pattern ATOM_PATTERN = Pattern.compile("^(" + ATOM + ").*?$");
167
168    private static final Pattern ALPHA_PATTERN = Pattern.compile("^[" + ALPHA_CHARS + "]");
169
170    /**
171     * Holds the set of current validation options.
172     */
173    private final Flags options;
174
175    /**
176     * The set of schemes that are allowed to be in a URL.
177     */
178    private final Set allowedSchemes = new HashSet();
179
180    /**
181     * If no schemes are provided, default to this set.
182     */
183    protected String[] defaultSchemes = {"http", "https", "ftp"};
184
185    /**
186     * Create a UrlValidator with default properties.
187     */
188    public UrlValidator() {
189        this(null);
190    }
191
192    /**
193     * Behavior of validation is modified by passing in several strings options:
194     * @param schemes Pass in one or more url schemes to consider valid, passing in
195     *        a null will default to "http,https,ftp" being valid.
196     *        If a non-null schemes is specified then all valid schemes must
197     *        be specified. Setting the ALLOW_ALL_SCHEMES option will
198     *        ignore the contents of schemes.
199     */
200    public UrlValidator(String[] schemes) {
201        this(schemes, 0);
202    }
203
204    /**
205     * Initialize a UrlValidator with the given validation options.
206     * @param options The options should be set using the public constants declared in
207     * this class.  To set multiple options you simply add them together.  For example,
208     * ALLOW_2_SLASHES + NO_FRAGMENTS enables both of those options.
209     */
210    public UrlValidator(int options) {
211        this(null, options);
212    }
213
214    /**
215     * Behavour of validation is modified by passing in options:
216     * @param schemes The set of valid schemes.
217     * @param options The options should be set using the public constants declared in
218     * this class.  To set multiple options you simply add them together.  For example,
219     * ALLOW_2_SLASHES + NO_FRAGMENTS enables both of those options.
220     */
221    public UrlValidator(String[] schemes, int options) {
222        this.options = new Flags(options);
223
224        if (this.options.isOn(ALLOW_ALL_SCHEMES)) {
225            return;
226        }
227
228        if (schemes == null) {
229            schemes = this.defaultSchemes;
230        }
231
232        this.allowedSchemes.addAll(Arrays.asList(schemes));
233    }
234
235    /**
236     * <p>Checks if a field has a valid url address.</p>
237     *
238     * @param value The value validation is being performed on.  A <code>null</code>
239     * value is considered invalid.
240     * @return true if the url is valid.
241     */
242    public boolean isValid(String value) {
243        if (value == null) {
244            return false;
245        }
246        if (!LEGAL_ASCII_PATTERN.matcher(value).matches()) {
247           return false;
248        }
249
250        // Check the whole url address structure
251        Matcher urlMatcher = URL_PATTERN.matcher(value);
252        if (!urlMatcher.matches()) {
253            return false;
254        }
255
256        if (!isValidScheme(urlMatcher.group(PARSE_URL_SCHEME))) {
257            return false;
258        }
259
260        if (!isValidAuthority(urlMatcher.group(PARSE_URL_AUTHORITY))) {
261            return false;
262        }
263
264        if (!isValidPath(urlMatcher.group(PARSE_URL_PATH))) {
265            return false;
266        }
267
268        if (!isValidQuery(urlMatcher.group(PARSE_URL_QUERY))) {
269            return false;
270        }
271
272        if (!isValidFragment(urlMatcher.group(PARSE_URL_FRAGMENT))) {
273            return false;
274        }
275
276        return true;
277    }
278
279    /**
280     * Validate scheme. If schemes[] was initialized to a non null,
281     * then only those scheme's are allowed.  Note this is slightly different
282     * than for the constructor.
283     * @param scheme The scheme to validate.  A <code>null</code> value is considered
284     * invalid.
285     * @return true if valid.
286     */
287    protected boolean isValidScheme(String scheme) {
288        if (scheme == null) {
289            return false;
290        }
291
292        if (!SCHEME_PATTERN.matcher(scheme).matches()) {
293            return false;
294        }
295
296        if (options.isOff(ALLOW_ALL_SCHEMES) && !allowedSchemes.contains(scheme)) {
297            return false;
298        }
299
300        return true;
301    }
302
303    /**
304     * Returns true if the authority is properly formatted.  An authority is the combination
305     * of hostname and port.  A <code>null</code> authority value is considered invalid.
306     * @param authority Authority value to validate.
307     * @return true if authority (hostname and port) is valid.
308     */
309    protected boolean isValidAuthority(String authority) {
310        if (authority == null) {
311            return false;
312        }
313
314        InetAddressValidator inetAddressValidator =
315                InetAddressValidator.getInstance();
316
317        Matcher authorityMatcher = AUTHORITY_PATTERN.matcher(authority);
318        if (!authorityMatcher.matches()) {
319            return false;
320        }
321
322        boolean hostname = false;
323        // check if authority is IP address or hostname
324        String hostIP = authorityMatcher.group(PARSE_AUTHORITY_HOST_IP);
325        boolean ipV4Address = inetAddressValidator.isValid(hostIP);
326
327        if (!ipV4Address) {
328            // Domain is hostname name
329            hostname = DOMAIN_PATTERN.matcher(hostIP).matches();
330        }
331
332        //rightmost hostname will never start with a digit.
333        if (hostname) {
334            // LOW-TECH FIX FOR VALIDATOR-202
335            // TODO: Rewrite to use ArrayList and .add semantics: see VALIDATOR-203
336            char[] chars = hostIP.toCharArray();
337            int size = 1;
338            for(int i=0; i<chars.length; i++) {
339                if(chars[i] == '.') {
340                    size++;
341                }
342            }
343            String[] domainSegment = new String[size];
344            boolean match = true;
345            int segmentCount = 0;
346            int segmentLength = 0;
347
348            while (match) {
349                Matcher atomMatcher = ATOM_PATTERN.matcher(hostIP);
350                match = atomMatcher.matches();
351                if (match) {
352                    domainSegment[segmentCount] = atomMatcher.group(1);
353                    segmentLength = domainSegment[segmentCount].length() + 1;
354                    hostIP =
355                            (segmentLength >= hostIP.length())
356                            ? ""
357                            : hostIP.substring(segmentLength);
358
359                    segmentCount++;
360                }
361            }
362            String topLevel = domainSegment[segmentCount - 1];
363            if (topLevel.length() < 2 || topLevel.length() > 4) {
364                return false;
365            }
366
367            // First letter of top level must be a alpha
368            if (!ALPHA_PATTERN.matcher(topLevel.substring(0, 1)).matches()) {
369                return false;
370            }
371
372            // Make sure there's a host name preceding the authority.
373            if (segmentCount < 2) {
374                return false;
375            }
376        }
377
378        if (!hostname && !ipV4Address) {
379            return false;
380        }
381
382        String port = authorityMatcher.group(PARSE_AUTHORITY_PORT);
383        if (port != null && !PORT_PATTERN.matcher(port).matches()) {
384            return false;
385        }
386
387        String extra = authorityMatcher.group(PARSE_AUTHORITY_EXTRA);
388        if (!GenericValidator.isBlankOrNull(extra)) {
389            return false;
390        }
391
392        return true;
393    }
394
395    /**
396     * Returns true if the path is valid.  A <code>null</code> value is considered invalid.
397     * @param path Path value to validate.
398     * @return true if path is valid.
399     */
400    protected boolean isValidPath(String path) {
401        if (path == null) {
402            return false;
403        }
404
405        if (!PATH_PATTERN.matcher(path).matches()) {
406            return false;
407        }
408
409        int slash2Count = countToken("//", path);
410        if (options.isOff(ALLOW_2_SLASHES) && (slash2Count > 0)) {
411            return false;
412        }
413
414        int slashCount = countToken("/", path);
415        int dot2Count = countToken("..", path);
416        if (dot2Count > 0 && (slashCount - slash2Count - 1) <= dot2Count){
417            return false;
418        }
419
420        return true;
421    }
422
423    /**
424     * Returns true if the query is null or it's a properly formatted query string.
425     * @param query Query value to validate.
426     * @return true if query is valid.
427     */
428    protected boolean isValidQuery(String query) {
429        if (query == null) {
430            return true;
431        }
432
433        return QUERY_PATTERN.matcher(query).matches();
434    }
435
436    /**
437     * Returns true if the given fragment is null or fragments are allowed.
438     * @param fragment Fragment value to validate.
439     * @return true if fragment is valid.
440     */
441    protected boolean isValidFragment(String fragment) {
442        if (fragment == null) {
443            return true;
444        }
445
446        return options.isOff(NO_FRAGMENTS);
447    }
448
449    /**
450     * Returns the number of times the token appears in the target.
451     * @param token Token value to be counted.
452     * @param target Target value to count tokens in.
453     * @return the number of tokens.
454     */
455    protected int countToken(String token, String target) {
456        int tokenIndex = 0;
457        int count = 0;
458        while (tokenIndex != -1) {
459            tokenIndex = target.indexOf(token, tokenIndex);
460            if (tokenIndex > -1) {
461                tokenIndex++;
462                count++;
463            }
464        }
465        return count;
466    }
467}