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 (autoload 'query-dig "dig"))
63 (defvar spam-use-dig t
64 "True if query-dig should be used instead of query-dns.")
66 (defvar spam-use-blacklist t
67 "True if the blacklist should be used.")
69 (defvar spam-use-whitelist nil
70 "True if the whitelist should be used.")
72 (defvar spam-use-blackholes nil
73 "True if blackholes should be used.")
75 (defvar spam-use-bogofilter nil
76 "True if bogofilter should be used.")
78 (defvar spam-use-bbdb nil
79 "True if BBDB should be used.")
81 (defvar spam-use-ifile nil
82 "True if ifile should be used.")
84 (defvar spam-split-group "spam"
85 "Usual group name where spam should be split.")
87 (defvar spam-junk-mailgroups
88 ;; FIXME! The mailgroup list evidently depends on other choices made by the
89 ;; user, so the built-in default below is not likely to be appropriate.
90 (cons spam-split-group '("mail.junk" "poste.pourriel"))
91 "Mailgroups which are dedicated by splitting to receive various junk.
92 All unmarked article in such group receive the spam mark on group entry.")
94 ;; FIXME! For `spam-ham-marks' and `spam-spam-marks', I wonder if it would
95 ;; not be easier for the user to just accept a string of mark letters, instead
96 ;; of a list of Gnus variable names. In such case, the stunt of deferred
97 ;; evaluation would not be useful anymore. Lars?? :-)
99 ;; FIXME! It is rather questionable to see `K', `X' and `Y' as indicating
100 ;; positive ham. It much depends on how and why people use kill files, score
101 ;; files, and the kill command. Maybe it would be better, by default, to not
102 ;; process a message neither as ham nor spam, that is, just ignore it for
103 ;; learning purposes, when we are not sure of how the user sees it.
104 ;; But `r' and `R' should undoubtedly be seen as ham.
106 ;; FIXME! Some might consider overkill to define a list of spam marks. On
107 ;; the other hand, who knows, some users might for example like that
108 ;; explicitly `E'xpired articles be processed as positive spam.
110 (defvar spam-ham-marks
111 (list gnus-del-mark gnus-read-mark gnus-killed-mark
112 gnus-kill-file-mark gnus-low-score-mark)
113 "Marks considered as being ham (positively not spam).
114 Such articles will be transmitted to `bogofilter -n' on group exit.")
116 (defvar spam-spam-marks
117 (list gnus-spam-mark)
118 "Marks considered as being spam (positively spam).
119 Such articles will be transmitted to `bogofilter -s' on group exit.")
121 ;; FIXME! Ideally, the remainder of this page should be fully integrated
122 ;; within `gnus-sum.el'.
124 ;;; Key bindings for spam control.
126 ;; FIXME! The justification for `M-d' is that this is what Paul Graham
127 ;; suggests in his original article, and what Eric Raymond's patch for Mutt
128 ;; uses. But more importantly, that binding was still free in Summary mode!
130 ;; FIXME! Lars has not blessed the following key bindings yet. It looks
131 ;; convenient that the score analysis command uses a sequence ending with the
132 ;; letter `t', so it nicely parallels `B t' or `V t'. `M-d' is a kind of
133 ;; "alternate" `d', it is also the sequence suggested in Paul Graham article,
134 ;; and also in Eric Raymond's patch for Mutt. `S x' might be the more
135 ;; official key binding for `M-d'.
137 (gnus-define-keys gnus-summary-mode-map
138 "St" spam-bogofilter-score
139 "Sx" gnus-summary-mark-as-spam
140 "Mst" spam-bogofilter-score
141 "Msx" gnus-summary-mark-as-spam
142 "\M-d" gnus-summary-mark-as-spam)
144 ;;; How to highlight a spam summary line.
146 ;; FIXME! Of course, `gnus-splash-face' has another purpose. Maybe a
147 ;; special face should be created, named and used instead, for spam lines.
149 (push '((eq mark gnus-spam-mark) . gnus-splash-face)
150 gnus-summary-highlight)
152 ;;; Hooks dispatching. A bit raw for now.
154 (defun spam-summary-prepare ()
155 (spam-mark-junk-as-spam-routine))
157 (defun spam-summary-prepare-exit ()
158 (spam-bogofilter-register-routine))
160 (add-hook 'gnus-summary-prepare-hook 'spam-summary-prepare)
161 (add-hook 'gnus-summary-prepare-exit-hook 'spam-summary-prepare-exit)
163 (defun spam-mark-junk-as-spam-routine ()
164 (when (member gnus-newsgroup-name spam-junk-mailgroups)
165 (let ((articles gnus-newsgroup-articles)
168 (setq article (pop articles))
169 (when (eq (gnus-summary-article-mark article) gnus-unread-mark)
170 (gnus-summary-mark-article article gnus-spam-mark))))))
172 ;;;; Spam determination.
175 (defvar spam-list-of-checks
176 '((spam-use-blacklist . spam-check-blacklist)
177 (spam-use-whitelist . spam-check-whitelist)
178 (spam-use-bbdb . spam-check-bbdb)
179 (spam-use-ifile . spam-check-ifile)
180 (spam-use-blackholes . spam-check-blackholes)
181 (spam-use-bogofilter . spam-check-bogofilter))
182 "The spam-list-of-checks list contains pairs associating a parameter
183 variable with a spam checking function. If the parameter variable is
184 true, then the checking function is called, and its value decides what
185 happens. Each individual check may return `nil', `t', or a mailgroup
186 name. The value `nil' means that the check does not yield a decision,
187 and so, that further checks are needed. The value `t' means that the
188 message is definitely not spam, and that further spam checks should be
189 inhibited. Otherwise, a mailgroup name is returned where the mail
190 should go, and further checks are also inhibited. The usual mailgroup
191 name is the value of `spam-split-group', meaning that the message is
195 "Split this message into the `spam' group if it is spam.
196 This function can be used as an entry in `nnmail-split-fancy', for
197 example like this: (: spam-split)
199 See the Info node `(gnus)Fancy Mail Splitting' for more details."
202 (let ((list-of-checks spam-list-of-checks)
204 (while (and list-of-checks (not decision))
205 (let ((pair (pop list-of-checks)))
206 (when (symbol-value (car pair))
207 (setq decision (funcall (cdr pair))))))
214 (defvar spam-blackhole-servers '("bl.spamcop.net"
218 "List of blackhole servers.")
220 (defun spam-check-blackholes ()
221 "Check the Received headers for blackholed relays."
222 (let ((headers (message-fetch-field "received"))
227 (goto-char (point-min))
228 (while (re-search-forward
229 "\\[\\([0-9]+.[0-9]+.[0-9]+.[0-9]+\\)\\]" nil t)
230 (message "Blackhole search found host IP %s." (match-string 1))
231 (push (mapconcat 'identity
232 (nreverse (split-string (match-string 1) "\\."))
235 (dolist (server spam-blackhole-servers)
237 (let ((query-string (concat ip "." server)))
239 (let ((query-result (query-dig query-string)))
241 (message "spam detected with blackhole check of relay %s (dig query result '%s')" query-string query-result)
242 (push (list ip server query-result)
244 ;; else, if not using dig.el
245 (when (query-dns query-string)
246 (push (list ip server (query-dns query-string 'TXT))
251 ;;;; Blacklists and whitelists.
253 (defvar spam-directory "~/News/spam/"
254 "When spam files are kept.")
256 (defvar spam-whitelist (expand-file-name "whitelist" spam-directory)
257 "The location of the whitelist.
258 The file format is one regular expression per line.
259 The regular expression is matched against the address.")
261 (defvar spam-blacklist (expand-file-name "blacklist" spam-directory)
262 "The location of the blacklist.
263 The file format is one regular expression per line.
264 The regular expression is matched against the address.")
266 (defvar spam-whitelist-cache nil)
267 (defvar spam-blacklist-cache nil)
269 (defun spam-enter-whitelist (address)
270 "Enter ADDRESS into the whitelist."
271 (interactive "sAddress: ")
272 (spam-enter-list address spam-whitelist)
273 (setq spam-whitelist-cache nil))
275 (defun spam-enter-blacklist (address)
276 "Enter ADDRESS into the blacklist."
277 (interactive "sAddress: ")
278 (spam-enter-list address spam-blacklist)
279 (setq spam-blacklist-cache nil))
281 (defun spam-enter-list (address file)
282 "Enter ADDRESS into the given FILE, either the whitelist or the blacklist."
283 (unless (file-exists-p (file-name-directory file))
284 (make-directory (file-name-directory file) t))
287 (find-file-noselect file))
288 (goto-char (point-max))
291 (insert address "\n")
294 ;;; returns nil if the sender is in the whitelist, spam-split-group otherwise
295 (defun spam-check-whitelist ()
296 ;; FIXME! Should it detect when file timestamps change?
297 (unless spam-whitelist-cache
298 (setq spam-whitelist-cache (spam-parse-list spam-whitelist)))
299 (if (spam-from-listed-p spam-whitelist-cache) nil spam-split-group))
301 ;;; original idea from Alexander Kotelnikov <sacha@giotto.sj.ru>
305 (defun spam-check-bbdb ()
306 "We want messages from people who are in the BBDB not to be split to spam"
307 (let ((who (message-fetch-field "from")))
309 (setq who (regexp-quote (cadr (gnus-extract-address-components who))))
310 (if (bbdb-search (bbdb-records) nil nil who) nil spam-split-group)))))
311 (file-error (setq spam-list-of-checks
312 (delete (assoc 'spam-use-bbdb spam-list-of-checks)
313 spam-list-of-checks))))
315 ;;; check the ifile backend; return nil if the mail was NOT classified as spam
318 (require 'ifile-gnus)
320 (defun spam-check-ifile ()
321 (let ((ifile-primary-spam-group spam-split-group))
322 (ifile-spam-filter nil))))
323 (file-error (setq spam-list-of-checks
324 (delete (assoc 'spam-use-ifile spam-list-of-checks)
325 spam-list-of-checks))))
327 (defun spam-check-blacklist ()
328 ;; FIXME! Should it detect when file timestamps change?
329 (unless spam-blacklist-cache
330 (setq spam-blacklist-cache (spam-parse-list spam-blacklist)))
331 (and (spam-from-listed-p spam-blacklist-cache) spam-split-group))
334 (defalias 'spam-point-at-eol (if (fboundp 'point-at-eol)
336 'line-end-position)))
338 (defun spam-parse-list (file)
339 (when (file-readable-p file)
340 (let (contents address)
342 (insert-file-contents file)
344 (setq address (buffer-substring (point) (spam-point-at-eol)))
346 (unless (zerop (length address))
347 (setq address (regexp-quote address))
348 (while (string-match "\\\\\\*" address)
349 (setq address (replace-match ".*" t t address)))
350 (push address contents))))
351 (nreverse contents))))
353 (defun spam-from-listed-p (cache)
354 (let ((from (message-fetch-field "from"))
357 (when (string-match (pop cache) from)
363 ;;;; Training via Bogofilter. Last updated 2002-09-02.
365 ;;; See Paul Graham article, at `http://www.paulgraham.com/spam.html'.
367 ;;; This page is for those wanting to control spam with the help of Eric
368 ;;; Raymond's speedy Bogofilter, see http://www.tuxedo.org/~esr/bogofilter.
369 ;;; This has been tested with a locally patched copy of version 0.4.
371 ;;; Make sure Bogofilter is installed. Bogofilter internally uses Judy fast
372 ;;; associative arrays, so you need to install Judy first, and Bogofilter
373 ;;; next. Fetch both distributions by visiting the following links and
374 ;;; downloading the latest version of each:
376 ;;; http://sourceforge.net/projects/judy/
377 ;;; http://www.tuxedo.org/~esr/bogofilter/
379 ;;; Unpack the Judy distribution and enter its main directory. Then do:
385 ;;; You will likely need to become super-user for the last step. Then, unpack
386 ;;; the Bogofilter distribution and enter its main directory:
391 ;;; Here as well, you need to become super-user for the last step. Now,
392 ;;; initialize your word lists by doing, under your own identity:
394 ;;; mkdir ~/.bogofilter
395 ;;; touch ~/.bogofilter/badlist
396 ;;; touch ~/.bogofilter/goodlist
398 ;;; These two files are text files you may edit, but you normally don't!
400 ;;; The `M-d' command gets added to Gnus summary mode, marking current article
401 ;;; as spam, showing it with the `H' mark. Whenever you see a spam article,
402 ;;; make sure to mark its summary line with `M-d' before leaving the group.
403 ;;; Some groups, as per variable `spam-junk-mailgroups' below, receive articles
404 ;;; from Gnus splitting on clues added by spam recognisers, so for these
405 ;;; groups, we tack an `H' mark at group entry for all summary lines which
406 ;;; would otherwise have no other mark. Make sure to _remove_ `H' marks for
407 ;;; any article which is _not_ genuine spam, before leaving such groups: you
408 ;;; may use `M-u' to "unread" the article, or `d' for declaring it read the
409 ;;; non-spam way. When you leave a group, all `H' marked articles, saved or
410 ;;; unsaved, are sent to Bogofilter which will study them as spam samples.
412 ;;; Messages may also be deleted in various other ways, and unless
413 ;;; `spam-ham-marks-form' gets overridden below, marks `R' and `r' for default
414 ;;; read or explicit delete, marks `X' and 'K' for automatic or explicit
415 ;;; kills, as well as mark `Y' for low scores, are all considered to be
416 ;;; associated with articles which are not spam. This assumption might be
417 ;;; false, in particular if you use kill files or score files as means for
418 ;;; detecting genuine spam, you should then adjust `spam-ham-marks-form'. When
419 ;;; you leave a group, all _unsaved_ articles bearing any the above marks are
420 ;;; sent to Bogofilter which will study these as not-spam samples. If you
421 ;;; explicit kill a lot, you might sometimes end up with articles marked `K'
422 ;;; which you never saw, and which might accidentally contain spam. Best is
423 ;;; to make sure that real spam is marked with `H', and nothing else.
425 ;;; All other marks do not contribute to Bogofilter pre-conditioning. In
426 ;;; particular, ticked, dormant or souped articles are likely to contribute
427 ;;; later, when they will get deleted for real, so there is no need to use
428 ;;; them prematurely. Explicitly expired articles do not contribute, command
429 ;;; `E' is a way to get rid of an article without Bogofilter ever seeing it.
431 ;;; In a word, with a minimum of care for associating the `H' mark for spam
432 ;;; articles only, Bogofilter training all gets fairly automatic. You should
433 ;;; do this until you get a few hundreds of articles in each category, spam
434 ;;; or not. The shell command `head -1 ~/.bogofilter/*' shows both article
435 ;;; counts. The command `S S' in summary mode, either for debugging or for
436 ;;; curiosity, triggers Bogofilter into displaying in another buffer the
437 ;;; "spamicity" score of the current article (between 0.0 and 1.0), together
438 ;;; with the article words which most significantly contribute to the score.
440 ;;; The real way for using Bogofilter, however, is to have some use tool like
441 ;;; `procmail' for invoking it on message reception, then adding some
442 ;;; recognisable header in case of detected spam. Gnus splitting rules might
443 ;;; later trip on these added headers and react by sorting such articles into
444 ;;; specific junk folders as per `spam-junk-mailgroups'. Here is a possible
445 ;;; `.procmailrc' contents (still untested -- please tell me how it goes):
449 ;;; | formail -bfI "X-Spam-Status: Yes"
451 (defvar spam-output-buffer-name "*Bogofilter Output*"
452 "Name of buffer when displaying `bogofilter -v' output.")
454 (defvar spam-spaminfo-header-regexp
455 ;; FIXME! In the following regexp, we should explain which tool produces
456 ;; which kind of header. I do not even remember them all by now. X-Junk
457 ;; (and previously X-NoSpam) are produced by the `NoSpam' tool, which has
458 ;; never been published, so it might not be reasonable leaving it in the
460 "^X-\\(jf\\|Junk\\|NoSpam\\|Spam\\|SB\\)[^:]*:"
461 "Regexp for spam markups in headers.
462 Markup from spam recognisers, as well as `Xref', are to be removed from
463 articles before they get registered by Bogofilter.")
465 (defvar spam-bogofilter-path (executable-find "bogofilter")
466 "File path of the Bogofilter executable program.
467 Force this variable to nil if you want to inhibit the functionality.")
469 (defun spam-check-bogofilter ()
470 ;; Dynamic spam check. I do not know how to check the exit status,
471 ;; so instead, read `bogofilter -v' output.
472 (when (and spam-use-bogofilter spam-bogofilter-path)
473 (spam-bogofilter-articles nil "-v" (list (gnus-summary-article-number)))
474 (when (save-excursion
475 (set-buffer spam-output-buffer-name)
476 (goto-char (point-min))
477 (re-search-forward "Spamicity: \\(0\\.9\\|1\\.0\\)" nil t))
480 (defun spam-bogofilter-score ()
481 "Use `bogofilter -v' on the current article.
482 This yields the 15 most discriminant words for this article and the
483 spamicity coefficient of each, and the overall article spamicity."
485 (when (and spam-use-bogofilter spam-bogofilter-path)
486 (spam-bogofilter-articles nil "-v" (list (gnus-summary-article-number)))
487 (with-current-buffer spam-output-buffer-name
488 (unless (zerop (buffer-size))
489 (if (<= (count-lines (point-min) (point-max)) 1)
491 (goto-char (point-max))
494 (message "%s" (buffer-substring (point-min) (point))))
495 (goto-char (point-min))
496 (display-buffer (current-buffer)))))))
498 (defun spam-bogofilter-register-routine ()
499 (when (and spam-use-bogofilter spam-bogofilter-path)
500 (let ((articles gnus-newsgroup-articles)
501 article mark ham-articles spam-articles)
503 (setq article (pop articles)
504 mark (gnus-summary-article-mark article))
505 (cond ((memq mark spam-spam-marks) (push article spam-articles))
506 ((memq article gnus-newsgroup-saved))
507 ((memq mark spam-ham-marks) (push article ham-articles))))
509 (spam-bogofilter-articles "ham" "-n" ham-articles))
511 (spam-bogofilter-articles "SPAM" "-s" spam-articles)))))
513 (defvar spam-bogofilter-initial-timeout 40
514 "Timeout in seconds for the initial reply from the `bogofilter' program.")
516 (defvar spam-bogofilter-subsequent-timeout 15
517 "Timeout in seconds for any subsequent reply from the `bogofilter' program.")
519 (defun spam-bogofilter-articles (type option articles)
520 (let ((output-buffer (get-buffer-create spam-output-buffer-name))
521 (article-copy (get-buffer-create " *Bogofilter Article Copy*"))
522 (remove-regexp (concat spam-spaminfo-header-regexp "\\|Xref:"))
524 prefix process article)
526 (setq prefix (format "Studying %d articles as %s..." (length articles)
528 (message "%s" prefix))
529 (save-excursion (set-buffer output-buffer) (erase-buffer))
530 (setq process (start-process "bogofilter" output-buffer
531 spam-bogofilter-path "-F" option))
532 (process-kill-without-query process t)
534 (save-window-excursion
536 (setq counter (1+ counter))
538 (message "%s %d" prefix counter))
539 (setq article (pop articles))
540 (gnus-summary-goto-subject article)
541 (gnus-summary-select-article)
542 (gnus-eval-in-buffer-window article-copy
543 (insert-buffer-substring gnus-original-article-buffer)
544 ;; Remove spam classification redundant headers: they may induce
545 ;; unwanted biases in later analysis.
546 (goto-char (point-min))
547 (while (not (or (eobp) (= (following-char) ?\n)))
548 (if (looking-at remove-regexp)
549 (delete-region (point)
550 (save-excursion (forward-line 1) (point)))
552 (goto-char (point-min))
553 ;; Bogofilter really wants From envelopes for counting articles.
554 ;; Fake one at the beginning, make sure there will be no other.
555 (if (looking-at "From ")
557 (insert "From nobody " (current-time-string) "\n"))
558 (let (case-fold-search)
559 (while (re-search-forward "^From " nil t)
562 (process-send-region process (point-min) (point-max))
564 ;; Sending the EOF is unwind-protected. This is to prevent lost copies
565 ;; of `bogofilter', hung on reading their standard input, in case the
566 ;; whole registering process gets interrupted by the user.
567 (process-send-eof process))
568 (kill-buffer article-copy)
569 ;; Receive process output. It sadly seems that we still have to protect
570 ;; ourselves against hung `bogofilter' processes.
571 (let ((status (process-status process))
572 (timeout (* 1000 spam-bogofilter-initial-timeout))
573 (quanta 200)) ; also counted in milliseconds
574 (while (and (not (eq status 'exit)) (> timeout 0))
575 ;; `accept-process-output' timeout is counted in microseconds.
576 (setq timeout (if (accept-process-output process 0 (* 1000 quanta))
577 (* 1000 spam-bogofilter-subsequent-timeout)
579 status (process-status process)))
580 (if (eq status 'exit)
582 (message "%s done!" prefix))
583 ;; Sigh! The process did time out... Become brutal!
584 (interrupt-process process)
585 (message "%s %d INTERRUPTED! (Article %d, status %s)"
586 (or prefix "Bogofilter process...")
587 counter article status)
588 ;; Give some time for user to read. Sitting redisplays but gives up
589 ;; if input is pending. Sleeping does not give up, but it does not
590 ;; redisplay either. Mix both: let's redisplay and not give up.
596 ;;; spam.el ends here.