1 package org.cacert.gigi.email;
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.io.InputStreamReader;
6 import java.io.PrintWriter;
7 import java.net.Socket;
8 import java.sql.PreparedStatement;
9 import java.sql.SQLException;
10 import java.util.LinkedList;
11 import java.util.regex.Pattern;
13 import org.cacert.gigi.database.DatabaseConnection;
15 public class EmailChecker {
16 public static final String OK = "OK";
17 public static final String FAIL = "FAIL";
18 private static final Pattern MAIL = Pattern
19 .compile("^([a-zA-Z0-9])+([a-zA-Z0-9\\+\\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\\._-]+)+$");
20 private EmailChecker() {
22 public static String checkEmailServer(int forUid, String address)
24 if (MAIL.matcher(address).matches()) {
25 String[] parts = address.split("@", 2);
26 String domain = parts[1];
28 LinkedList<String> mxhosts = getMxHosts(domain);
30 for (String host : mxhosts) {
31 try (Socket s = new Socket(host, 25);
32 BufferedReader br = new BufferedReader(
33 new InputStreamReader(s.getInputStream()));
34 PrintWriter pw = new PrintWriter(s.getOutputStream())) {
36 while ((line = br.readLine()) != null
37 && line.startsWith("220-")) {
39 if (line == null || !line.startsWith("220")) {
43 pw.print("HELO www.cacert.org\r\n");
46 while ((line = br.readLine()) != null
47 && line.startsWith("220")) {
50 if (line == null || !line.startsWith("250")) {
53 pw.print("MAIL FROM: <returns@cacert.org>\r\n");
58 if (line == null || !line.startsWith("250")) {
61 pw.print("RCPT TO: <" + address + ">\r\n");
69 PreparedStatement statmt = DatabaseConnection
72 "insert into `pinglog` set `when`=NOW(), `email`=?, `result`=?, `uid`=?");
73 statmt.setString(1, address);
74 statmt.setString(2, line);
75 statmt.setInt(3, forUid);
77 } catch (SQLException e) {
81 if (line == null || !line.startsWith("250")) {
91 PreparedStatement statmt = DatabaseConnection
94 "insert into `pinglog` set `when`=NOW(), `email`=?, `result`=?, `uid`=?");
95 statmt.setString(1, address);
97 "Failed to make a connection to the mail server");
98 statmt.setInt(3, forUid);
100 } catch (SQLException e) {
105 private static LinkedList<String> getMxHosts(String domain)
107 LinkedList<String> mxhosts = new LinkedList<String>();
108 Process dig = Runtime.getRuntime().exec(
109 new String[]{"dig", "+short", "MX", domain});
110 try (BufferedReader br = new BufferedReader(new InputStreamReader(
111 dig.getInputStream()))) {
113 while ((line = br.readLine()) != null) {
114 String[] mxparts = line.split(" ", 2);
115 if (mxparts.length != 2) {
118 mxhosts.add(mxparts[1].substring(0, mxparts[1].length() - 1));