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