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