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());
34 rs = check.executeQuery();
35 ret = !rs.isAfterLast();
36 } finally { close(rs); }
38 } catch (SQLException e) { throw new RuntimeException(e); }
41 public synchronized long getGrayListTimestamp(InetAddress ip, String from, String to) {
43 PreparedStatement check =
44 conn.prepareStatement("select date from graylist where ip=? and fromaddr=? and toaddr=?");
45 check.setString(1, graylistAddress(ip));
46 check.setString(2, from);
47 check.setString(3, to);
50 rs = check.executeQuery();
51 if (rs.isAfterLast()) return 0;
52 return rs.getTimestamp(1).getTime();
53 } finally { close(rs); }
54 } catch (SQLException e) { throw new RuntimeException(e); }
57 public synchronized void setGrayListTimestamp(InetAddress ip, String from, String to, long date) {
59 PreparedStatement check =
60 conn.prepareStatement("insert or replace into graylist (ip,fromaddr,toaddr,date) values(?,?,?,?)");
61 check.setString(1, graylistAddress(ip));
62 check.setString(2, from);
63 check.setString(3, to);
64 check.setTimestamp(4, new Timestamp(date));
65 check.executeUpdate();
66 } catch (SQLException e) { throw new RuntimeException(e); }
70 // this is mostly to deal with comcast's pathetic retry policy and
71 // rotating pool of outbound servers
72 // see: http://lists.puremagic.com/pipermail/greylist-users/2006-November/001255.html
74 private static String graylistAddress(InetAddress ipa) {
75 byte[] ip = ipa.getAddress();