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