]> WPIA git - gigi.git/blob - src/club/wpia/gigi/email/EmailProvider.java
Merge "upd: remove 'browser install'"
[gigi.git] / src / club / wpia / gigi / email / EmailProvider.java
1 package club.wpia.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 club.wpia.gigi.crypto.SMIME;
23 import club.wpia.gigi.database.GigiPreparedStatement;
24 import club.wpia.gigi.util.DNSUtil;
25 import club.wpia.gigi.util.DomainAssessment;
26 import club.wpia.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, final String address) throws IOException {
87         if ( !isValidMailAddress(address)) {
88             try (GigiPreparedStatement statmt = new GigiPreparedStatement("INSERT INTO `emailPinglog` SET `when`=NOW(), `email`=?, `result`=?, `uid`=?, `type`='fast'::`emailPingType`, `status`='failed'::`pingState`")) {
89                 statmt.setString(1, address);
90                 statmt.setString(2, "Invalid email address provided");
91                 statmt.setInt(3, forUid);
92                 statmt.execute();
93             }
94             return FAIL;
95         }
96
97         String[] parts = address.split("@", 2);
98         String domain = parts[1];
99
100         String[] mxhosts;
101         try {
102             mxhosts = DNSUtil.getMXEntries(domain);
103         } catch (NamingException e1) {
104             return "MX lookup for your hostname failed.";
105         }
106         sortMX(mxhosts);
107
108         for (String host : mxhosts) {
109             host = host.split(" ", 2)[1];
110             if (host.endsWith(".")) {
111                 host = host.substring(0, host.length() - 1);
112             } else {
113                 return "Strange MX records.";
114             }
115
116             class SMTPSessionHandler {
117
118                 public boolean detectedSTARTTLS = false;
119
120                 public boolean initiateSMTPSession(BufferedReader r, PrintWriter w) throws IOException {
121                     String line;
122
123                     if ( !SendMail.readSMTPResponse(r, 220)) {
124                         return false;
125                     }
126
127                     w.print("EHLO " + SystemKeywords.SMTP_NAME + "\r\n");
128                     w.flush();
129
130                     detectedSTARTTLS = false;
131                     do {
132                         line = r.readLine();
133                         if (line == null) {
134                             break;
135                         }
136                         detectedSTARTTLS |= line.substring(4).equals("STARTTLS");
137                     } while (line.startsWith("250-"));
138
139                     if (line == null || !line.startsWith("250 ")) {
140                         return false;
141                     }
142
143                     return true;
144                 }
145
146                 public boolean trySendEmail(BufferedReader r, PrintWriter w) throws IOException {
147                     w.print("MAIL FROM: <" + SystemKeywords.SMTP_PSEUDO_FROM + ">\r\n");
148                     w.flush();
149
150                     if ( !SendMail.readSMTPResponse(r, 250)) {
151                         return false;
152                     }
153
154                     w.print("RCPT TO: <" + address + ">\r\n");
155                     w.flush();
156
157                     if ( !SendMail.readSMTPResponse(r, 250)) {
158                         return false;
159                     }
160
161                     w.print("QUIT\r\n");
162                     w.flush();
163
164                     if ( !SendMail.readSMTPResponse(r, 221)) {
165                         return false;
166                     }
167
168                     return true;
169                 }
170
171             }
172
173             SMTPSessionHandler sh = new SMTPSessionHandler();
174
175             try (Socket plainSocket = new Socket(host, 25); //
176                     BufferedReader plainReader = new BufferedReader(new InputStreamReader(plainSocket.getInputStream(), "UTF-8")); //
177                     PrintWriter plainWriter = new PrintWriter(new OutputStreamWriter(plainSocket.getOutputStream(), "UTF-8"))) {
178
179                 if ( !sh.initiateSMTPSession(plainReader, plainWriter)) {
180                     continue;
181                 }
182
183                 boolean canSend = false;
184
185                 if (sh.detectedSTARTTLS) {
186                     plainWriter.print("STARTTLS\r\n");
187                     plainWriter.flush();
188
189                     if ( !SendMail.readSMTPResponse(plainReader, 220)) {
190                         continue;
191                     }
192
193                     try (Socket tlsSocket = ((SSLSocketFactory) SSLSocketFactory.getDefault()).createSocket(plainSocket, host, 25, true); //
194                             BufferedReader tlsReader = new BufferedReader(new InputStreamReader(tlsSocket.getInputStream(), "UTF-8")); //
195                             PrintWriter tlsWriter = new PrintWriter(new OutputStreamWriter(tlsSocket.getOutputStream(), "UTF-8"))) {
196
197                         tlsWriter.print("EHLO " + SystemKeywords.SMTP_NAME + "\r\n");
198                         tlsWriter.flush();
199
200                         if ( !SendMail.readSMTPResponse(tlsReader, 250)) {
201                             continue;
202                         }
203
204                         canSend = sh.trySendEmail(tlsReader, tlsWriter);
205                     }
206                 } else {
207                     canSend = sh.trySendEmail(plainReader, plainWriter);
208                 }
209
210                 if ( !canSend) {
211                     continue;
212                 }
213
214                 try (GigiPreparedStatement statmt = new GigiPreparedStatement("INSERT INTO `emailPinglog` SET `when`=NOW(), `email`=?, `result`=?, `uid`=?, `type`='fast', `status`='success'::`pingState`")) {
215                     statmt.setString(1, address);
216                     statmt.setString(2, OK);
217                     statmt.setInt(3, forUid);
218                     statmt.execute();
219                 }
220
221                 return OK;
222             }
223         }
224
225         try (GigiPreparedStatement statmt = new GigiPreparedStatement("INSERT INTO `emailPinglog` SET `when`=NOW(), `email`=?, `result`=?, `uid`=?, `type`='fast'::`emailPingType`, `status`='failed'::`pingState`")) {
226             statmt.setString(1, address);
227             statmt.setString(2, "Failed to make a connection to the mail server");
228             statmt.setInt(3, forUid);
229             statmt.execute();
230         }
231
232         return FAIL;
233     }
234
235     private static void sortMX(String[] mxhosts) {
236         Arrays.sort(mxhosts, new Comparator<String>() {
237
238             @Override
239             public int compare(String o1, String o2) {
240                 int i1 = Integer.parseInt(o1.split(" ")[0]);
241                 int i2 = Integer.parseInt(o2.split(" ")[0]);
242                 return Integer.compare(i1, i2);
243             }
244         });
245     }
246
247     public static boolean isValidMailAddress(String address) {
248         if ( !MAIL_ADDRESS.matcher(address).matches()) {
249             return false;
250         }
251
252         String[] parts = address.split("@", 2);
253
254         String local = parts[0];
255         String domain = parts[1];
256
257         if ( !MAIL_LOCAL.matcher(local).matches()) {
258             return false;
259         }
260
261         for (String domainPart : domain.split("\\.", -1)) {
262             if ( !DomainAssessment.isValidDomainPart(domainPart)) {
263                 return false;
264             }
265         }
266
267         return true;
268     }
269
270 }