2 // todo: periodically flush out old graylist entries
8 import java.sql.Timestamp;
10 public class Graylist extends SqliteDB {
12 public Graylist(String filename) throws SQLException {
14 SqliteTable whitelist = getTable("whitelist", "(ip unique)");
15 SqliteTable graylist = getTable("graylist", "(ip,fromaddr,toaddr,date,PRIMARY KEY(ip,fromaddr,toaddr))");
16 graylist.reap("date");
19 public synchronized void addWhitelist(InetAddress ip) {
21 PreparedStatement add = conn.prepareStatement("insert or replace into 'whitelist' values(?)");
22 add.setString(1, ip.getHostAddress());
24 } catch (SQLException e) { throw new RuntimeException(e); }
27 public synchronized boolean isWhitelisted(InetAddress ip) {
29 PreparedStatement check = conn.prepareStatement("select * from 'whitelist' where ip=?");
30 check.setString(1, ip.getHostAddress());
31 ResultSet rs = check.executeQuery();
32 return !rs.isAfterLast();
33 } catch (SQLException e) { throw new RuntimeException(e); }
36 public synchronized long getGrayListTimestamp(InetAddress ip, String from, String to) {
38 PreparedStatement check =
39 conn.prepareStatement("select date from graylist where ip=? and fromaddr=? and toaddr=?");
40 check.setString(1, graylistAddress(ip));
41 check.setString(2, from);
42 check.setString(3, to);
43 ResultSet rs = check.executeQuery();
44 if (rs.isAfterLast()) return 0;
45 return rs.getTimestamp(1).getTime();
46 } catch (SQLException e) { throw new RuntimeException(e); }
49 public synchronized void setGrayListTimestamp(InetAddress ip, String from, String to, long date) {
51 PreparedStatement check =
52 conn.prepareStatement("insert or replace into graylist (ip,fromaddr,toaddr,date) values(?,?,?,?)");
53 check.setString(1, graylistAddress(ip));
54 check.setString(2, from);
55 check.setString(3, to);
56 check.setTimestamp(4, new Timestamp(date));
57 check.executeUpdate();
58 } catch (SQLException e) { throw new RuntimeException(e); }
62 // this is mostly to deal with comcast's pathetic retry policy and
63 // rotating pool of outbound servers
64 // see: http://lists.puremagic.com/pipermail/greylist-users/2006-November/001255.html
66 private static String graylistAddress(InetAddress ipa) {
67 byte[] ip = ipa.getAddress();