added spam.el and spam-stat.el fixes
[gnus] / lisp / spam.el
1 ;;; spam.el --- Identifying spam
2 ;; Copyright (C) 2002 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;; Keywords: network
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;;; This module addresses a few aspects of spam control under Gnus.  Page
27 ;;; breaks are used for grouping declarations and documentation relating to
28 ;;; each particular aspect.
29
30 ;;; The integration with Gnus is not yet complete.  See various `FIXME'
31 ;;; comments, below, for supplementary explanations or discussions.
32
33 ;;; Code:
34
35 (require 'gnus-sum)
36
37 ;; FIXME!  We should not require `dns' nor `message' until we actually
38 ;; need them.  Best would be to declare needed functions as auto-loadable.
39 (require 'dns)
40 (require 'message)
41
42 (autoload 'bbdb-records "bbdb-com")
43
44 ;; Attempt to load BBDB macros
45 (eval-when-compile
46   (condition-case nil
47       (require 'bbdb-com)
48     (file-error (defalias 'bbdb-search 'ignore))))
49
50 ;; autoload executable-find
51 (autoload 'executable-find "executable")
52
53 ;;; Main parameters.
54
55 (defvar spam-use-blacklist t
56   "True if the blacklist should be used.")
57
58 (defvar spam-use-whitelist t
59   "True if the whitelist should be used.")
60
61 (defvar spam-use-blackholes nil
62   ;; FIXME!  Turned off for now.  The DNS routines are said to be flaky.
63   "True if blackholes should be used.")
64
65 (defvar spam-use-bogofilter t
66   "True if bogofilter should be used.")
67
68 (defvar spam-use-bbdb t
69   "True if BBDB should be used.")
70
71 (defvar spam-split-group "spam"
72   "Usual group name where spam should be split.")
73
74 (defvar spam-junk-mailgroups
75   ;; FIXME!  The mailgroup list evidently depends on other choices made by the
76   ;; user, so the built-in default below is not likely to be appropriate.
77   (cons spam-split-group '("mail.junk" "poste.pourriel"))
78   "Mailgroups which are dedicated by splitting to receive various junk.
79 All unmarked article in such group receive the spam mark on group entry.")
80
81 ;; FIXME!  For `spam-ham-marks' and `spam-spam-marks', I wonder if it would
82 ;; not be easier for the user to just accept a string of mark letters, instead
83 ;; of a list of Gnus variable names.  In such case, the stunt of deferred
84 ;; evaluation would not be useful anymore.  Lars?? :-)
85
86 ;; FIXME!  It is rather questionable to see `K', `X' and `Y' as indicating
87 ;; positive ham.  It much depends on how and why people use kill files, score
88 ;; files, and the kill command.  Maybe it would be better, by default, to not
89 ;; process a message neither as ham nor spam, that is, just ignore it for
90 ;; learning purposes, when we are not sure of how the user sees it.
91 ;; But `r' and `R' should undoubtedly be seen as ham.
92
93 ;; FIXME!  Some might consider overkill to define a list of spam marks.  On
94 ;; the other hand, who knows, some users might for example like that
95 ;; explicitly `E'xpired articles be processed as positive spam.
96
97 (defvar spam-ham-marks
98   (list gnus-del-mark gnus-read-mark gnus-killed-mark
99          gnus-kill-file-mark gnus-low-score-mark)
100   "Marks considered as being ham (positively not spam).
101 Such articles will be transmitted to `bogofilter -n' on group exit.")
102
103 (defvar spam-spam-marks
104   (list gnus-spam-mark)
105   "Marks considered as being spam (positively spam).
106 Such articles will be transmitted to `bogofilter -s' on group exit.")
107
108 ;; FIXME!  Ideally, the remainder of this page should be fully integrated
109 ;; within `gnus-sum.el'.
110
111 ;;; Key bindings for spam control.
112
113 ;; FIXME!  The justification for `M-d' is that this is what Paul Graham
114 ;; suggests in his original article, and what Eric Raymond's patch for Mutt
115 ;; uses.  But more importantly, that binding was still free in Summary mode!
116
117 ;; FIXME!  Lars has not blessed the following key bindings yet.  It looks
118 ;; convenient that the score analysis command uses a sequence ending with the
119 ;; letter `t', so it nicely parallels `B t' or `V t'.  `M-d' is a kind of
120 ;; "alternate" `d', it is also the sequence suggested in Paul Graham article,
121 ;; and also in Eric Raymond's patch for Mutt.  `S x' might be the more
122 ;; official key binding for `M-d'.
123
124 (gnus-define-keys gnus-summary-mode-map
125   "St" spam-bogofilter-score
126   "Sx" gnus-summary-mark-as-spam
127   "\M-d" gnus-summary-mark-as-spam)
128
129 ;;; How to highlight a spam summary line.
130
131 ;; FIXME!  Of course, `gnus-splash-face' has another purpose.  Maybe a
132 ;; special face should be created, named and used instead, for spam lines.
133
134 (push '((eq mark gnus-spam-mark) . gnus-splash-face)
135       gnus-summary-highlight)
136
137 ;;; Hooks dispatching.  A bit raw for now.
138
139 (defun spam-summary-prepare ()
140   (spam-mark-junk-as-spam-routine))
141
142 (defun spam-summary-prepare-exit ()
143   (spam-bogofilter-register-routine))
144
145 (add-hook 'gnus-summary-prepare-hook 'spam-summary-prepare)
146 (add-hook 'gnus-summary-prepare-exit-hook 'spam-summary-prepare-exit)
147
148 (defun spam-mark-junk-as-spam-routine ()
149   (when (member gnus-newsgroup-name spam-junk-mailgroups)
150     (let ((articles gnus-newsgroup-articles)
151           article)
152       (while articles
153         (setq article (pop articles))
154         (when (eq (gnus-summary-article-mark article) gnus-unread-mark)
155           (gnus-summary-mark-article article gnus-spam-mark))))))
156 \f
157 ;;;; Spam determination.
158
159
160 (defvar spam-list-of-checks
161   '((spam-use-blacklist  . spam-check-blacklist)
162     (spam-use-whitelist  . spam-check-whitelist)
163     (spam-use-bbdb       . spam-check-bbdb)
164     (spam-use-blackholes . spam-check-blackholes)
165     (spam-use-bogofilter . spam-check-bogofilter))
166 "The spam-list-of-checks list contains pairs associating a parameter
167 variable with a spam checking function.  If the parameter variable is
168 true, then the checking function is called, and its value decides what
169 happens.  Each individual check may return `nil', `t', or a mailgroup
170 name.  The value `nil' means that the check does not yield a decision,
171 and so, that further checks are needed.  The value `t' means that the
172 message is definitely not spam, and that further spam checks should be
173 inhibited.  Otherwise, a mailgroup name is returned where the mail
174 should go, and further checks are also inhibited.  The usual mailgroup
175 name is the value of `spam-split-group', meaning that the message is
176 definitely a spam.")
177
178 (defun spam-split ()
179   "Split this message into the `spam' group if it is spam.
180 This function can be used as an entry in `nnmail-split-fancy', for
181 example like this: (: spam-split)
182
183 See the Info node `(gnus)Fancy Mail Splitting' for more details."
184   (interactive)
185
186   (let ((list-of-checks spam-list-of-checks)
187         decision)
188     (while (and list-of-checks (not decision))
189       (let ((pair (pop list-of-checks)))
190         (when (eval (car pair))
191           (setq decision (apply (cdr pair))))))
192     (if (eq decision t)
193         nil
194       decision)))
195 \f
196 ;;;; Blackholes.
197
198 (defvar spam-blackhole-servers '("bl.spamcop.net"
199                                  "relays.ordb.org"
200                                  "dev.null.dk"
201                                  "relays.visi.com"
202                                  "rbl.maps.vix.com")
203   "List of blackhole servers.")
204
205 (defun spam-check-blackholes ()
206   "Check the Receieved headers for blackholed relays."
207   (let ((headers (message-fetch-field "received"))
208         ips matches)
209     (when headers
210       (with-temp-buffer
211         (insert headers)
212         (goto-char (point-min))
213         (while (re-search-forward
214                 "\\[\\([0-9]+.[0-9]+.[0-9]+.[0-9]+\\)\\]" nil t)
215           (message "Blackhole search found host IP %s." (match-string 1))
216           (push (mapconcat 'identity
217                            (nreverse (split-string (match-string 1) "\\."))
218                            ".")
219                 ips)))
220       (dolist (server spam-blackhole-servers)
221         (dolist (ip ips)
222           (when (query-dns (concat ip "." server))
223             (push (list ip server (query-dns (concat ip "." server) 'TXT))
224                   matches)))))
225     (when matches
226       spam-split-group)))
227 \f
228 ;;;; Blacklists and whitelists.
229
230 (defvar spam-directory "~/News/spam/"
231   "When spam files are kept.")
232
233 (defvar spam-whitelist (expand-file-name "whitelist" spam-directory)
234   "The location of the whitelist.
235 The file format is one regular expression per line.
236 The regular expression is matched against the address.")
237
238 (defvar spam-blacklist (expand-file-name "blacklist" spam-directory)
239   "The location of the blacklist.
240 The file format is one regular expression per line.
241 The regular expression is matched against the address.")
242
243 (defvar spam-whitelist-cache nil)
244 (defvar spam-blacklist-cache nil)
245
246 (defun spam-enter-whitelist (address)
247   "Enter ADDRESS into the whitelist."
248   (interactive "sAddress: ")
249   (spam-enter-list address spam-whitelist)
250   (setq spam-whitelist-cache nil))
251
252 (defun spam-enter-blacklist (address)
253   "Enter ADDRESS into the blacklist."
254   (interactive "sAddress: ")
255   (spam-enter-list address spam-blacklist)
256   (setq spam-blacklist-cache nil))
257
258 (defun spam-enter-list (address file)
259   "Enter ADDRESS into the given FILE, either the whitelist or the blacklist."
260   (unless (file-exists-p (file-name-directory file))
261     (make-directory (file-name-directory file) t))
262   (save-excursion
263     (set-buffer
264      (find-file-noselect file))
265     (goto-char (point-max))
266     (unless (bobp)
267       (insert "\n"))
268     (insert address "\n")
269     (save-buffer)))
270
271 ;;; returns nil if the sender is in the whitelist, spam-split-group otherwise
272 (defun spam-check-whitelist ()
273   ;; FIXME!  Should it detect when file timestamps change?
274   (unless spam-whitelist-cache
275     (setq spam-whitelist-cache (spam-parse-list spam-whitelist)))
276   (if (spam-from-listed-p spam-whitelist-cache) nil spam-split-group))
277
278 (condition-case nil
279     (progn
280       (require 'bbdb-com)
281         ;;; copied from code by Alexander Kotelnikov <sacha@giotto.sj.ru>
282       (defun spam-check-bbdb ()
283         "We want messages from people who are in the BBDB not to be split to spam"
284         (let ((who (message-fetch-field "from")))
285           (when who
286             (setq who (regexp-quote (cadr (gnus-extract-address-components who))))
287             (if (bbdb-search (bbdb-records) nil nil who) nil spam-split-group)))))
288   (file-error (setq spam-list-of-checks
289                     (delete (assoc 'spam-use-bbdb spam-list-of-checks)
290                             spam-list-of-checks))))
291
292 (defun spam-check-blacklist ()
293   ;; FIXME!  Should it detect when file timestamps change?
294   (unless spam-blacklist-cache
295     (setq spam-blacklist-cache (spam-parse-list spam-blacklist)))
296   (and (spam-from-listed-p spam-blacklist-cache) spam-split-group))
297
298 (eval-and-compile
299   (defalias 'spam-point-at-eol (if (fboundp 'point-at-eol)
300                                    'point-at-eol
301                                  'line-end-position)))
302
303 (defun spam-parse-list (file)
304   (when (file-readable-p file)
305     (let (contents address)
306       (with-temp-buffer
307         (insert-file-contents file)
308         (while (not (eobp))
309           (setq address (buffer-substring (point) (spam-point-at-eol)))
310           (forward-line 1)
311           (unless (zerop (length address))
312             (setq address (regexp-quote address))
313             (while (string-match "\\\\\\*" address)
314               (setq address (replace-match ".*" t t address)))
315             (push address contents))))
316       (nreverse contents))))
317
318 (defun spam-from-listed-p (cache)
319   (let ((from (message-fetch-field "from"))
320         found)
321     (while cache
322       (when (string-match (pop cache) from)
323         (setq found t
324               cache nil)))
325     found))
326 \f
327 ;;;; Training via Bogofilter.   Last updated 2002-09-02.
328
329 ;;; See Paul Graham article, at `http://www.paulgraham.com/spam.html'.
330
331 ;;; This page is for those wanting to control spam with the help of Eric
332 ;;; Raymond's speedy Bogofilter, see http://www.tuxedo.org/~esr/bogofilter.
333 ;;; This has been tested with a locally patched copy of version 0.4.
334
335 ;;; Make sure Bogofilter is installed.  Bogofilter internally uses Judy fast
336 ;;; associative arrays, so you need to install Judy first, and Bogofilter
337 ;;; next.  Fetch both distributions by visiting the following links and
338 ;;; downloading the latest version of each:
339 ;;;
340 ;;;     http://sourceforge.net/projects/judy/
341 ;;;     http://www.tuxedo.org/~esr/bogofilter/
342 ;;;
343 ;;; Unpack the Judy distribution and enter its main directory.  Then do:
344 ;;;
345 ;;;     ./configure
346 ;;;     make
347 ;;;     make install
348 ;;;
349 ;;; You will likely need to become super-user for the last step.  Then, unpack
350 ;;; the Bogofilter distribution and enter its main directory:
351 ;;;
352 ;;;     make
353 ;;;     make install
354 ;;;
355 ;;; Here as well, you need to become super-user for the last step.  Now,
356 ;;; initialises your word lists by doing, under your own identity:
357 ;;;
358 ;;;     mkdir ~/.bogofilter
359 ;;;     touch ~/.bogofilter/badlist
360 ;;;     touch ~/.bogofilter/goodlist
361 ;;;
362 ;;; These two files are text files you may edit, but you normally don't!
363
364 ;;; The `M-d' command gets added to Gnus summary mode, marking current article
365 ;;; as spam, showing it with the `H' mark.  Whenever you see a spam article,
366 ;;; make sure to mark its summary line with `M-d' before leaving the group.
367 ;;; Some groups, as per variable `spam-junk-mailgroups' below, receive articles
368 ;;; from Gnus splitting on clues added by spam recognisers, so for these
369 ;;; groups, we tack an `H' mark at group entry for all summary lines which
370 ;;; would otherwise have no other mark.  Make sure to _remove_ `H' marks for
371 ;;; any article which is _not_ genuine spam, before leaving such groups: you
372 ;;; may use `M-u' to "unread" the article, or `d' for declaring it read the
373 ;;; non-spam way.  When you leave a group, all `H' marked articles, saved or
374 ;;; unsaved, are sent to Bogofilter which will study them as spam samples.
375
376 ;;; Messages may also be deleted in various other ways, and unless
377 ;;; `spam-ham-marks-form' gets overridden below, marks `R' and `r' for default
378 ;;; read or explicit delete, marks `X' and 'K' for automatic or explicit
379 ;;; kills, as well as mark `Y' for low scores, are all considered to be
380 ;;; associated with articles which are not spam.  This assumption might be
381 ;;; false, in particular if you use kill files or score files as means for
382 ;;; detecting genuine spam, you should then adjust `spam-ham-marks-form'.  When
383 ;;; you leave a group, all _unsaved_ articles bearing any the above marks are
384 ;;; sent to Bogofilter which will study these as not-spam samples.  If you
385 ;;; explicit kill a lot, you might sometimes end up with articles marked `K'
386 ;;; which you never saw, and which might accidentally contain spam.  Best is
387 ;;; to make sure that real spam is marked with `H', and nothing else.
388
389 ;;; All other marks do not contribute to Bogofilter pre-conditioning.  In
390 ;;; particular, ticked, dormant or souped articles are likely to contribute
391 ;;; later, when they will get deleted for real, so there is no need to use
392 ;;; them prematurely.  Explicitly expired articles do not contribute, command
393 ;;; `E' is a way to get rid of an article without Bogofilter ever seeing it.
394
395 ;;; In a word, with a minimum of care for associating the `H' mark for spam
396 ;;; articles only, Bogofilter training all gets fairly automatic.  You should
397 ;;; do this until you get a few hundreds of articles in each category, spam
398 ;;; or not.  The shell command `head -1 ~/.bogofilter/*' shows both article
399 ;;; counts.  The command `S S' in summary mode, either for debugging or for
400 ;;; curiosity, triggers Bogofilter into displaying in another buffer the
401 ;;; "spamicity" score of the current article (between 0.0 and 1.0), together
402 ;;; with the article words which most significantly contribute to the score.
403
404 ;;; The real way for using Bogofilter, however, is to have some use tool like
405 ;;; `procmail' for invoking it on message reception, then adding some
406 ;;; recognisable header in case of detected spam.  Gnus splitting rules might
407 ;;; later trip on these added headers and react by sorting such articles into
408 ;;; specific junk folders as per `spam-junk-mailgroups'.  Here is a possible
409 ;;; `.procmailrc' contents (still untested -- please tell me how it goes):
410 ;;;
411 ;;; :0HBf:
412 ;;; * ? bogofilter
413 ;;; | formail -bfI "X-Spam-Status: Yes"
414
415 (defvar spam-output-buffer-name "*Bogofilter Output*"
416   "Name of buffer when displaying `bogofilter -v' output.")
417
418 (defvar spam-spaminfo-header-regexp
419   ;; FIXME!  In the following regexp, we should explain which tool produces
420   ;; which kind of header.  I do not even remember them all by now.  X-Junk
421   ;; (and previously X-NoSpam) are produced by the `NoSpam' tool, which has
422   ;; never been published, so it might not be reasonable leaving it in the
423   ;; list.
424   "^X-\\(jf\\|Junk\\|NoSpam\\|Spam\\|SB\\)[^:]*:"
425   "Regexp for spam markups in headers.
426 Markup from spam recognisers, as well as `Xref', are to be removed from
427 articles before they get registered by Bogofilter.")
428
429 (defvar spam-bogofilter-path (executable-find "bogofilter")
430   "File path of the Bogofilter executable program.
431 Force this variable to nil if you want to inhibit the functionality.")
432
433 (defun spam-check-bogofilter ()
434   ;; Dynamic spam check.  I do not know how to check the exit status,
435   ;; so instead, read `bogofilter -v' output.
436   (when (and spam-use-bogofilter spam-bogofilter-path)
437     (spam-bogofilter-articles nil "-v" (list (gnus-summary-article-number)))
438     (when (save-excursion
439             (set-buffer spam-output-buffer-name)
440             (goto-char (point-min))
441             (re-search-forward "Spamicity: \\(0\\.9\\|1\\.0\\)" nil t))
442       spam-split-group)))
443
444 (defun spam-bogofilter-score ()
445   "Use `bogofilter -v' on the current article.
446 This yields the 15 most discriminant words for this article and the
447 spamicity coefficient of each, and the overall article spamicity."
448   (interactive)
449   (when (and spam-use-bogofilter spam-bogofilter-path)
450     (spam-bogofilter-articles nil "-v" (list (gnus-summary-article-number)))
451     (save-excursion
452       (set-buffer spam-output-buffer-name)
453       (unless (= (point-min) (point-max))
454         (display-message-or-buffer (current-buffer)
455                                    spam-output-buffer-name)))))
456
457 (defun spam-bogofilter-register-routine ()
458   (when (and spam-use-bogofilter spam-bogofilter-path)
459     (let ((articles gnus-newsgroup-articles)
460           article mark ham-articles spam-articles)
461       (while articles
462         (setq article (pop articles)
463               mark (gnus-summary-article-mark article))
464         (cond ((memq mark spam-spam-marks) (push article spam-articles))
465               ((memq article gnus-newsgroup-saved))
466               ((memq mark spam-ham-marks) (push article ham-articles))))
467       (when ham-articles
468         (spam-bogofilter-articles "ham" "-n" ham-articles))
469       (when spam-articles
470         (spam-bogofilter-articles "SPAM" "-s" spam-articles)))))
471
472 (defvar spam-bogofilter-initial-timeout 40
473   "Timeout in seconds for the initial reply from the `bogofilter' program.")
474
475 (defvar spam-bogofilter-subsequent-timeout 15
476   "Timeout in seconds for any subsequent reply from the `bogofilter' program.")
477
478 (defun spam-bogofilter-articles (type option articles)
479   (let ((output-buffer (get-buffer-create spam-output-buffer-name))
480         (article-copy (get-buffer-create " *Bogofilter Article Copy*"))
481         (remove-regexp (concat spam-spaminfo-header-regexp "\\|Xref:"))
482         (counter 0)
483         prefix process article)
484     (when type
485       (setq prefix (format "Studying %d articles as %s..." (length articles)
486                            type))
487       (message "%s" prefix))
488     (save-excursion (set-buffer output-buffer) (erase-buffer))
489     (setq process (start-process "bogofilter" output-buffer
490                                  spam-bogofilter-path "-F" option))
491     (process-kill-without-query process t)
492     (unwind-protect
493         (save-window-excursion
494           (while articles
495             (setq counter (1+ counter))
496             (when prefix
497               (message "%s %d" prefix counter))
498             (setq article (pop articles))
499             (gnus-summary-goto-subject article)
500             (gnus-summary-select-article)
501             (gnus-eval-in-buffer-window article-copy
502               (insert-buffer-substring gnus-original-article-buffer)
503               ;; Remove spam classification redundant headers: they may induce
504               ;; unwanted biases in later analysis.
505               (goto-char (point-min))
506               (while (not (or (eobp) (= (following-char) ?\n)))
507                 (if (looking-at remove-regexp)
508                     (delete-region (point)
509                                    (save-excursion (forward-line 1) (point)))
510                   (forward-line 1)))
511               (goto-char (point-min))
512               ;; Bogofilter really wants From envelopes for counting articles.
513               ;; Fake one at the beginning, make sure there will be no other.
514               (if (looking-at "From ")
515                   (forward-line 1)
516                 (insert "From nobody " (current-time-string) "\n"))
517               (let (case-fold-search)
518                 (while (re-search-forward "^From " nil t)
519                   (beginning-of-line)
520                   (insert ">")))
521               (process-send-region process (point-min) (point-max))
522               (erase-buffer))))
523       ;; Sending the EOF is unwind-protected.  This is to prevent lost copies
524       ;; of `bogofilter', hung on reading their standard input, in case the
525       ;; whole registering process gets interrupted by the user.
526       (process-send-eof process))
527     (kill-buffer article-copy)
528     ;; Receive process output.  It sadly seems that we still have to protect
529     ;; ourselves against hung `bogofilter' processes.
530     (let ((status (process-status process))
531           (timeout (* 1000 spam-bogofilter-initial-timeout))
532           (quanta 200))                 ; also counted in milliseconds
533       (while (and (not (eq status 'exit)) (> timeout 0))
534         ;; `accept-process-output' timeout is counted in microseconds.
535         (setq timeout (if (accept-process-output process 0 (* 1000 quanta))
536                           (* 1000 spam-bogofilter-subsequent-timeout)
537                         (- timeout quanta))
538               status (process-status process)))
539       (if (eq status 'exit)
540           (when prefix
541             (message "%s done!" prefix))
542         ;; Sigh!  The process did time out...  Become brutal!
543         (interrupt-process process)
544         (message "%s %d INTERRUPTED!  (Article %d, status %s)"
545                  (or prefix "Bogofilter process...")
546                  counter article status)
547         ;; Give some time for user to read.  Sitting redisplays but gives up
548         ;; if input is pending.  Sleeping does not give up, but it does not
549         ;; redisplay either.  Mix both: let's redisplay and not give up.
550         (sit-for 1)
551         (sleep-for 3)))))
552
553 (provide 'spam)
554
555 ;;; spam.el ends here.