1 ;;; spam.el --- Identifying spam
2 ;; Copyright (C) 2002 Free Software Foundation, Inc.
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
7 ;; This file is part of GNU Emacs.
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)
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.
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.
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.
30 ;;; The integration with Gnus is not yet complete. See various `FIXME'
31 ;;; comments, below, for supplementary explanations or discussions.
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.
42 ;; Attempt to load BBDB macros
46 (file-error (defalias 'bbdb-search 'ignore))))
48 ;; autoload executable-find
50 ;; executable-find is not autoloaded in Emacs 20
51 (autoload 'executable-find "executable"))
53 ;; autoload ifile-spam-filter
55 (autoload 'ifile-spam-filter "ifile-gnus"))
59 (defvar spam-use-blacklist t
60 "True if the blacklist should be used.")
62 (defvar spam-use-whitelist nil
63 "True if the whitelist should be used.")
65 (defvar spam-use-blackholes nil
66 ;; FIXME! Turned off for now. The DNS routines are said to be flaky.
67 "True if blackholes should be used.")
69 (defvar spam-use-bogofilter nil
70 "True if bogofilter should be used.")
72 (defvar spam-use-bbdb nil
73 "True if BBDB should be used.")
75 (defvar spam-use-ifile nil
76 "True if ifile should be used.")
78 (defvar spam-split-group "spam"
79 "Usual group name where spam should be split.")
81 (defvar spam-junk-mailgroups
82 ;; FIXME! The mailgroup list evidently depends on other choices made by the
83 ;; user, so the built-in default below is not likely to be appropriate.
84 (cons spam-split-group '("mail.junk" "poste.pourriel"))
85 "Mailgroups which are dedicated by splitting to receive various junk.
86 All unmarked article in such group receive the spam mark on group entry.")
88 ;; FIXME! For `spam-ham-marks' and `spam-spam-marks', I wonder if it would
89 ;; not be easier for the user to just accept a string of mark letters, instead
90 ;; of a list of Gnus variable names. In such case, the stunt of deferred
91 ;; evaluation would not be useful anymore. Lars?? :-)
93 ;; FIXME! It is rather questionable to see `K', `X' and `Y' as indicating
94 ;; positive ham. It much depends on how and why people use kill files, score
95 ;; files, and the kill command. Maybe it would be better, by default, to not
96 ;; process a message neither as ham nor spam, that is, just ignore it for
97 ;; learning purposes, when we are not sure of how the user sees it.
98 ;; But `r' and `R' should undoubtedly be seen as ham.
100 ;; FIXME! Some might consider overkill to define a list of spam marks. On
101 ;; the other hand, who knows, some users might for example like that
102 ;; explicitly `E'xpired articles be processed as positive spam.
104 (defvar spam-ham-marks
105 (list gnus-del-mark gnus-read-mark gnus-killed-mark
106 gnus-kill-file-mark gnus-low-score-mark)
107 "Marks considered as being ham (positively not spam).
108 Such articles will be transmitted to `bogofilter -n' on group exit.")
110 (defvar spam-spam-marks
111 (list gnus-spam-mark)
112 "Marks considered as being spam (positively spam).
113 Such articles will be transmitted to `bogofilter -s' on group exit.")
115 ;; FIXME! Ideally, the remainder of this page should be fully integrated
116 ;; within `gnus-sum.el'.
118 ;;; Key bindings for spam control.
120 ;; FIXME! The justification for `M-d' is that this is what Paul Graham
121 ;; suggests in his original article, and what Eric Raymond's patch for Mutt
122 ;; uses. But more importantly, that binding was still free in Summary mode!
124 ;; FIXME! Lars has not blessed the following key bindings yet. It looks
125 ;; convenient that the score analysis command uses a sequence ending with the
126 ;; letter `t', so it nicely parallels `B t' or `V t'. `M-d' is a kind of
127 ;; "alternate" `d', it is also the sequence suggested in Paul Graham article,
128 ;; and also in Eric Raymond's patch for Mutt. `S x' might be the more
129 ;; official key binding for `M-d'.
131 (gnus-define-keys gnus-summary-mode-map
132 "St" spam-bogofilter-score
133 "Sx" gnus-summary-mark-as-spam
134 "Mst" spam-bogofilter-score
135 "Msx" gnus-summary-mark-as-spam
136 "\M-d" gnus-summary-mark-as-spam)
138 ;;; How to highlight a spam summary line.
140 ;; FIXME! Of course, `gnus-splash-face' has another purpose. Maybe a
141 ;; special face should be created, named and used instead, for spam lines.
143 (push '((eq mark gnus-spam-mark) . gnus-splash-face)
144 gnus-summary-highlight)
146 ;;; Hooks dispatching. A bit raw for now.
148 (defun spam-summary-prepare ()
149 (spam-mark-junk-as-spam-routine))
151 (defun spam-summary-prepare-exit ()
152 (spam-bogofilter-register-routine))
154 (add-hook 'gnus-summary-prepare-hook 'spam-summary-prepare)
155 (add-hook 'gnus-summary-prepare-exit-hook 'spam-summary-prepare-exit)
157 (defun spam-mark-junk-as-spam-routine ()
158 (when (member gnus-newsgroup-name spam-junk-mailgroups)
159 (let ((articles gnus-newsgroup-articles)
162 (setq article (pop articles))
163 (when (eq (gnus-summary-article-mark article) gnus-unread-mark)
164 (gnus-summary-mark-article article gnus-spam-mark))))))
166 ;;;; Spam determination.
169 (defvar spam-list-of-checks
170 '((spam-use-blacklist . spam-check-blacklist)
171 (spam-use-whitelist . spam-check-whitelist)
172 (spam-use-bbdb . spam-check-bbdb)
173 (spam-use-ifile . spam-check-ifile)
174 (spam-use-blackholes . spam-check-blackholes)
175 (spam-use-bogofilter . spam-check-bogofilter))
176 "The spam-list-of-checks list contains pairs associating a parameter
177 variable with a spam checking function. If the parameter variable is
178 true, then the checking function is called, and its value decides what
179 happens. Each individual check may return `nil', `t', or a mailgroup
180 name. The value `nil' means that the check does not yield a decision,
181 and so, that further checks are needed. The value `t' means that the
182 message is definitely not spam, and that further spam checks should be
183 inhibited. Otherwise, a mailgroup name is returned where the mail
184 should go, and further checks are also inhibited. The usual mailgroup
185 name is the value of `spam-split-group', meaning that the message is
189 "Split this message into the `spam' group if it is spam.
190 This function can be used as an entry in `nnmail-split-fancy', for
191 example like this: (: spam-split)
193 See the Info node `(gnus)Fancy Mail Splitting' for more details."
196 (let ((list-of-checks spam-list-of-checks)
198 (while (and list-of-checks (not decision))
199 (let ((pair (pop list-of-checks)))
200 (when (symbol-value (car pair))
201 (setq decision (funcall (cdr pair))))))
208 (defvar spam-blackhole-servers '("bl.spamcop.net"
213 "List of blackhole servers.")
215 (defun spam-check-blackholes ()
216 "Check the Receieved headers for blackholed relays."
217 (let ((headers (message-fetch-field "received"))
222 (goto-char (point-min))
223 (while (re-search-forward
224 "\\[\\([0-9]+.[0-9]+.[0-9]+.[0-9]+\\)\\]" nil t)
225 (message "Blackhole search found host IP %s." (match-string 1))
226 (push (mapconcat 'identity
227 (nreverse (split-string (match-string 1) "\\."))
230 (dolist (server spam-blackhole-servers)
232 (when (query-dns (concat ip "." server))
233 (push (list ip server (query-dns (concat ip "." server) 'TXT))
238 ;;;; Blacklists and whitelists.
240 (defvar spam-directory "~/News/spam/"
241 "When spam files are kept.")
243 (defvar spam-whitelist (expand-file-name "whitelist" spam-directory)
244 "The location of the whitelist.
245 The file format is one regular expression per line.
246 The regular expression is matched against the address.")
248 (defvar spam-blacklist (expand-file-name "blacklist" spam-directory)
249 "The location of the blacklist.
250 The file format is one regular expression per line.
251 The regular expression is matched against the address.")
253 (defvar spam-whitelist-cache nil)
254 (defvar spam-blacklist-cache nil)
256 (defun spam-enter-whitelist (address)
257 "Enter ADDRESS into the whitelist."
258 (interactive "sAddress: ")
259 (spam-enter-list address spam-whitelist)
260 (setq spam-whitelist-cache nil))
262 (defun spam-enter-blacklist (address)
263 "Enter ADDRESS into the blacklist."
264 (interactive "sAddress: ")
265 (spam-enter-list address spam-blacklist)
266 (setq spam-blacklist-cache nil))
268 (defun spam-enter-list (address file)
269 "Enter ADDRESS into the given FILE, either the whitelist or the blacklist."
270 (unless (file-exists-p (file-name-directory file))
271 (make-directory (file-name-directory file) t))
274 (find-file-noselect file))
275 (goto-char (point-max))
278 (insert address "\n")
281 ;;; returns nil if the sender is in the whitelist, spam-split-group otherwise
282 (defun spam-check-whitelist ()
283 ;; FIXME! Should it detect when file timestamps change?
284 (unless spam-whitelist-cache
285 (setq spam-whitelist-cache (spam-parse-list spam-whitelist)))
286 (if (spam-from-listed-p spam-whitelist-cache) nil spam-split-group))
288 ;;; original idea from Alexander Kotelnikov <sacha@giotto.sj.ru>
292 (defun spam-check-bbdb ()
293 "We want messages from people who are in the BBDB not to be split to spam"
294 (let ((who (message-fetch-field "from")))
296 (setq who (regexp-quote (cadr (gnus-extract-address-components who))))
297 (if (bbdb-search (bbdb-records) nil nil who) nil spam-split-group)))))
298 (file-error (setq spam-list-of-checks
299 (delete (assoc 'spam-use-bbdb spam-list-of-checks)
300 spam-list-of-checks))))
302 ;;; check the ifile backend; return nil if the mail was NOT classified as spam
305 (require 'ifile-gnus)
307 (defun spam-check-ifile ()
308 (let ((ifile-primary-spam-group spam-split-group))
309 (ifile-spam-filter nil))))
310 (file-error (setq spam-list-of-checks
311 (delete (assoc 'spam-use-ifile spam-list-of-checks)
312 spam-list-of-checks))))
314 (defun spam-check-blacklist ()
315 ;; FIXME! Should it detect when file timestamps change?
316 (unless spam-blacklist-cache
317 (setq spam-blacklist-cache (spam-parse-list spam-blacklist)))
318 (and (spam-from-listed-p spam-blacklist-cache) spam-split-group))
321 (defalias 'spam-point-at-eol (if (fboundp 'point-at-eol)
323 'line-end-position)))
325 (defun spam-parse-list (file)
326 (when (file-readable-p file)
327 (let (contents address)
329 (insert-file-contents file)
331 (setq address (buffer-substring (point) (spam-point-at-eol)))
333 (unless (zerop (length address))
334 (setq address (regexp-quote address))
335 (while (string-match "\\\\\\*" address)
336 (setq address (replace-match ".*" t t address)))
337 (push address contents))))
338 (nreverse contents))))
340 (defun spam-from-listed-p (cache)
341 (let ((from (message-fetch-field "from"))
344 (when (string-match (pop cache) from)
350 ;;;; Training via Bogofilter. Last updated 2002-09-02.
352 ;;; See Paul Graham article, at `http://www.paulgraham.com/spam.html'.
354 ;;; This page is for those wanting to control spam with the help of Eric
355 ;;; Raymond's speedy Bogofilter, see http://www.tuxedo.org/~esr/bogofilter.
356 ;;; This has been tested with a locally patched copy of version 0.4.
358 ;;; Make sure Bogofilter is installed. Bogofilter internally uses Judy fast
359 ;;; associative arrays, so you need to install Judy first, and Bogofilter
360 ;;; next. Fetch both distributions by visiting the following links and
361 ;;; downloading the latest version of each:
363 ;;; http://sourceforge.net/projects/judy/
364 ;;; http://www.tuxedo.org/~esr/bogofilter/
366 ;;; Unpack the Judy distribution and enter its main directory. Then do:
372 ;;; You will likely need to become super-user for the last step. Then, unpack
373 ;;; the Bogofilter distribution and enter its main directory:
378 ;;; Here as well, you need to become super-user for the last step. Now,
379 ;;; initialize your word lists by doing, under your own identity:
381 ;;; mkdir ~/.bogofilter
382 ;;; touch ~/.bogofilter/badlist
383 ;;; touch ~/.bogofilter/goodlist
385 ;;; These two files are text files you may edit, but you normally don't!
387 ;;; The `M-d' command gets added to Gnus summary mode, marking current article
388 ;;; as spam, showing it with the `H' mark. Whenever you see a spam article,
389 ;;; make sure to mark its summary line with `M-d' before leaving the group.
390 ;;; Some groups, as per variable `spam-junk-mailgroups' below, receive articles
391 ;;; from Gnus splitting on clues added by spam recognisers, so for these
392 ;;; groups, we tack an `H' mark at group entry for all summary lines which
393 ;;; would otherwise have no other mark. Make sure to _remove_ `H' marks for
394 ;;; any article which is _not_ genuine spam, before leaving such groups: you
395 ;;; may use `M-u' to "unread" the article, or `d' for declaring it read the
396 ;;; non-spam way. When you leave a group, all `H' marked articles, saved or
397 ;;; unsaved, are sent to Bogofilter which will study them as spam samples.
399 ;;; Messages may also be deleted in various other ways, and unless
400 ;;; `spam-ham-marks-form' gets overridden below, marks `R' and `r' for default
401 ;;; read or explicit delete, marks `X' and 'K' for automatic or explicit
402 ;;; kills, as well as mark `Y' for low scores, are all considered to be
403 ;;; associated with articles which are not spam. This assumption might be
404 ;;; false, in particular if you use kill files or score files as means for
405 ;;; detecting genuine spam, you should then adjust `spam-ham-marks-form'. When
406 ;;; you leave a group, all _unsaved_ articles bearing any the above marks are
407 ;;; sent to Bogofilter which will study these as not-spam samples. If you
408 ;;; explicit kill a lot, you might sometimes end up with articles marked `K'
409 ;;; which you never saw, and which might accidentally contain spam. Best is
410 ;;; to make sure that real spam is marked with `H', and nothing else.
412 ;;; All other marks do not contribute to Bogofilter pre-conditioning. In
413 ;;; particular, ticked, dormant or souped articles are likely to contribute
414 ;;; later, when they will get deleted for real, so there is no need to use
415 ;;; them prematurely. Explicitly expired articles do not contribute, command
416 ;;; `E' is a way to get rid of an article without Bogofilter ever seeing it.
418 ;;; In a word, with a minimum of care for associating the `H' mark for spam
419 ;;; articles only, Bogofilter training all gets fairly automatic. You should
420 ;;; do this until you get a few hundreds of articles in each category, spam
421 ;;; or not. The shell command `head -1 ~/.bogofilter/*' shows both article
422 ;;; counts. The command `S S' in summary mode, either for debugging or for
423 ;;; curiosity, triggers Bogofilter into displaying in another buffer the
424 ;;; "spamicity" score of the current article (between 0.0 and 1.0), together
425 ;;; with the article words which most significantly contribute to the score.
427 ;;; The real way for using Bogofilter, however, is to have some use tool like
428 ;;; `procmail' for invoking it on message reception, then adding some
429 ;;; recognisable header in case of detected spam. Gnus splitting rules might
430 ;;; later trip on these added headers and react by sorting such articles into
431 ;;; specific junk folders as per `spam-junk-mailgroups'. Here is a possible
432 ;;; `.procmailrc' contents (still untested -- please tell me how it goes):
436 ;;; | formail -bfI "X-Spam-Status: Yes"
438 (defvar spam-output-buffer-name "*Bogofilter Output*"
439 "Name of buffer when displaying `bogofilter -v' output.")
441 (defvar spam-spaminfo-header-regexp
442 ;; FIXME! In the following regexp, we should explain which tool produces
443 ;; which kind of header. I do not even remember them all by now. X-Junk
444 ;; (and previously X-NoSpam) are produced by the `NoSpam' tool, which has
445 ;; never been published, so it might not be reasonable leaving it in the
447 "^X-\\(jf\\|Junk\\|NoSpam\\|Spam\\|SB\\)[^:]*:"
448 "Regexp for spam markups in headers.
449 Markup from spam recognisers, as well as `Xref', are to be removed from
450 articles before they get registered by Bogofilter.")
452 (defvar spam-bogofilter-path (executable-find "bogofilter")
453 "File path of the Bogofilter executable program.
454 Force this variable to nil if you want to inhibit the functionality.")
456 (defun spam-check-bogofilter ()
457 ;; Dynamic spam check. I do not know how to check the exit status,
458 ;; so instead, read `bogofilter -v' output.
459 (when (and spam-use-bogofilter spam-bogofilter-path)
460 (spam-bogofilter-articles nil "-v" (list (gnus-summary-article-number)))
461 (when (save-excursion
462 (set-buffer spam-output-buffer-name)
463 (goto-char (point-min))
464 (re-search-forward "Spamicity: \\(0\\.9\\|1\\.0\\)" nil t))
467 (defun spam-bogofilter-score ()
468 "Use `bogofilter -v' on the current article.
469 This yields the 15 most discriminant words for this article and the
470 spamicity coefficient of each, and the overall article spamicity."
472 (when (and spam-use-bogofilter spam-bogofilter-path)
473 (spam-bogofilter-articles nil "-v" (list (gnus-summary-article-number)))
474 (with-current-buffer spam-output-buffer-name
475 (unless (zerop (buffer-size))
476 (if (<= (count-lines (point-min) (point-max)) 1)
478 (goto-char (point-max))
481 (message "%s" (buffer-substring (point-min) (point))))
482 (goto-char (point-min))
483 (display-buffer (current-buffer)))))))
485 (defun spam-bogofilter-register-routine ()
486 (when (and spam-use-bogofilter spam-bogofilter-path)
487 (let ((articles gnus-newsgroup-articles)
488 article mark ham-articles spam-articles)
490 (setq article (pop articles)
491 mark (gnus-summary-article-mark article))
492 (cond ((memq mark spam-spam-marks) (push article spam-articles))
493 ((memq article gnus-newsgroup-saved))
494 ((memq mark spam-ham-marks) (push article ham-articles))))
496 (spam-bogofilter-articles "ham" "-n" ham-articles))
498 (spam-bogofilter-articles "SPAM" "-s" spam-articles)))))
500 (defvar spam-bogofilter-initial-timeout 40
501 "Timeout in seconds for the initial reply from the `bogofilter' program.")
503 (defvar spam-bogofilter-subsequent-timeout 15
504 "Timeout in seconds for any subsequent reply from the `bogofilter' program.")
506 (defun spam-bogofilter-articles (type option articles)
507 (let ((output-buffer (get-buffer-create spam-output-buffer-name))
508 (article-copy (get-buffer-create " *Bogofilter Article Copy*"))
509 (remove-regexp (concat spam-spaminfo-header-regexp "\\|Xref:"))
511 prefix process article)
513 (setq prefix (format "Studying %d articles as %s..." (length articles)
515 (message "%s" prefix))
516 (save-excursion (set-buffer output-buffer) (erase-buffer))
517 (setq process (start-process "bogofilter" output-buffer
518 spam-bogofilter-path "-F" option))
519 (process-kill-without-query process t)
521 (save-window-excursion
523 (setq counter (1+ counter))
525 (message "%s %d" prefix counter))
526 (setq article (pop articles))
527 (gnus-summary-goto-subject article)
528 (gnus-summary-select-article)
529 (gnus-eval-in-buffer-window article-copy
530 (insert-buffer-substring gnus-original-article-buffer)
531 ;; Remove spam classification redundant headers: they may induce
532 ;; unwanted biases in later analysis.
533 (goto-char (point-min))
534 (while (not (or (eobp) (= (following-char) ?\n)))
535 (if (looking-at remove-regexp)
536 (delete-region (point)
537 (save-excursion (forward-line 1) (point)))
539 (goto-char (point-min))
540 ;; Bogofilter really wants From envelopes for counting articles.
541 ;; Fake one at the beginning, make sure there will be no other.
542 (if (looking-at "From ")
544 (insert "From nobody " (current-time-string) "\n"))
545 (let (case-fold-search)
546 (while (re-search-forward "^From " nil t)
549 (process-send-region process (point-min) (point-max))
551 ;; Sending the EOF is unwind-protected. This is to prevent lost copies
552 ;; of `bogofilter', hung on reading their standard input, in case the
553 ;; whole registering process gets interrupted by the user.
554 (process-send-eof process))
555 (kill-buffer article-copy)
556 ;; Receive process output. It sadly seems that we still have to protect
557 ;; ourselves against hung `bogofilter' processes.
558 (let ((status (process-status process))
559 (timeout (* 1000 spam-bogofilter-initial-timeout))
560 (quanta 200)) ; also counted in milliseconds
561 (while (and (not (eq status 'exit)) (> timeout 0))
562 ;; `accept-process-output' timeout is counted in microseconds.
563 (setq timeout (if (accept-process-output process 0 (* 1000 quanta))
564 (* 1000 spam-bogofilter-subsequent-timeout)
566 status (process-status process)))
567 (if (eq status 'exit)
569 (message "%s done!" prefix))
570 ;; Sigh! The process did time out... Become brutal!
571 (interrupt-process process)
572 (message "%s %d INTERRUPTED! (Article %d, status %s)"
573 (or prefix "Bogofilter process...")
574 counter article status)
575 ;; Give some time for user to read. Sitting redisplays but gives up
576 ;; if input is pending. Sleeping does not give up, but it does not
577 ;; redisplay either. Mix both: let's redisplay and not give up.
583 ;;; spam.el ends here.