graylist/whitelist updates
[org.ibex.mail.git] / src / org / ibex / mail / Graylist.java
1 package org.ibex.mail;
2 // todo: periodically flush out old graylist entries
3
4 import java.sql.*;
5 import java.net.*;
6 import java.io.*;
7 import java.util.*;
8 import java.sql.Timestamp;
9
10 public class Graylist extends SqliteTable {
11
12     public Graylist(String filename) {
13         super(filename,
14               new String[] {
15                   "create table if not exists 'whitelist' (ip unique)",
16                   "create table if not exists 'graylist' (ip,fromaddr,toaddr,date, primary key(ip,fromaddr,toaddr))"
17               },
18               "graylist",
19               "date");
20     }
21
22     public synchronized void addWhitelist(InetAddress ip) {
23         try {
24             PreparedStatement add    = conn.prepareStatement("insert or replace into 'whitelist' values(?)");
25             add.setString(1, ip.getHostAddress());
26             add.executeUpdate();
27         } catch (SQLException e) { throw new RuntimeException(e); }
28     }
29
30     public synchronized boolean isWhitelisted(InetAddress ip) {
31         try {
32             PreparedStatement check = conn.prepareStatement("select * from 'whitelist' where ip=?");
33             check.setString(1, ip.getHostAddress());
34             ResultSet rs = check.executeQuery();
35             return !rs.isAfterLast();
36         } catch (SQLException e) { throw new RuntimeException(e); }
37     }
38
39     public synchronized long getGrayListTimestamp(InetAddress ip, String from, String to) {
40         try {
41             PreparedStatement check =
42                 conn.prepareStatement("select date from graylist where ip=? and fromaddr=? and toaddr=?");
43             check.setString(1, ip.getHostAddress());
44             check.setString(2, from);
45             check.setString(3, to);
46             ResultSet rs = check.executeQuery();
47             if (rs.isAfterLast()) return 0;
48             return rs.getTimestamp(1).getTime();
49         } catch (SQLException e) { throw new RuntimeException(e); }
50     }
51
52     public synchronized void setGrayListTimestamp(InetAddress ip, String from, String to, long date) {
53         try {
54             PreparedStatement check =
55                 conn.prepareStatement("insert or replace into graylist (ip,fromaddr,toaddr,date) values(?,?,?,?)");
56             check.setString(1, ip.getHostAddress());
57             check.setString(2, from);
58             check.setString(3, to);
59             check.setTimestamp(4, new Timestamp(date));
60             check.executeUpdate();
61         } catch (SQLException e) { throw new RuntimeException(e); }
62     }
63
64 }
65