1. /*
  2. * $Header: /home/cvs/jakarta-commons/validator/src/share/org/apache/commons/validator/UrlValidator.java,v 1.19 2004/02/21 17:10:29 rleland Exp $
  3. * $Revision: 1.19 $
  4. * $Date: 2004/02/21 17:10:29 $
  5. *
  6. * ====================================================================
  7. * Copyright 2001-2004 The Apache Software Foundation
  8. *
  9. * Licensed under the Apache License, Version 2.0 (the "License");
  10. * you may not use this file except in compliance with the License.
  11. * You may obtain a copy of the License at
  12. *
  13. * http://www.apache.org/licenses/LICENSE-2.0
  14. *
  15. * Unless required by applicable law or agreed to in writing, software
  16. * distributed under the License is distributed on an "AS IS" BASIS,
  17. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. * See the License for the specific language governing permissions and
  19. * limitations under the License.
  20. */
  21. package org.apache.commons.validator;
  22. import java.io.Serializable;
  23. import java.util.Arrays;
  24. import java.util.HashSet;
  25. import java.util.Set;
  26. import org.apache.commons.validator.util.Flags;
  27. import org.apache.oro.text.perl.Perl5Util;
  28. /**
  29. * <p>Validates URLs.</p>
  30. * Behavour of validation is modified by passing in options:
  31. * <li>ALLOW_2_SLASHES - [FALSE] Allows double '/' characters in the path
  32. * component.</li>
  33. * <li>NO_FRAGMENT- [FALSE] By default fragments are allowed, if this option is
  34. * included then fragments are flagged as illegal.</li>
  35. * <li>ALLOW_ALL_SCHEMES - [FALSE] By default only http, https, and ftp are
  36. * considered valid schemes. Enabling this option will let any scheme pass validation.</li>
  37. *
  38. * <p>Originally based in on php script by Debbie Dyer, validation.php v1.2b, Date: 03/07/02,
  39. * http://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")) {
  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")) {
  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 Validator 1.1
  72. */
  73. public class UrlValidator implements Serializable {
  74. /**
  75. * Allows all validly formatted schemes to pass validation instead of supplying a
  76. * set of valid schemes.
  77. */
  78. public static final int ALLOW_ALL_SCHEMES = 1 << 0;
  79. /**
  80. * Allow two slashes in the path component of the URL.
  81. */
  82. public static final int ALLOW_2_SLASHES = 1 << 1;
  83. /**
  84. * Enabling this options disallows any URL fragments.
  85. */
  86. public static final int NO_FRAGMENTS = 1 << 2;
  87. private static final String ALPHA_CHARS = "a-zA-Z";
  88. private static final String ALPHA_NUMERIC_CHARS = ALPHA_CHARS + "\\d";
  89. private static final String SPECIAL_CHARS = ";/@&=,.?:+$";
  90. private static final String VALID_CHARS = "[^\\s" + SPECIAL_CHARS + "]";
  91. private static final String SCHEME_CHARS = ALPHA_CHARS;
  92. // Drop numeric, and "+-." for now
  93. private static final String AUTHORITY_CHARS = ALPHA_NUMERIC_CHARS + "\\-\\.";
  94. private static final String ATOM = VALID_CHARS + '+';
  95. /**
  96. * This expression derived/taken from the BNF for URI (RFC2396).
  97. */
  98. private static final String URL_PATTERN =
  99. "/^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?/";
  100. // 12 3 4 5 6 7 8 9
  101. /**
  102. * Schema/Protocol (ie. http:, ftp:, file:, etc).
  103. */
  104. private static final int PARSE_URL_SCHEME = 2;
  105. /**
  106. * Includes hostname/ip and port number.
  107. */
  108. private static final int PARSE_URL_AUTHORITY = 4;
  109. private static final int PARSE_URL_PATH = 5;
  110. private static final int PARSE_URL_QUERY = 7;
  111. private static final int PARSE_URL_FRAGMENT = 9;
  112. /**
  113. * Protocol (ie. http:, ftp:,https:).
  114. */
  115. private static final String SCHEME_PATTERN = "/^[" + SCHEME_CHARS + "]/";
  116. private static final String AUTHORITY_PATTERN =
  117. "/^([" + AUTHORITY_CHARS + "]*)(:\\d*)?(.*)?/";
  118. // 1 2 3 4
  119. private static final int PARSE_AUTHORITY_HOST_IP = 1;
  120. private static final int PARSE_AUTHORITY_PORT = 2;
  121. /**
  122. * Should always be empty.
  123. */
  124. private static final int PARSE_AUTHORITY_EXTRA = 3;
  125. private static final String PATH_PATTERN =
  126. "/^(/[-a-zA-Z0-9_:@&?=+,.!/~*'%$]*)$/";
  127. private static final String QUERY_PATTERN = "/^(.*)$/";
  128. private static final String LEGAL_ASCII_PATTERN = "/^[\\000-\\177]+$/";
  129. private static final String IP_V4_DOMAIN_PATTERN =
  130. "/^(\\d{1,3})[.](\\d{1,3})[.](\\d{1,3})[.](\\d{1,3})$/";
  131. private static final String DOMAIN_PATTERN =
  132. "/^" + ATOM + "(\\." + ATOM + ")*$/";
  133. private static final String PORT_PATTERN = "/^:(\\d{1,5})$/";
  134. private static final String ATOM_PATTERN = "/(" + ATOM + ")/";
  135. private static final String ALPHA_PATTERN = "/^[" + ALPHA_CHARS + "]/";
  136. /**
  137. * Holds the set of current validation options.
  138. */
  139. private Flags options = null;
  140. /**
  141. * The set of schemes that are allowed to be in a URL.
  142. */
  143. private Set allowedSchemes = new HashSet();
  144. /**
  145. * If no schemes are provided, default to this set.
  146. */
  147. protected String[] defaultSchemes = {"http", "https", "ftp"};
  148. /**
  149. * Create a UrlValidator with default properties.
  150. */
  151. public UrlValidator() {
  152. this(null);
  153. }
  154. /**
  155. * Behavior of validation is modified by passing in several strings options:
  156. * @param schemes Pass in one or more url schemes to consider valid, passing in
  157. * a null will default to "http,https,ftp" being valid.
  158. * If a non-null schemes is specified then all valid schemes must
  159. * be specified. Setting the ALLOW_ALL_SCHEMES option will
  160. * ignore the contents of schemes.
  161. */
  162. public UrlValidator(String[] schemes) {
  163. this(schemes, 0);
  164. }
  165. /**
  166. * Initialize a UrlValidator with the given validation options.
  167. * @param options The options should be set using the public constants declared in
  168. * this class. To set multiple options you simply add them together. For example,
  169. * ALLOW_2_SLASHES + NO_FRAGMENTS enables both of those options.
  170. */
  171. public UrlValidator(int options) {
  172. this(null, options);
  173. }
  174. /**
  175. * Behavour of validation is modified by passing in options:
  176. * @param schemes The set of valid schemes.
  177. * @param options The options should be set using the public constants declared in
  178. * this class. To set multiple options you simply add them together. For example,
  179. * ALLOW_2_SLASHES + NO_FRAGMENTS enables both of those options.
  180. */
  181. public UrlValidator(String[] schemes, int options) {
  182. this.options = new Flags(options);
  183. if (this.options.isOn(ALLOW_ALL_SCHEMES)) {
  184. return;
  185. }
  186. if (schemes == null) {
  187. schemes = this.defaultSchemes;
  188. }
  189. this.allowedSchemes.addAll(Arrays.asList(schemes));
  190. }
  191. /**
  192. * <p>Checks if a field has a valid url address.</p>
  193. *
  194. * @param value The value validation is being performed on. A <code>null</code>
  195. * value is considered invalid.
  196. * @return true if the url is valid.
  197. */
  198. public boolean isValid(String value) {
  199. if (value == null) {
  200. return false;
  201. }
  202. Perl5Util matchUrlPat = new Perl5Util();
  203. Perl5Util matchAsciiPat = new Perl5Util();
  204. if (!matchAsciiPat.match(LEGAL_ASCII_PATTERN, value)) {
  205. return false;
  206. }
  207. // Check the whole url address structure
  208. if (!matchUrlPat.match(URL_PATTERN, value)) {
  209. return false;
  210. }
  211. if (!isValidScheme(matchUrlPat.group(PARSE_URL_SCHEME))) {
  212. return false;
  213. }
  214. if (!isValidAuthority(matchUrlPat.group(PARSE_URL_AUTHORITY))) {
  215. return false;
  216. }
  217. if (!isValidPath(matchUrlPat.group(PARSE_URL_PATH))) {
  218. return false;
  219. }
  220. if (!isValidQuery(matchUrlPat.group(PARSE_URL_QUERY))) {
  221. return false;
  222. }
  223. if (!isValidFragment(matchUrlPat.group(PARSE_URL_FRAGMENT))) {
  224. return false;
  225. }
  226. return true;
  227. }
  228. /**
  229. * Validate scheme. If schemes[] was initialized to a non null,
  230. * then only those scheme's are allowed. Note this is slightly different
  231. * than for the constructor.
  232. * @param scheme The scheme to validate. A <code>null</code> value is considered
  233. * invalid.
  234. * @return true if valid.
  235. */
  236. protected boolean isValidScheme(String scheme) {
  237. if (scheme == null) {
  238. return false;
  239. }
  240. Perl5Util schemeMatcher = new Perl5Util();
  241. if (!schemeMatcher.match(SCHEME_PATTERN, scheme)) {
  242. return false;
  243. }
  244. if (this.options.isOff(ALLOW_ALL_SCHEMES)) {
  245. if (!this.allowedSchemes.contains(scheme)) {
  246. return false;
  247. }
  248. }
  249. return true;
  250. }
  251. /**
  252. * Returns true if the authority is properly formatted. An authority is the combination
  253. * of hostname and port. A <code>null</code> authority value is considered invalid.
  254. */
  255. protected boolean isValidAuthority(String authority) {
  256. if (authority == null) {
  257. return false;
  258. }
  259. Perl5Util authorityMatcher = new Perl5Util();
  260. Perl5Util matchIPV4Pat = new Perl5Util();
  261. if (!authorityMatcher.match(AUTHORITY_PATTERN, authority)) {
  262. return false;
  263. }
  264. boolean ipV4Address = false;
  265. boolean hostname = false;
  266. // check if authority is IP address or hostname
  267. String hostIP = authorityMatcher.group(PARSE_AUTHORITY_HOST_IP);
  268. ipV4Address = matchIPV4Pat.match(IP_V4_DOMAIN_PATTERN, hostIP);
  269. if (ipV4Address) {
  270. // this is an IP address so check components
  271. for (int i = 1; i <= 4; i++) {
  272. String ipSegment = matchIPV4Pat.group(i);
  273. if (ipSegment == null || ipSegment.length() <= 0) {
  274. return false;
  275. }
  276. try {
  277. if (Integer.parseInt(ipSegment) > 255) {
  278. return false;
  279. }
  280. } catch(NumberFormatException e) {
  281. return false;
  282. }
  283. }
  284. } else {
  285. // Domain is hostname name
  286. Perl5Util domainMatcher = new Perl5Util();
  287. hostname = domainMatcher.match(DOMAIN_PATTERN, hostIP);
  288. }
  289. //rightmost hostname will never start with a digit.
  290. if (hostname) {
  291. String[] domainSegment = new String[10];
  292. boolean match = true;
  293. int segmentCount = 0;
  294. int segmentLength = 0;
  295. Perl5Util atomMatcher = new Perl5Util();
  296. while (match) {
  297. match = atomMatcher.match(ATOM_PATTERN, hostIP);
  298. if (match) {
  299. domainSegment[segmentCount] = atomMatcher.group(1);
  300. segmentLength = domainSegment[segmentCount].length() + 1;
  301. hostIP =
  302. (segmentLength >= hostIP.length())
  303. ? ""
  304. : hostIP.substring(segmentLength);
  305. segmentCount++;
  306. }
  307. }
  308. String topLevel = domainSegment[segmentCount - 1];
  309. if (topLevel.length() < 2 || topLevel.length() > 4) {
  310. return false;
  311. }
  312. // First letter of top level must be a alpha
  313. Perl5Util alphaMatcher = new Perl5Util();
  314. if (!alphaMatcher.match(ALPHA_PATTERN, topLevel.substring(0, 1))) {
  315. return false;
  316. }
  317. // Make sure there's a host name preceding the authority.
  318. if (segmentCount < 2) {
  319. return false;
  320. }
  321. }
  322. if (!hostname && !ipV4Address) {
  323. return false;
  324. }
  325. String port = authorityMatcher.group(PARSE_AUTHORITY_PORT);
  326. if (port != null) {
  327. Perl5Util portMatcher = new Perl5Util();
  328. if (!portMatcher.match(PORT_PATTERN, port)) {
  329. return false;
  330. }
  331. }
  332. String extra = authorityMatcher.group(PARSE_AUTHORITY_EXTRA);
  333. if (!GenericValidator.isBlankOrNull(extra)) {
  334. return false;
  335. }
  336. return true;
  337. }
  338. /**
  339. * Returns true if the path is valid. A <code>null</code> value is considered invalid.
  340. */
  341. protected boolean isValidPath(String path) {
  342. if (path == null) {
  343. return false;
  344. }
  345. Perl5Util pathMatcher = new Perl5Util();
  346. if (!pathMatcher.match(PATH_PATTERN, path)) {
  347. return false;
  348. }
  349. if (path.endsWith("/")) {
  350. return false;
  351. }
  352. int slash2Count = countToken("//", path);
  353. if (this.options.isOff(ALLOW_2_SLASHES) && (slash2Count > 0)) {
  354. return false;
  355. }
  356. int slashCount = countToken("/", path);
  357. int dot2Count = countToken("..", path);
  358. if (dot2Count > 0) {
  359. if ((slashCount - slash2Count - 1) <= dot2Count) {
  360. return false;
  361. }
  362. }
  363. return true;
  364. }
  365. /**
  366. * Returns true if the query is null or it's a properly formatted query string.
  367. */
  368. protected boolean isValidQuery(String query) {
  369. if (query == null) {
  370. return true;
  371. }
  372. Perl5Util queryMatcher = new Perl5Util();
  373. return queryMatcher.match(QUERY_PATTERN, query);
  374. }
  375. /**
  376. * Returns true if the given fragment is null or fragments are allowed.
  377. */
  378. protected boolean isValidFragment(String fragment) {
  379. if (fragment == null) {
  380. return true;
  381. }
  382. return this.options.isOff(NO_FRAGMENTS);
  383. }
  384. /**
  385. * Returns the number of times the token appears in the target.
  386. */
  387. protected int countToken(String token, String target) {
  388. int tokenIndex = 0;
  389. int count = 0;
  390. while (tokenIndex != -1) {
  391. tokenIndex = target.indexOf(token, tokenIndex);
  392. if (tokenIndex > -1) {
  393. tokenIndex++;
  394. count++;
  395. }
  396. }
  397. return count;
  398. }
  399. }