Whitelist cleanup
[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 SqliteTable {
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               "pending",
25               "date");
26     }
27
28     public synchronized boolean handleRequest(org.ibex.net.Connection c) {
29         try {
30             Socket sock = c.getSocket();
31             BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
32             String s = br.readLine();
33             String url = s.substring(s.indexOf(' ')+1);
34             url = url.substring(0, url.indexOf(' '));
35             while(s!=null && !s.equals(""))
36                 s = br.readLine();
37             PrintWriter pw = new PrintWriter(new OutputStreamWriter(sock.getOutputStream()));
38             if (!url.startsWith("/whitelist/")) {
39                 pw.print("HTTP/1.0 404 Not Found\r\n");
40                 pw.print("Content-Type: text/plain\r\n");
41                 pw.print("\r\n");
42                 pw.println("you are lost.");
43             } else {
44                 url = url.substring("/whitelist/".length());
45                 url = URLDecoder.decode(url);
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             do {
91                 addWhitelist(Address.parse(rs.getString(1)));
92                 Message m = Message.newMessage(new Fountain.StringFountain(rs.getString(2)));
93                 Target.root.accept(m);
94             } while (rs.next());
95         } catch (SQLException e) { throw new RuntimeException(e); }
96     }
97
98     public synchronized void challenge(Message m) {
99         try {
100             Log.warn(Whitelist.class, "challenging message: " + m.summary());
101
102             Address to = m.headers.get("reply-to")==null ? null : Address.parse(m.headers.get("reply-to"));
103             if (to==null) to = m.from;
104             if (to==null) to = m.envelopeFrom;
105
106             if (m.envelopeTo==null || m.envelopeTo.equals("null") || m.envelopeTo.equals("")) {
107                 Log.warn(this, "message is missing a to/replyto/envelopeto header; cannot accept");
108                 return;
109             }
110             if (m.headers.get("Auto-Submitted") != null &&
111                 m.headers.get("Auto-Submitted").toLowerCase().indexOf("auto-replied")!=-1) {
112                 Log.warn(this, "refusing to send a challenge to a message "+
113                          "with Auto-Submitted=\""+m.headers.get("Auto-Submitted")+"\"");
114                 return;
115             }
116
117             Address from = Address.parse("adam@megacz.com");
118
119             String messageid = "x" + m.messageid.substring(1);
120             messageid = messageid.substring(0, messageid.length() - 1);
121             messageid = messageid.replace('%','_');
122             Log.warn(Whitelist.class, "got challenge for: " + messageid);
123
124             String url = "http://www.megacz.com:8025/whitelist/"+URLEncoder.encode(messageid);
125             String message =
126                 "Return-Path: <>"                                     + "\r\n" +
127                 "Envelope-To: "           + to                        + "\r\n" +
128                 "X-Originally-Received: " + m.headers.get("received") + "\r\n" +
129                 "To: "                    + to                        + "\r\n" +
130                 "From: "                  + from                      + "\r\n" +
131                 "Subject: Re: "           + m.subject                 + "\r\n" +
132                 "Message-ID:"             + Message.generateFreshMessageId() + "\r\n" +
133                 "\r\n" +
134                 "Hi, I've never sent a message to you before, so my spam filter trapped\n"        +
135                 "your email.  If you're really a human being and not an evil spammer,\n"          +
136                 "please click the link below or paste it into a web browser; doing so will\n"     +
137                 "add you to my list of non-spammers (so you won't get this email in the future)\n"+
138                 "and it will move your message from my spam folder to my incoming mail folder.\n" +
139                 "\n"                                                                              +
140                 "Thanks!\n"                                                                       +
141                 "\n"                                                                              +
142                 "  - Adam\n"                                                                      +
143                 "\n"                                                                              +
144                 url+"\n" +
145                 "\n"                                                                              +
146                 "\n"                                                                              +
147                 "About this message:\n" +
148                 "\n"                                                                              +
149                 "NOTE: SPAMCOP DOES NOT CONSIDER THIS TO BE SPAM; see this:\n"+
150                 "\n"+
151                 "         http://www.spamcop.net/fom-serve/cache/369.html\n"+
152                 "\n"+
153                 "      and examine the \"x-originally-received\" header on this message \n"+
154                 "      for the required \"chain of custody\" information.\n"+
155                 "\n"+
156                 "      Only one of these challenge messages is ever generated in response to \n"+
157                 "      a given inbound SMTP connection; it cannot be used to amplify spam    \n"+
158                 "      attacks, and in fact actually retards them while also stripping the   \n"+
159                 "      advertisement they were meant to convey.\n"+
160                 "\n"+
161                 "      Only one delivery attempt for this challenge is ever made, and it is made\n"+
162                 "      DURING the SMTP delivery of the message being challenged (that is, \n"+
163                 "      between C:DATA and S:250); the deliverer of the possibly-spam message\n"+
164                 "      must remain SMTP connected to my server during the entire process or else\n"+
165                 "      the delivery will immediately abort.  These challenge messages are NEVER,\n"+
166                 "      EVER queued for multiple delivery attempts\n"+
167                 "      \n"+
168                 "      For more information, please see:\n"+
169                 "      \n"+
170                 "      http://www.templetons.com/brad/spam/crgood.html\n";
171
172             Message challenge = Message.newMessage(new Fountain.StringFountain(message));
173
174             PreparedStatement query = conn.prepareStatement("select email from pending where email=?");
175             query.setString(1, to.toString(false));
176             ResultSet rs = query.executeQuery();
177             if (rs.next()) {
178                 Log.warn(this, "already challenged " + to.toString(false) + "; not challenging again.");
179             } else {
180                 if (!SMTP.Outgoing.attempt(challenge))
181                     throw new RuntimeException("attempted to send challenge but could not: " + m.summary());
182             }
183
184             PreparedStatement add = conn.prepareStatement("insert into pending values(?,?,?,?)");
185             add.setString(1, messageid);
186             add.setString(2, to.toString(false));
187             add.setString(3, streamToString(m.getStream()));
188             add.setTimestamp(4, new Timestamp(System.currentTimeMillis()));
189             add.executeUpdate();
190         } catch (Exception e) { throw new RuntimeException(e); }
191     }
192
193     private static String streamToString(Stream stream) throws Exception {
194         StringBuffer b = new StringBuffer();
195         for(String s = stream.readln(); s!=null; s=stream.readln())
196             b.append(s+"\n");
197         return b.toString();
198     }
199 }
200