1 package club.wpia.gigi.email;
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;
19 import javax.naming.NamingException;
20 import javax.net.ssl.SSLSocketFactory;
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;
28 public abstract class EmailProvider {
30 public abstract void sendMail(String to, String subject, String message, String replyto, String toname, String fromname, String errorsto, boolean extra) throws IOException;
32 private static EmailProvider instance;
34 private X509Certificate c;
38 protected void init(Certificate c, Key k) {
39 this.c = (X509Certificate) c;
40 this.k = (PrivateKey) k;
43 protected final void sendSigned(String contents, PrintWriter output) throws IOException, GeneralSecurityException {
44 if (k == null || c == null) {
45 output.print(contents);
47 SMIME.smime(contents, k, c, output);
51 public static EmailProvider getInstance() {
55 protected static void setInstance(EmailProvider instance) {
56 EmailProvider.instance = instance;
59 public static void initSystem(Properties conf, Certificate cert, Key pk) {
61 Class<?> c = Class.forName(conf.getProperty("emailProvider"));
62 EmailProvider ep = (EmailProvider) c.getDeclaredConstructor(Properties.class).newInstance(conf);
65 } catch (ReflectiveOperationException e) {
70 public static final String OK = "OK";
72 public static final String FAIL = "FAIL";
74 private static final String MAIL_P_RFC_WORD = "[A-Za-z0-9\\+\\.!#$%&'*/=?^_`|~{}-]+";
76 private static final String MAIL_P_RFC_LOCAL = MAIL_P_RFC_WORD + "(?:\\." + MAIL_P_RFC_WORD + ")*";
78 private static final String MAIL_P_RFC_LABEL = "(?!(?!xn)..--|-)(?:[A-Za-z0-9-]+)(?<!-)";
80 private static final String MAIL_P_RFC_ADDRESS = MAIL_P_RFC_LOCAL + "@(?:" + MAIL_P_RFC_LABEL + "\\.)+" + MAIL_P_RFC_LABEL + "\\.?";
82 private static final Pattern MAIL_LOCAL = Pattern.compile("^" + MAIL_P_RFC_LOCAL + "$");
84 private static final Pattern MAIL_ADDRESS = Pattern.compile("^" + MAIL_P_RFC_ADDRESS + "$");
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);
97 String[] parts = address.split("@", 2);
98 String domain = parts[1];
102 mxhosts = DNSUtil.getMXEntries(domain);
103 } catch (NamingException e1) {
104 return "MX lookup for your hostname failed.";
108 for (String host : mxhosts) {
109 host = host.split(" ", 2)[1];
110 if (host.endsWith(".")) {
111 host = host.substring(0, host.length() - 1);
113 return "Strange MX records.";
116 class SMTPSessionHandler {
118 public boolean detectedSTARTTLS = false;
120 public boolean initiateSMTPSession(BufferedReader r, PrintWriter w) throws IOException {
123 if ( !SendMail.readSMTPResponse(r, 220)) {
127 w.print("EHLO " + SystemKeywords.SMTP_NAME + "\r\n");
130 detectedSTARTTLS = false;
136 detectedSTARTTLS |= line.substring(4).equals("STARTTLS");
137 } while (line.startsWith("250-"));
139 if (line == null || !line.startsWith("250 ")) {
146 public boolean trySendEmail(BufferedReader r, PrintWriter w) throws IOException {
147 w.print("MAIL FROM: <" + SystemKeywords.SMTP_PSEUDO_FROM + ">\r\n");
150 if ( !SendMail.readSMTPResponse(r, 250)) {
154 w.print("RCPT TO: <" + address + ">\r\n");
157 if ( !SendMail.readSMTPResponse(r, 250)) {
164 if ( !SendMail.readSMTPResponse(r, 221)) {
173 SMTPSessionHandler sh = new SMTPSessionHandler();
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"))) {
179 if ( !sh.initiateSMTPSession(plainReader, plainWriter)) {
183 boolean canSend = false;
185 if (sh.detectedSTARTTLS) {
186 plainWriter.print("STARTTLS\r\n");
189 if ( !SendMail.readSMTPResponse(plainReader, 220)) {
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"))) {
197 tlsWriter.print("EHLO " + SystemKeywords.SMTP_NAME + "\r\n");
200 if ( !SendMail.readSMTPResponse(tlsReader, 250)) {
204 canSend = sh.trySendEmail(tlsReader, tlsWriter);
207 canSend = sh.trySendEmail(plainReader, plainWriter);
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);
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);
235 private static void sortMX(String[] mxhosts) {
236 Arrays.sort(mxhosts, new Comparator<String>() {
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);
247 public static boolean isValidMailAddress(String address) {
248 if ( !MAIL_ADDRESS.matcher(address).matches()) {
252 String[] parts = address.split("@", 2);
254 String local = parts[0];
255 String domain = parts[1];
257 if ( !MAIL_LOCAL.matcher(local).matches()) {
261 for (String domainPart : domain.split("\\.", -1)) {
262 if ( !DomainAssessment.isValidDomainPart(domainPart)) {