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