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