summaryrefslogtreecommitdiff
path: root/src/com/android/messaging/util/EmailAddress.java
blob: c59170e13fa460ccd78184b084bc031e6849da24 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.messaging.util;

import com.google.common.base.CharMatcher;

/**
 * Parsing the email address
 */
public final class EmailAddress {
    private static final CharMatcher ANY_WHITESPACE = CharMatcher.anyOf(
            " \t\n\r\f\u000B\u0085\u2028\u2029\u200D\uFFEF\uFFFD\uFFFE\uFFFF");
    private static final CharMatcher EMAIL_ALLOWED_CHARS = CharMatcher.inRange((char) 0, (char) 31)
            .or(CharMatcher.is((char) 127))
            .or(CharMatcher.anyOf(" @,:<>"))
            .negate();

    /**
     * Helper method that checks whether the input text is valid email address.
     * TODO: This creates a new EmailAddress object each time
     * Need to make it more lightweight by pulling out the validation code into a static method.
     */
    public static boolean isValidEmail(final String emailText) {
        return new EmailAddress(emailText).isValid();
    }

    /**
     * Parses the specified email address. Internationalized addresses are treated as invalid.
     *
     * @param emailString A string representing just an email address. It should
     * not contain any other tokens. <code>"Name&lt;foo@example.org>"</code> won't be valid.
     */
    public EmailAddress(final String emailString) {
        this(emailString, false);
    }

    /**
     * Parses the specified email address.
     *
     * @param emailString A string representing just an email address. It should
     * not contain any other tokens. <code>"Name&lt;foo@example.org>"</code> won't be valid.
     * @param i18n Accept an internationalized address if it is true.
     */
    public EmailAddress(final String emailString, final boolean i18n) {
        allowI18n = i18n;
        valid = parseEmail(emailString);
    }

    /**
     * Parses the specified email address. Internationalized addresses are treated as invalid.
     *
     * @param user A string representing the username in the email prior to the '@' symbol
     * @param host A string representing the host following the '@' symbol
     */
    public EmailAddress(final String user, final String host) {
        this(user, host, false);
    }

    /**
     * Parses the specified email address.
     *
     * @param user A string representing the username in the email prior to the '@' symbol
     * @param host A string representing the host following the '@' symbol
     * @param i18n Accept an internationalized address if it is true.
     */
    public EmailAddress(final String user, final String host, final boolean i18n) {
        allowI18n = i18n;
        this.user = user;
        setHost(host);
    }

    protected boolean parseEmail(final String emailString) {
        // check for null
        if (emailString == null) {
            return false;
        }

        // Check for an '@' character. Get the last one, in case the local part is
        // quoted. See http://b/1944742.
        final int atIndex = emailString.lastIndexOf('@');
        if ((atIndex <= 0) || // no '@' character in the email address
                              // or @ on the first position
                (atIndex == (emailString.length() - 1))) { // last character, no host
            return false;
        }

        user = emailString.substring(0, atIndex);
        host = emailString.substring(atIndex + 1);

        return isValidInternal();
    }

    @Override
    public String toString() {
        return user + "@" + host;
    }

    /**
     * Ensure the email address is valid, conforming to current RFC2821 and
     * RFC2822 guidelines (although some iffy characters, like ! and ;, are
     * allowed because they are not technically prohibited in the RFC)
     */
    private boolean isValidInternal() {
        if ((user == null) || (host == null)) {
            return false;
        }

        if ((user.length() == 0) || (host.length() == 0)) {
            return false;
        }

        // check for white space in the host
        if (ANY_WHITESPACE.indexIn(host) >= 0) {
            return false;
        }

        // ensure the host is above the minimum length
        if (host.length() < 4) {
            return false;
        }

        final int firstDot = host.indexOf('.');

        // ensure host contains at least one dot
        if (firstDot == -1) {
            return false;
        }

        // check if the host contains two continuous dots.
        if (host.indexOf("..") >= 0) {
            return false;
        }

        // check if the first host char is a dot.
        if (host.charAt(0) == '.') {
            return false;
        }

        final int secondDot = host.indexOf(".", firstDot + 1);

        // if there's a dot at the end, there needs to be a second dot
        if (host.charAt(host.length() - 1) == '.' && secondDot == -1) {
            return false;
        }

        // Host must not have any disallowed characters; allowI18n dictates whether
        // host must be ASCII.
        if (!EMAIL_ALLOWED_CHARS.matchesAllOf(host)
                || (!allowI18n && !CharMatcher.ascii().matchesAllOf(host))) {
            return false;
        }

        if (user.startsWith("\"")) {
            if (!isQuotedUserValid()) {
                return false;
            }
        } else {
            // check for white space in the user
            if (ANY_WHITESPACE.indexIn(user) >= 0) {
                return false;
            }

            // the user cannot contain two continuous dots
            if (user.indexOf("..") >= 0) {
                return false;
            }

            // User must not have any disallowed characters; allow I18n dictates whether
            // user must be ASCII.
            if (!EMAIL_ALLOWED_CHARS.matchesAllOf(user)
                    || (!allowI18n && !CharMatcher.ascii().matchesAllOf(user))) {
                return false;
            }
        }
        return true;
    }

    private boolean isQuotedUserValid() {
        final int limit = user.length() - 1;
        if (limit < 1 || !user.endsWith("\"")) {
            return false;
        }

        // Unusual loop bounds (looking only at characters between the outer quotes,
        // not at either quote character). Plus, i is manipulated within the loop.
        for (int i = 1; i < limit; ++i) {
            final char ch = user.charAt(i);
            if (ch == '"' || ch == 127
                    // No non-whitespace control chars:
                    || (ch < 32 && !ANY_WHITESPACE.matches(ch))
                    // No non-ASCII chars, unless i18n is in effect:
                    || (ch >= 128 && !allowI18n)) {
                return false;
            } else if (ch == '\\') {
                if (i + 1 < limit) {
                    ++i; // Skip the quoted character
                } else {
                    // We have a trailing backslash -- so it can't be quoting anything.
                    return false;
                }
            }
        }

        return true;
    }

    @Override
    public boolean equals(final Object otherObject) {
        // Do an instance check first as an optimization.
        if (this == otherObject) {
            return true;
        }
        if (otherObject instanceof EmailAddress) {
            final EmailAddress otherAddress = (EmailAddress) otherObject;
            return toString().equals(otherAddress.toString());
        }
        return false;
    }

    @Override
    public int hashCode() {
        // Arbitrary hash code as a function of both host and user.
        return toString().hashCode();
    }

    // accessors
    public boolean isValid() {
        return valid;
    }

    public String getUser() {
        return user;
    }

    public String getHost() {
        return host;
    }

    // used to change the host on an email address and rechecks validity

    /**
     * Changes the host name of the email address and rechecks the address'
     * validity. Exercise caution when storing EmailAddress instances in
     * hash-keyed collections. Calling setHost() with a different host name will
     * change the return value of hashCode.
     *
     * @param hostName The new host name of the email address.
     */
    public void setHost(final String hostName) {
        host = hostName;
        valid = isValidInternal();
    }

    protected boolean valid = false;
    protected String user = null;
    protected String host = null;
    protected boolean allowI18n = false;
}