break out SqliteTable
[org.ibex.mail.git] / src / org / ibex / mail / Whitelist.java
1 package org.ibex.mail;
2
3 import org.ibex.io.*;
4 import org.ibex.net.*;
5 import org.ibex.mail.protocol.*;
6 import org.ibex.util.*;
7 import org.ibex.net.*;
8 import java.sql.*;
9 import java.net.*;
10 import java.io.*;
11 import java.util.*;
12 import java.sql.Timestamp;
13 import java.sql.Connection;
14
15 public class Whitelist extends SqliteDB {
16
17     public Whitelist(String filename) {
18         super(filename,
19               new String[] {
20                   "create table if not exists 'whitelist' (email)",
21                   "create table if not exists 'pending' (spamid,email,message,date)"
22               },
23               true);
24         getTable("pending").reap("date");
25     }
26
27     public boolean handleRequest(org.ibex.net.Connection c) {
28         try {
29             Socket sock = c.getSocket();
30             BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
31             String s = br.readLine();
32             String url = s.substring(s.indexOf(' ')+1);
33             url = url.substring(0, url.indexOf(' '));
34             while(s!=null && !s.equals(""))
35                 s = br.readLine();
36             PrintWriter pw = new PrintWriter(new OutputStreamWriter(sock.getOutputStream()));
37             if (!url.startsWith("/whitelist/")) {
38                 pw.print("HTTP/1.0 404 Not Found\r\n");
39                 pw.print("Content-Type: text/plain\r\n");
40                 pw.print("\r\n");
41                 pw.println("you are lost.");
42             } else {
43                 url = url.substring("/whitelist/".length());
44                 url = URLDecoder.decode(url);
45                 if (url.endsWith(".txt")) url = url.substring(0, url.length()-4);
46                 pw.print("HTTP/1.0 200 OK\r\n");
47                 pw.print("Content-Type: text/plain\r\n");
48                 pw.print("\r\n");
49                 try {
50                     SMTP.whitelist.response(url);
51                     pw.println("Thanks!  You've been added to my list of non-spammers and your message");
52                     pw.println("has been moved to my inbox.");
53                     pw.println("email id " + url);
54                     pw.println("");
55                 } catch (Exception e) {
56                     e.printStackTrace(pw);
57                 }
58             }
59             pw.flush();
60             sock.close();
61         } catch (Exception e) { throw new RuntimeException(e); }
62         return true;
63     }
64
65     public synchronized boolean isWhitelisted(Address a) {
66         try {
67             if (a==null) return false;
68             PreparedStatement check = conn.prepareStatement("select * from 'whitelist' where email=?");
69             check.setString(1, a.toString(false).toLowerCase());
70             ResultSet rs = check.executeQuery();
71             return !rs.isAfterLast();
72         } catch (SQLException e) { throw new RuntimeException(e); }
73     }
74
75     public synchronized void addWhitelist(Address a) {
76         try {
77             PreparedStatement add    = conn.prepareStatement("insert or replace into 'whitelist' values(?)");
78             add.setString(1, a.toString(false).toLowerCase());
79             add.executeUpdate();
80         } catch (SQLException e) { throw new RuntimeException(e); }
81     }
82
83     public synchronized void response(String messageid) throws IOException, MailException {
84         try {
85             PreparedStatement query = conn.prepareStatement("select email,message from pending where spamid=?");
86             query.setString(1, messageid);
87             ResultSet rs = query.executeQuery();
88             if (!rs.next())
89                 throw new RuntimeException("could not find messageid \""+messageid+"\"");
90             HashSet<Message> hsm = new HashSet<Message>();
91             synchronized(this) {
92                 do {
93                     addWhitelist(Address.parse(rs.getString(1)));
94                     Message m = Message.newMessage(new Fountain.StringFountain(rs.getString(2)));
95                     Address a = m.headers.get("reply-to")==null ? null : Address.parse(m.headers.get("reply-to"));
96                     if (a!=null) addWhitelist(a);
97                     a = m.from;
98                     if (a!=null) addWhitelist(a);
99                     a = m.envelopeFrom;
100                     if (a!=null) addWhitelist(a);
101                     hsm.add(m);
102                 } while (rs.next());
103             }
104             for(Message m : hsm)
105                 Target.root.accept(m);
106         } catch (SQLException e) { throw new RuntimeException(e); }
107     }
108
109     public void challenge(Message m) {
110         try {
111             // FIXME: don't challenge emails with binaries in them;
112             // reject them outright and have the sender send an
113             // initial message w/o a binary.
114
115             // FIXME: use Auto here!!!
116             // The challenge should refer to the message-id of the mail being challenged. 
117
118             // FIXME: watch outgoing MessageID's: if something comes
119             // back with an In-Reply-To mentioning a MessageID from
120             // the last few days, auto-whitelist them.
121
122             // FIXME: important that "From" on the challenge matches
123             // RCPT TO on the original message.
124
125             Log.warn(Whitelist.class, "challenging message: " + m.summary());
126
127             Address to = m.headers.get("reply-to")==null ? null : Address.parse(m.headers.get("reply-to"));
128             if (to==null) to = m.from;
129             if (to==null) to = m.envelopeFrom;
130
131             if (m.envelopeTo==null || m.envelopeTo.equals("null") || m.envelopeTo.equals("")) {
132                 Log.warn(this, "message is missing a to/replyto/envelopeto header; cannot accept");
133                 return;
134             }
135             if (m.headers.get("Auto-Submitted") != null &&
136                 m.headers.get("Auto-Submitted").toLowerCase().indexOf("auto-replied")!=-1) {
137                 Log.warn(this, "refusing to send a challenge to a message "+
138                          "with Auto-Submitted=\""+m.headers.get("Auto-Submitted")+"\"");
139                 return;
140             }
141
142             Address from = Address.parse("adam@megacz.com");
143
144             String messageid = "x" + m.messageid.substring(1);
145             messageid = messageid.substring(0, messageid.length() - 1);
146             messageid = messageid.replace('%','_');
147             Log.warn(Whitelist.class, "got challenge for: " + messageid);
148
149             String url = "http://www.megacz.com:8025/whitelist/"+URLEncoder.encode(messageid)+".txt";
150             String message =
151                 "Return-Path: <>"                                     + "\r\n" +
152                 "Envelope-To: "           + to                        + "\r\n" +
153                 "X-Originally-Received: " + m.headers.get("received") + "\r\n" +
154                 "To: "                    + to                        + "\r\n" +
155                 "From: "                  + from                      + "\r\n" +
156                 "Subject: Re: "           + m.subject                 + "\r\n" +
157                 "Message-ID:"             + Message.generateFreshMessageId() + "\r\n" +
158                 "\r\n" +
159                 "Hi, I've never sent a message to you before, so my spam filter trapped\n"        +
160                 "your email.  If you're really a human being and not an evil spammer,\n"          +
161                 "please click the link below or paste it into a web browser; doing so will\n"     +
162                 "add you to my list of non-spammers (so you won't get this email in the future)\n"+
163                 "and it will move your message from my spam folder to my incoming mail folder.\n" +
164                 "\n"                                                                              +
165                 "Thanks!\n"                                                                       +
166                 "\n"                                                                              +
167                 "  - Adam\n"                                                                      +
168                 "\n"                                                                              +
169                 url+"\n" +
170                 "\n"                                                                              +
171                 "\n"                                                                              +
172                 "About this message:\n" +
173                 "\n"                                                                              +
174                 "NOTE: SPAMCOP DOES NOT CONSIDER THIS TO BE SPAM; see this:\n"+
175                 "\n"+
176                 "         http://www.spamcop.net/fom-serve/cache/369.html\n"+
177                 "\n"+
178                 "      and examine the \"x-originally-received\" header on this message \n"+
179                 "      for the required \"chain of custody\" information.\n"+
180                 "\n"+
181                 "      Only one of these challenge messages is ever generated in response to \n"+
182                 "      a given inbound SMTP connection; it cannot be used to amplify spam    \n"+
183                 "      attacks, and in fact actually retards them while also stripping the   \n"+
184                 "      advertisement they were meant to convey.\n"+
185                 "\n"+
186                 "      Only one delivery attempt for this challenge is ever made, and it is made\n"+
187                 "      DURING the SMTP delivery of the message being challenged (that is, \n"+
188                 "      between C:DATA and S:250); the deliverer of the possibly-spam message\n"+
189                 "      must remain SMTP connected to my server during the entire process or else\n"+
190                 "      the delivery will immediately abort.  These challenge messages are NEVER,\n"+
191                 "      EVER queued for multiple delivery attempts\n"+
192                 "      \n"+
193                 "      For more information, please see:\n"+
194                 "      \n"+
195                 "      http://www.templetons.com/brad/spam/crgood.html\n";
196
197             Message challenge = Message.newMessage(new Fountain.StringFountain(message));
198
199             boolean send = false;
200             synchronized(this) {
201                 PreparedStatement query = conn.prepareStatement("select email from pending where email=?");
202                 query.setString(1, to.toString(false));
203                 ResultSet rs = query.executeQuery();
204                 if (rs.next()) {
205                     Log.warn(this, "already challenged " + to.toString(false) + "; not challenging again.");
206                 } else {
207                     send = true;
208                 }
209             }
210
211             if (send)
212                 if (!SMTP.Outgoing.attempt(challenge))
213                     throw new RuntimeException("attempted to send challenge but could not: " + m.summary());
214
215             synchronized(this) {
216                 PreparedStatement add = conn.prepareStatement("insert into pending values(?,?,?,?)");
217                 add.setString(1, messageid);
218                 add.setString(2, to.toString(false));
219                 add.setString(3, streamToString(m.getStream()));
220                 add.setTimestamp(4, new Timestamp(System.currentTimeMillis()));
221                 add.executeUpdate();
222             }
223         } catch (Exception e) { throw new RuntimeException(e); }
224     }
225
226     private static String streamToString(Stream stream) throws Exception {
227         StringBuffer b = new StringBuffer();
228         for(String s = stream.readln(); s!=null; s=stream.readln())
229             b.append(s+"\n");
230         return b.toString();
231     }
232 }
233