]> WPIA git - gigi.git/blob - src/org/cacert/gigi/email/EmailProvider.java
chg: Be more liberal in what email addresses are accepted.
[gigi.git] / src / org / cacert / gigi / email / EmailProvider.java
1 package org.cacert.gigi.email;
2
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.io.InputStreamReader;
6 import java.io.OutputStreamWriter;
7 import java.io.PrintWriter;
8 import java.net.Socket;
9 import java.security.GeneralSecurityException;
10 import java.security.Key;
11 import java.security.PrivateKey;
12 import java.security.cert.Certificate;
13 import java.security.cert.X509Certificate;
14 import java.util.Arrays;
15 import java.util.Comparator;
16 import java.util.Properties;
17 import java.util.regex.Pattern;
18
19 import javax.naming.NamingException;
20 import javax.net.ssl.SSLSocketFactory;
21
22 import org.cacert.gigi.crypto.SMIME;
23 import org.cacert.gigi.database.GigiPreparedStatement;
24 import org.cacert.gigi.util.DNSUtil;
25 import org.cacert.gigi.util.DomainAssessment;
26
27 public abstract class EmailProvider {
28
29     public abstract void sendMail(String to, String subject, String message, String replyto, String toname, String fromname, String errorsto, boolean extra) throws IOException;
30
31     private static EmailProvider instance;
32
33     private X509Certificate c;
34
35     private PrivateKey k;
36
37     protected void init(Certificate c, Key k) {
38         this.c = (X509Certificate) c;
39         this.k = (PrivateKey) k;
40     }
41
42     protected final void sendSigned(String contents, PrintWriter output) throws IOException, GeneralSecurityException {
43         if (k == null || c == null) {
44             output.println("Content-Transfer-Encoding: base64");
45             output.println();
46             output.print(contents);
47         } else {
48             SMIME.smime(contents, k, c, output);
49         }
50     }
51
52     public static EmailProvider getInstance() {
53         return instance;
54     }
55
56     protected static void setInstance(EmailProvider instance) {
57         EmailProvider.instance = instance;
58     }
59
60     public static void initSystem(Properties conf, Certificate cert, Key pk) {
61         try {
62             Class<?> c = Class.forName(conf.getProperty("emailProvider"));
63             EmailProvider ep = (EmailProvider) c.getDeclaredConstructor(Properties.class).newInstance(conf);
64             ep.init(cert, pk);
65             instance = ep;
66         } catch (ReflectiveOperationException e) {
67             e.printStackTrace();
68         }
69     }
70
71     public static final String OK = "OK";
72
73     public static final String FAIL = "FAIL";
74
75     private static final String MAIL_P_RFC_WORD = "[A-Za-z0-9\\+\\.!#$%&'*/=?^_`|~{}-]+";
76
77     private static final String MAIL_P_RFC_LOCAL = MAIL_P_RFC_WORD + "(?:\\." + MAIL_P_RFC_WORD + ")*";
78
79     private static final String MAIL_P_RFC_LABEL = "(?!(?!xn)..--|-)(?:[A-Za-z0-9-]+)(?<!-)";
80
81     private static final String MAIL_P_RFC_ADDRESS = MAIL_P_RFC_LOCAL + "@(?:" + MAIL_P_RFC_LABEL + "\\.)+" + MAIL_P_RFC_LABEL + "\\.?";
82
83     private static final Pattern MAIL_LOCAL = Pattern.compile("^" + MAIL_P_RFC_LOCAL + "$");
84
85     private static final Pattern MAIL_ADDRESS = Pattern.compile("^" + MAIL_P_RFC_ADDRESS + "$");
86
87     public String checkEmailServer(int forUid, String address) throws IOException {
88         if (isValidMailAddress(address)) {
89             String[] parts = address.split("@", 2);
90             String domain = parts[1];
91
92             String[] mxhosts;
93             try {
94                 mxhosts = DNSUtil.getMXEntries(domain);
95             } catch (NamingException e1) {
96                 return "MX lookup for your hostname failed.";
97             }
98             sortMX(mxhosts);
99
100             for (String host : mxhosts) {
101                 host = host.split(" ", 2)[1];
102                 if (host.endsWith(".")) {
103                     host = host.substring(0, host.length() - 1);
104                 } else {
105                     return "Strange MX records.";
106                 }
107                 try (Socket s = new Socket(host, 25);
108                         BufferedReader br0 = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8"));//
109                         PrintWriter pw0 = new PrintWriter(new OutputStreamWriter(s.getOutputStream(), "UTF-8"))) {
110                     BufferedReader br = br0;
111                     PrintWriter pw = pw0;
112                     String line;
113                     if ( !SendMail.readSMTPResponse(br, 220)) {
114                         continue;
115                     }
116
117                     pw.print("EHLO www.cacert.org\r\n");
118                     pw.flush();
119                     boolean starttls = false;
120                     do {
121                         line = br.readLine();
122                         if (line == null) {
123                             break;
124                         }
125                         starttls |= line.substring(4).equals("STARTTLS");
126                     } while (line.startsWith("250-"));
127                     if (line == null || !line.startsWith("250 ")) {
128                         continue;
129                     }
130
131                     if (starttls) {
132                         pw.print("STARTTLS\r\n");
133                         pw.flush();
134                         if ( !SendMail.readSMTPResponse(br, 220)) {
135                             continue;
136                         }
137                         Socket s1 = ((SSLSocketFactory) SSLSocketFactory.getDefault()).createSocket(s, host, 25, true);
138                         br = new BufferedReader(new InputStreamReader(s1.getInputStream(), "UTF-8"));
139                         pw = new PrintWriter(new OutputStreamWriter(s1.getOutputStream(), "UTF-8"));
140                         pw.print("EHLO www.cacert.org\r\n");
141                         pw.flush();
142                         if ( !SendMail.readSMTPResponse(br, 250)) {
143                             continue;
144                         }
145                     }
146
147                     pw.print("MAIL FROM: <returns@cacert.org>\r\n");
148                     pw.flush();
149
150                     if ( !SendMail.readSMTPResponse(br, 250)) {
151                         continue;
152                     }
153                     pw.print("RCPT TO: <" + address + ">\r\n");
154                     pw.flush();
155
156                     if ( !SendMail.readSMTPResponse(br, 250)) {
157                         continue;
158                     }
159                     pw.print("QUIT\r\n");
160                     pw.flush();
161                     if ( !SendMail.readSMTPResponse(br, 221)) {
162                         continue;
163                     }
164
165                     try (GigiPreparedStatement statmt = new GigiPreparedStatement("INSERT INTO `emailPinglog` SET `when`=NOW(), `email`=?, `result`=?, `uid`=?, `type`='fast', `status`=?::`pingState`")) {
166                         statmt.setString(1, address);
167                         statmt.setString(2, line);
168                         statmt.setInt(3, forUid);
169                         statmt.setString(4, "success");
170                         statmt.execute();
171                     }
172
173                     if (line == null || !line.startsWith("250")) {
174                         return line;
175                     } else {
176                         return OK;
177                     }
178                 }
179
180             }
181         }
182         try (GigiPreparedStatement statmt = new GigiPreparedStatement("INSERT INTO `emailPinglog` SET `when`=NOW(), `email`=?, `result`=?, `uid`=?, `type`='fast', `status`=?::`pingState`")) {
183             statmt.setString(1, address);
184             statmt.setString(2, "Failed to make a connection to the mail server");
185             statmt.setInt(3, forUid);
186             statmt.setString(4, "failed");
187             statmt.execute();
188         }
189         return FAIL;
190     }
191
192     private static void sortMX(String[] mxhosts) {
193         Arrays.sort(mxhosts, new Comparator<String>() {
194
195             @Override
196             public int compare(String o1, String o2) {
197                 int i1 = Integer.parseInt(o1.split(" ")[0]);
198                 int i2 = Integer.parseInt(o2.split(" ")[0]);
199                 return Integer.compare(i1, i2);
200             }
201         });
202     }
203
204     public static boolean isValidMailAddress(String address) {
205         if ( !MAIL_ADDRESS.matcher(address).matches()) {
206             return false;
207         }
208
209         String[] parts = address.split("@", 2);
210
211         String local = parts[0];
212         String domain = parts[1];
213
214         if ( !MAIL_LOCAL.matcher(local).matches()) {
215             return false;
216         }
217
218         for (String domainPart : domain.split("\\.", -1)) {
219             if ( !DomainAssessment.isValidDomainPart(domainPart)) {
220                 return false;
221             }
222         }
223
224         return true;
225     }
226
227 }