    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 *      https://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.util.regex.Matcher;
    020import java.util.regex.Pattern;
    021
    022import org.apache.commons.validator.routines.InetAddressValidator;
    023
    024/**
    025 * Perform email validations.
    026 * <p>
    027 * This class is a Singleton; you can retrieve the instance via the getInstance() method.
    028 * </p>
    029 * <p>
    030 * Based on a script by <a href="mailto:stamhankar@hotmail.com">Sandeep V. Tamhankar</a>
    031 * https://javascript.internet.com
    032 * </p>
    033 * <p>
    034 * This implementation is not guaranteed to catch all possible errors in an email address.
    035 * For example, an address like nobody@noplace.somedog will pass validator, even though there
    036 * is no TLD "somedog"
    037 * </p>.
    038 *
    039 * @since 1.1
    040 * @deprecated Use the new EmailValidator in the routines package. This class
    041 * will be removed in a future release.
    042 */
    043@Deprecated
    044public class EmailValidator {
    045
    046    private static final String SPECIAL_CHARS = "\\p{Cc}\\(\\)<>@,;:'\\\\\\\"\\.\\[\\]";
    047    private static final String VALID_CHARS = "[^\\s" + SPECIAL_CHARS + "]";
    048    private static final String QUOTED_USER = "(\"[^\"\\p{Cc}]*\")";
    049    private static final String ATOM = VALID_CHARS + '+';
    050    private static final String WORD = "((" + VALID_CHARS + "|')+|" + QUOTED_USER + ")";
    051
    052// NOT USED   private static final Pattern LEGAL_ASCII_PATTERN = Pattern.compile("^\\p{ASCII}+$");
    053// NOT USED   private static final Pattern EMAIL_PATTERN = Pattern.compile("^(.+)@(.+)$");
    054    private static final Pattern IP_DOMAIN_PATTERN = Pattern.compile("^\\[(.*)\\]$");
    055    private static final Pattern TLD_PATTERN = Pattern.compile("^([a-zA-Z]+)$");
    056
    057    private static final Pattern USER_PATTERN = Pattern.compile("^\\s*" + WORD + "(\\." + WORD + ")*$");
    058    private static final Pattern DOMAIN_PATTERN = Pattern.compile("^" + ATOM + "(\\." + ATOM + ")*\\s*$");
    059    private static final Pattern ATOM_PATTERN = Pattern.compile("(" + ATOM + ")");
    060
    061    /**
    062     * Singleton instance of this class.
    063     */
    064    private static final EmailValidator EMAIL_VALIDATOR = new EmailValidator();
    065
    066    /**
    067     * Returns the Singleton instance of this validator.
    068     *
    069     * @return singleton instance of this validator.
    070     */
    071    public static EmailValidator getInstance() {
    072        return EMAIL_VALIDATOR;
    073    }
    074
    075    /**
    076     * Protected constructor for subclasses to use.
    077     */
    078    protected EmailValidator() {
    079    }
    080
    081    /**
    082     * Checks if a field has a valid e-mail address.
    083     *
    084     * @param email The value validation is being performed on.  A {@code null}
    085     * value is considered invalid.
    086     * @return true if the email address is valid.
    087     */
    088    public boolean isValid(final String email) {
    089        return org.apache.commons.validator.routines.EmailValidator.getInstance().isValid(email);
    090    }
    091
    092    /**
    093     * Returns true if the domain component of an email address is valid.
    094     *
    095     * @param domain being validated.
    096     * @return true if the email address's domain is valid.
    097     */
    098    protected boolean isValidDomain(final String domain) {
    099        boolean symbolic = false;
    100
    101        // see if domain is an IP address in brackets
    102        final Matcher ipDomainMatcher = IP_DOMAIN_PATTERN.matcher(domain);
    103
    104        if (ipDomainMatcher.matches()) {
    105            final InetAddressValidator inetAddressValidator =
    106                    InetAddressValidator.getInstance();
    107            if (inetAddressValidator.isValid(ipDomainMatcher.group(1))) {
    108                return true;
    109            }
    110        } else {
    111            // Domain is symbolic name
    112            symbolic = DOMAIN_PATTERN.matcher(domain).matches();
    113        }
    114
    115        if (!symbolic || !isValidSymbolicDomain(domain)) {
    116            return false;
    117        }
    118
    119        return true;
    120    }
    121
    122    /**
    123     * Validates an IP address. Returns true if valid.
    124     *
    125     * @param ipAddress IP address
    126     * @return true if the ip address is valid.
    127     */
    128    protected boolean isValidIpAddress(final String ipAddress) {
    129        final Matcher ipAddressMatcher = IP_DOMAIN_PATTERN.matcher(ipAddress);
    130        for (int i = 1; i <= 4; i++) { // CHECKSTYLE IGNORE MagicNumber
    131            final String ipSegment = ipAddressMatcher.group(i);
    132            if (ipSegment == null || ipSegment.isEmpty()) {
    133                return false;
    134            }
    135
    136            int iIpSegment = 0;
    137
    138            try {
    139                iIpSegment = Integer.parseInt(ipSegment);
    140            } catch (final NumberFormatException e) {
    141                return false;
    142            }
    143
    144            if (iIpSegment > 255) { // CHECKSTYLE IGNORE MagicNumber
    145                return false;
    146            }
    147
    148        }
    149        return true;
    150    }
    151
    152    /**
    153     * Validates a symbolic domain name.  Returns true if it's valid.
    154     *
    155     * @param domain symbolic domain name
    156     * @return true if the symbolic domain name is valid.
    157     */
    158    protected boolean isValidSymbolicDomain(String domain) {
    159        final String[] domainSegment = new String[10]; // CHECKSTYLE IGNORE MagicNumber
    160        boolean match = true;
    161        int i = 0;
    162        final Matcher atomMatcher = ATOM_PATTERN.matcher(domain);
    163        while (match) {
    164            match = atomMatcher.matches();
    165            if (match) {
    166                domainSegment[i] = atomMatcher.group(1);
    167                final int l = domainSegment[i].length() + 1;
    168                domain =
    169                        l >= domain.length()
    170                        ? ""
    171                        : domain.substring(l);
    172
    173                i++;
    174            }
    175        }
    176
    177        final int len = i;
    178
    179        // Make sure there's a host name preceding the domain.
    180        if (len < 2) {
    181            return false;
    182        }
    183
    184        final String tld = domainSegment[len - 1];
    185        if (tld.length() <= 1 || ! TLD_PATTERN.matcher(tld).matches()) {
    186            return false;
    187        }
    188
    189        return true;
    190    }
    191
    192    /**
    193     * Returns true if the user component of an email address is valid.
    194     *
    195     * @param user being validated
    196     * @return true if the username is valid.
    197     */
    198    protected boolean isValidUser(final String user) {
    199        return USER_PATTERN.matcher(user).matches();
    200    }
    201
    202    /**
    203     * Recursively remove comments, and replace with a single space. The simpler regexps in the Email Addressing FAQ are imperfect - they will miss escaped
    204     * chars in atoms, for example. Derived From Mail::RFC822::Address
    205     *
    206     * @param emailStr The email address
    207     * @return address with comments removed.
    208     */
    209    protected String stripComments(final String emailStr) {
    210        String result = emailStr;
    211        final String commentPat = "^((?:[^\"\\\\]|\\\\.)*(?:\"(?:[^\"\\\\]|\\\\.)*\"(?:[^\"\\\\]|\111111\\\\.)*)*)\\((?:[^()\\\\]|\\\\.)*\\)/";
    212        final Pattern commentMatcher = Pattern.compile(commentPat);
    213
    214        while (commentMatcher.matcher(result).matches()) {
    215            result = result.replaceFirst(commentPat, "\1 ");
    216        }
    217        return result;
    218    }
    219}