(spam-bogofilter-score): check bogofilter headers before
[gnus] / lisp / spam.el
1 ;;; spam.el --- Identifying spam
2 ;; Copyright (C) 2002, 2003 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 ;;; Several TODO items are marked as such
34
35 ;;; Code:
36
37 (require 'gnus-sum)
38
39 (require 'gnus-uu)                      ; because of key prefix issues
40 (require 'gnus) ; for the definitions of group content classification and spam processors
41 (require 'message)                      ;for the message-fetch-field functions
42
43 ;; for nnimap-split-download-body-default
44 (eval-when-compile (require 'nnimap))
45
46 ;; autoload executable-find
47 (eval-and-compile
48   ;; executable-find is not autoloaded in Emacs 20
49   (autoload 'executable-find "executable"))
50
51 ;; autoload query-dig
52 (eval-and-compile
53   (autoload 'query-dig "dig"))
54
55 ;; autoload query-dns
56 (eval-and-compile
57   (autoload 'query-dns "dns"))
58
59 ;;; Main parameters.
60
61 (defgroup spam nil
62   "Spam configuration.")
63
64 (defcustom spam-directory "~/News/spam/"
65   "Directory for spam whitelists and blacklists."
66   :type 'directory
67   :group 'spam)
68
69 (defcustom spam-move-spam-nonspam-groups-only t
70   "Whether spam should be moved in non-spam groups only.
71 When nil, only ham and unclassified groups will have their spam moved
72 to the spam-process-destination.  When t, spam will also be moved from
73 spam groups."
74   :type 'boolean
75   :group 'spam)
76
77 (defcustom spam-mark-ham-unread-before-move-from-spam-group nil
78   "Whether ham should be marked unread before it's moved out of a spam
79 group according to ham-process-destination.  This variable is an
80 official entry in the international Longest Variable Name
81 Competition."
82   :type 'boolean
83   :group 'spam)
84
85 (defcustom spam-whitelist (expand-file-name "whitelist" spam-directory)
86   "The location of the whitelist.
87 The file format is one regular expression per line.
88 The regular expression is matched against the address."
89   :type 'file
90   :group 'spam)
91
92 (defcustom spam-blacklist (expand-file-name "blacklist" spam-directory)
93   "The location of the blacklist.
94 The file format is one regular expression per line.
95 The regular expression is matched against the address."
96   :type 'file
97   :group 'spam)
98
99 (defcustom spam-use-dig t
100   "Whether query-dig should be used instead of query-dns."
101   :type 'boolean
102   :group 'spam)
103
104 (defcustom spam-use-blacklist nil
105   "Whether the blacklist should be used by spam-split."
106   :type 'boolean
107   :group 'spam)
108
109 (defcustom spam-use-whitelist nil
110   "Whether the whitelist should be used by spam-split."
111   :type 'boolean
112   :group 'spam)
113
114 (defcustom spam-use-whitelist-exclusive nil
115   "Whether whitelist-exclusive should be used by spam-split.
116 Exclusive whitelisting means that all messages from senders not in the whitelist
117 are considered spam."
118   :type 'boolean
119   :group 'spam)
120
121 (defcustom spam-use-blackholes nil
122   "Whether blackholes should be used by spam-split."
123   :type 'boolean
124   :group 'spam)
125
126 (defcustom spam-use-hashcash nil
127   "Whether hashcash payments should be detected by spam-split."
128   :type 'boolean
129   :group 'spam)
130
131 (defcustom spam-use-regex-headers nil
132   "Whether a header regular expression match should be used by spam-split.
133 Also see the variable `spam-spam-regex-headers' and `spam-ham-regex-headers'."
134   :type 'boolean
135   :group 'spam)
136
137 (defcustom spam-use-bogofilter-headers nil
138   "Whether bogofilter headers should be used by spam-split.
139 Enable this if you pre-process messages with Bogofilter BEFORE Gnus sees them."
140   :type 'boolean
141   :group 'spam)
142
143 (defcustom spam-use-bogofilter nil
144   "Whether bogofilter should be invoked by spam-split.
145 Enable this if you want Gnus to invoke Bogofilter on new messages."
146   :type 'boolean
147   :group 'spam)
148
149 (defcustom spam-use-BBDB nil
150   "Whether BBDB should be used by spam-split."
151   :type 'boolean
152   :group 'spam)
153
154 (defcustom spam-use-BBDB-exclusive nil
155   "Whether BBDB-exclusive should be used by spam-split.
156 Exclusive BBDB means that all messages from senders not in the BBDB are 
157 considered spam."
158   :type 'boolean
159   :group 'spam)
160
161 (defcustom spam-use-ifile nil
162   "Whether ifile should be used by spam-split."
163   :type 'boolean
164   :group 'spam)
165
166 (defcustom spam-use-stat nil
167   "Whether spam-stat should be used by spam-split."
168   :type 'boolean
169   :group 'spam)
170
171 (defcustom spam-split-group "spam"
172   "Group name where incoming spam should be put by spam-split."
173   :type 'string
174   :group 'spam)
175
176 (defcustom spam-junk-mailgroups (cons spam-split-group '("mail.junk" "poste.pourriel"))
177   "Mailgroups with spam contents.
178 All unmarked article in such group receive the spam mark on group entry."
179   :type '(repeat (string :tag "Group"))
180   :group 'spam)
181
182 (defcustom spam-blackhole-servers '("bl.spamcop.net" "relays.ordb.org" 
183                                     "dev.null.dk" "relays.visi.com")
184   "List of blackhole servers."
185   :type '(repeat (string :tag "Server"))
186   :group 'spam)
187
188 (defcustom spam-blackhole-good-server-regex nil
189   "String matching IP addresses that should not be checked in the blackholes"
190   :type 'regexp
191   :group 'spam)
192
193 (defcustom spam-face 'gnus-splash-face
194   "Face for spam-marked articles"
195   :type 'face
196   :group 'spam)
197
198 (defcustom spam-regex-headers-spam '("^X-Spam-Flag: YES")
199   "Regular expression for positive header spam matches"
200   :type '(repeat (regexp :tag "Regular expression to match spam header"))
201   :group 'spam)
202
203 (defcustom spam-regex-headers-ham '("^X-Spam-Flag: NO")
204   "Regular expression for positive header ham matches"
205   :type '(repeat (regexp :tag "Regular expression to match ham header"))
206   :group 'spam)
207
208 (defgroup spam-ifile nil
209   "Spam ifile configuration."
210   :group 'spam)
211
212 (defcustom spam-ifile-path (executable-find "ifile")
213   "File path of the ifile executable program."
214   :type '(choice (file :tag "Location of ifile")
215                  (const :tag "ifile is not installed"))
216   :group 'spam-ifile)
217
218 (defcustom spam-ifile-database-path nil
219   "File path of the ifile database."
220   :type '(choice (file :tag "Location of the ifile database")
221                  (const :tag "Use the default"))
222   :group 'spam-ifile)
223
224 (defcustom spam-ifile-spam-category "spam"
225   "Name of the spam ifile category."  
226   :type 'string
227   :group 'spam-ifile)
228
229 (defcustom spam-ifile-ham-category nil
230   "Name of the ham ifile category.  If nil, the current group name will
231 be used."
232   :type '(choice (string :tag "Use a fixed category")
233                 (const :tag "Use the current group name"))
234   :group 'spam-ifile)
235
236 (defcustom spam-ifile-all-categories nil
237   "Whether the ifile check will return all categories, or just spam.
238 Set this to t if you want to use the spam-split invocation of ifile as
239 your main source of newsgroup names."
240   :type 'boolean
241   :group 'spam-ifile)
242
243 (defgroup spam-bogofilter nil
244   "Spam bogofilter configuration."
245   :group 'spam)
246
247 (defcustom spam-bogofilter-path (executable-find "bogofilter")
248   "File path of the Bogofilter executable program."
249   :type '(choice (file :tag "Location of bogofilter")
250                  (const :tag "Bogofilter is not installed"))
251   :group 'spam-bogofilter)
252
253 (defcustom spam-bogofilter-header "X-Bogosity"
254   "The header that Bogofilter inserts in messages."
255   :type 'string
256   :group 'spam-bogofilter)
257
258 (defcustom spam-bogofilter-spam-switch "-s"
259   "The switch that Bogofilter uses to register spam messages."
260   :type 'string
261   :group 'spam-bogofilter)
262
263 (defcustom spam-bogofilter-ham-switch "-n"
264   "The switch that Bogofilter uses to register ham messages."
265   :type 'string
266   :group 'spam-bogofilter)
267
268 (defcustom spam-bogofilter-bogosity-positive-spam-header "^\\(Yes\\|Spam\\)"
269   "The regex on `spam-bogofilter-header' for positive spam identification."
270   :type 'regexp
271   :group 'spam-bogofilter)
272
273 (defcustom spam-bogofilter-database-directory nil
274   "Directory path of the Bogofilter databases."
275   :type '(choice (directory :tag "Location of the Bogofilter database directory")
276                  (const :tag "Use the default"))
277   :group 'spam-ifile)
278
279 ;;; Key bindings for spam control.
280
281 (gnus-define-keys gnus-summary-mode-map
282   "St" spam-bogofilter-score
283   "Sx" gnus-summary-mark-as-spam
284   "Mst" spam-bogofilter-score
285   "Msx" gnus-summary-mark-as-spam
286   "\M-d" gnus-summary-mark-as-spam)
287
288 ;;; How to highlight a spam summary line.
289
290 ;; TODO: How do we redo this every time spam-face is customized?
291
292 (push '((eq mark gnus-spam-mark) . spam-face)
293       gnus-summary-highlight)
294
295 ;; convenience functions
296 (defun spam-group-ham-mark-p (group mark &optional spam)
297   (when (stringp group)
298     (let* ((marks (spam-group-ham-marks group spam))
299            (marks (if (symbolp mark) 
300                       marks 
301                     (mapcar 'symbol-value marks))))
302       (memq mark marks))))
303
304 (defun spam-group-spam-mark-p (group mark)
305   (spam-group-ham-mark-p group mark t))
306
307 (defun spam-group-ham-marks (group &optional spam)
308   (when (stringp group)
309     (let* ((marks (if spam
310                      (gnus-parameter-spam-marks group)
311                    (gnus-parameter-ham-marks group)))
312            (marks (car marks))
313            (marks (if (listp (car marks)) (car marks) marks)))
314       marks)))
315
316 (defun spam-group-spam-marks (group)
317   (spam-group-ham-marks group t))
318
319 (defun spam-group-spam-contents-p (group)
320   (if (stringp group)
321       (or (member group spam-junk-mailgroups)
322           (memq 'gnus-group-spam-classification-spam 
323                 (gnus-parameter-spam-contents group)))
324     nil))
325   
326 (defun spam-group-ham-contents-p (group)
327   (if (stringp group)
328       (memq 'gnus-group-spam-classification-ham 
329             (gnus-parameter-spam-contents group))
330     nil))
331
332 (defun spam-group-processor-p (group processor)
333   (if (and (stringp group)
334            (symbolp processor))
335       (member processor (car (gnus-parameter-spam-process group)))
336     nil))
337
338 (defun spam-group-spam-processor-bogofilter-p (group)
339   (spam-group-processor-p group 'gnus-group-spam-exit-processor-bogofilter))
340
341 (defun spam-group-spam-processor-blacklist-p (group)
342   (spam-group-processor-p group 'gnus-group-spam-exit-processor-blacklist))
343
344 (defun spam-group-spam-processor-ifile-p (group)
345   (spam-group-processor-p group 'gnus-group-spam-exit-processor-ifile))
346
347 (defun spam-group-ham-processor-ifile-p (group)
348   (spam-group-processor-p group 'gnus-group-ham-exit-processor-ifile))
349
350 (defun spam-group-ham-processor-bogofilter-p (group)
351   (spam-group-processor-p group 'gnus-group-ham-exit-processor-bogofilter))
352
353 (defun spam-group-spam-processor-stat-p (group)
354   (spam-group-processor-p group 'gnus-group-spam-exit-processor-stat))
355
356 (defun spam-group-ham-processor-stat-p (group)
357   (spam-group-processor-p group 'gnus-group-ham-exit-processor-stat))
358
359 (defun spam-group-ham-processor-whitelist-p (group)
360   (spam-group-processor-p group 'gnus-group-ham-exit-processor-whitelist))
361
362 (defun spam-group-ham-processor-BBDB-p (group)
363   (spam-group-processor-p group 'gnus-group-ham-exit-processor-BBDB))
364
365 (defun spam-group-ham-processor-copy-p (group)
366   (spam-group-processor-p group 'gnus-group-ham-exit-processor-copy))
367
368 ;;; Summary entry and exit processing.
369
370 (defun spam-summary-prepare ()
371   (spam-mark-junk-as-spam-routine))
372
373 (add-hook 'gnus-summary-prepare-hook 'spam-summary-prepare)
374
375 ;; The spam processors are invoked for any group, spam or ham or neither
376 (defun spam-summary-prepare-exit ()
377   (unless gnus-group-is-exiting-without-update-p
378     (gnus-message 6 "Exiting summary buffer and applying spam rules")
379     (when (and spam-bogofilter-path
380                (spam-group-spam-processor-bogofilter-p gnus-newsgroup-name))
381       (gnus-message 5 "Registering spam with bogofilter")
382       (spam-bogofilter-register-spam-routine))
383   
384     (when (and spam-ifile-path
385                (spam-group-spam-processor-ifile-p gnus-newsgroup-name))
386       (gnus-message 5 "Registering spam with ifile")
387       (spam-ifile-register-spam-routine))
388   
389     (when (spam-group-spam-processor-stat-p gnus-newsgroup-name)
390       (gnus-message 5 "Registering spam with spam-stat")
391       (spam-stat-register-spam-routine))
392
393     (when (spam-group-spam-processor-blacklist-p gnus-newsgroup-name)
394       (gnus-message 5 "Registering spam with the blacklist")
395       (spam-blacklist-register-routine))
396
397     (if spam-move-spam-nonspam-groups-only      
398         (when (not (spam-group-spam-contents-p gnus-newsgroup-name))
399           (spam-mark-spam-as-expired-and-move-routine
400            (gnus-parameter-spam-process-destination gnus-newsgroup-name)))
401       (gnus-message 5 "Marking spam as expired and moving it to %s" gnus-newsgroup-name)
402       (spam-mark-spam-as-expired-and-move-routine 
403        (gnus-parameter-spam-process-destination gnus-newsgroup-name)))
404
405     ;; now we redo spam-mark-spam-as-expired-and-move-routine to only
406     ;; expire spam, in case the above did not expire them
407     (gnus-message 5 "Marking spam as expired without moving it")
408     (spam-mark-spam-as-expired-and-move-routine nil)
409
410     (when (spam-group-ham-contents-p gnus-newsgroup-name)
411       (when (spam-group-ham-processor-whitelist-p gnus-newsgroup-name)
412         (gnus-message 5 "Registering ham with the whitelist")
413         (spam-whitelist-register-routine))
414       (when (spam-group-ham-processor-ifile-p gnus-newsgroup-name)
415         (gnus-message 5 "Registering ham with ifile")
416         (spam-ifile-register-ham-routine))
417       (when (spam-group-ham-processor-bogofilter-p gnus-newsgroup-name)
418         (gnus-message 5 "Registering ham with Bogofilter")
419         (spam-bogofilter-register-ham-routine))
420       (when (spam-group-ham-processor-stat-p gnus-newsgroup-name)
421         (gnus-message 5 "Registering ham with spam-stat")
422         (spam-stat-register-ham-routine))
423       (when (spam-group-ham-processor-BBDB-p gnus-newsgroup-name)
424         (gnus-message 5 "Registering ham with the BBDB")
425         (spam-BBDB-register-routine)))
426
427     (when (spam-group-ham-processor-copy-p gnus-newsgroup-name)
428       (gnus-message 5 "Copying ham")
429       (spam-ham-move-routine
430        (gnus-parameter-ham-process-destination gnus-newsgroup-name) t))
431
432     ;; now move all ham articles out of spam groups
433     (when (spam-group-spam-contents-p gnus-newsgroup-name)
434       (gnus-message 5 "Moving ham messages from spam group")
435       (spam-ham-move-routine
436        (gnus-parameter-ham-process-destination gnus-newsgroup-name)))))
437
438 (add-hook 'gnus-summary-prepare-exit-hook 'spam-summary-prepare-exit)
439
440 (defun spam-mark-junk-as-spam-routine ()
441   ;; check the global list of group names spam-junk-mailgroups and the
442   ;; group parameters
443   (when (spam-group-spam-contents-p gnus-newsgroup-name)
444     (gnus-message 5 "Marking unread articles as spam")
445     (let ((articles gnus-newsgroup-articles)
446           article)
447       (while articles
448         (setq article (pop articles))
449         (when (eq (gnus-summary-article-mark article) gnus-unread-mark)
450           (gnus-summary-mark-article article gnus-spam-mark))))))
451
452 (defun spam-mark-spam-as-expired-and-move-routine (&optional group)
453   (gnus-summary-kill-process-mark)
454   (let ((articles gnus-newsgroup-articles)
455         article tomove)
456     (dolist (article articles)
457       (when (eq (gnus-summary-article-mark article) gnus-spam-mark)
458         (gnus-summary-mark-article article gnus-expirable-mark)
459         (push article tomove)))
460
461     ;; now do the actual move
462     (when (and tomove
463                (stringp group))
464       (dolist (article tomove)
465         (gnus-summary-set-process-mark article))
466       (when tomove (gnus-summary-move-article nil group))))
467   (gnus-summary-yank-process-mark))
468  
469 (defun spam-ham-move-routine (&optional group copy)
470   (gnus-summary-kill-process-mark)
471   (let ((articles gnus-newsgroup-articles)
472         article mark tomove)
473     (when (stringp group)               ; this routine will do nothing
474                                         ; without a valid group
475       (dolist (article articles)
476         (when (spam-group-ham-mark-p gnus-newsgroup-name
477                                      (gnus-summary-article-mark article))
478           (push article tomove)))
479
480       ;; now do the actual move
481       (when tomove
482         (dolist (article tomove)
483           (when spam-mark-ham-unread-before-move-from-spam-group
484             (gnus-summary-mark-article article gnus-unread-mark))           
485           (gnus-summary-set-process-mark article))
486         (if copy
487             (gnus-summary-copy-article nil group)
488           (gnus-summary-move-article nil group)))))
489   (gnus-summary-yank-process-mark))
490  
491 (defun spam-generic-register-routine (spam-func ham-func)
492   (let ((articles gnus-newsgroup-articles)
493         article mark ham-articles spam-articles)
494
495     (while articles
496       (setq article (pop articles)
497             mark (gnus-summary-article-mark article))
498       (cond ((spam-group-spam-mark-p gnus-newsgroup-name mark) 
499              (push article spam-articles))
500             ((memq article gnus-newsgroup-saved))
501             ((spam-group-ham-mark-p gnus-newsgroup-name mark)
502              (push article ham-articles))))
503
504     (when (and ham-articles ham-func)
505       (mapc ham-func ham-articles))     ; we use mapc because unlike
506                                         ; mapcar it discards the
507                                         ; return values
508     (when (and spam-articles spam-func)
509       (mapc spam-func spam-articles)))) ; we use mapc because unlike
510                                         ; mapcar it discards the
511                                         ; return values
512
513 (eval-and-compile
514   (defalias 'spam-point-at-eol (if (fboundp 'point-at-eol)
515                                    'point-at-eol
516                                  'line-end-position)))
517
518 (defun spam-get-article-as-string (article)
519   (let ((article-buffer (spam-get-article-as-buffer article))
520                         article-string)
521     (when article-buffer
522       (save-window-excursion
523         (set-buffer article-buffer)
524         (setq article-string (buffer-string))))
525   article-string))
526
527 (defun spam-get-article-as-buffer (article)
528   (let ((article-buffer))
529     (when (numberp article)
530       (save-window-excursion
531         (gnus-summary-goto-subject article)
532         (gnus-summary-show-article t)
533         (setq article-buffer (get-buffer gnus-article-buffer))))
534     article-buffer))
535
536 ;; disabled for now
537 ;; (defun spam-get-article-as-filename (article)
538 ;;   (let ((article-filename))
539 ;;     (when (numberp article)
540 ;;       (nnml-possibly-change-directory (gnus-group-real-name gnus-newsgroup-name))
541 ;;       (setq article-filename (expand-file-name (int-to-string article) nnml-current-directory)))
542 ;;     (if (file-exists-p article-filename)
543 ;;      article-filename
544 ;;       nil)))
545
546 (defun spam-fetch-field-from-fast (article)
547   "Fetch the `from' field quickly, using the internal gnus-data-list function"
548   (if (and (numberp article)
549            (assoc article (gnus-data-list nil)))
550       (mail-header-from (gnus-data-header (assoc article (gnus-data-list nil))))
551     nil))
552
553 (defun spam-fetch-field-subject-fast (article)
554   "Fetch the `subject' field quickly, using the internal gnus-data-list function"
555   (if (and (numberp article)
556            (assoc article (gnus-data-list nil)))
557       (mail-header-subject (gnus-data-header (assoc article (gnus-data-list nil))))
558     nil))
559
560 \f
561 ;;;; Spam determination.
562
563 (defvar spam-list-of-checks
564   '((spam-use-blacklist                 .       spam-check-blacklist)
565     (spam-use-regex-headers             .       spam-check-regex-headers)
566     (spam-use-whitelist                 .       spam-check-whitelist)
567     (spam-use-BBDB                      .       spam-check-BBDB)
568     (spam-use-ifile                     .       spam-check-ifile)
569     (spam-use-stat                      .       spam-check-stat)
570     (spam-use-blackholes                .       spam-check-blackholes)
571     (spam-use-hashcash                  .       spam-check-hashcash)
572     (spam-use-bogofilter-headers        .       spam-check-bogofilter-headers)
573     (spam-use-bogofilter                .       spam-check-bogofilter))
574 "The spam-list-of-checks list contains pairs associating a parameter
575 variable with a spam checking function.  If the parameter variable is
576 true, then the checking function is called, and its value decides what
577 happens.  Each individual check may return nil, t, or a mailgroup
578 name.  The value nil means that the check does not yield a decision,
579 and so, that further checks are needed.  The value t means that the
580 message is definitely not spam, and that further spam checks should be
581 inhibited.  Otherwise, a mailgroup name is returned where the mail
582 should go, and further checks are also inhibited.  The usual mailgroup
583 name is the value of `spam-split-group', meaning that the message is
584 definitely a spam.")
585
586 (defvar spam-list-of-statistical-checks
587   '(spam-use-ifile spam-use-stat spam-use-bogofilter)
588 "The spam-list-of-statistical-checks list contains all the mail
589 splitters that need to have the full message body available.")
590
591 (defun spam-split ()
592   "Split this message into the `spam' group if it is spam.
593 This function can be used as an entry in `nnmail-split-fancy', for
594 example like this: (: spam-split)
595
596 See the Info node `(gnus)Fancy Mail Splitting' for more details."
597   (interactive)
598   (save-excursion
599     (save-restriction
600       (dolist (check spam-list-of-statistical-checks)
601         (when (symbol-value check)
602           (widen)
603           (gnus-message 8 "spam-split: widening the buffer (%s requires it)"
604                         (symbol-name check))
605           (return)))
606       ;;   (progn (widen) (debug (buffer-string)))
607       (let ((list-of-checks spam-list-of-checks)
608             decision)
609         (while (and list-of-checks (not decision))
610           (let ((pair (pop list-of-checks)))
611             (when (symbol-value (car pair))
612               (gnus-message 5 "spam-split: calling the %s function" (symbol-name (cdr pair)))
613               (setq decision (funcall (cdr pair))))))
614         (if (eq decision t)
615             nil
616           decision)))))
617   
618 (defun spam-setup-widening ()
619   (dolist (check spam-list-of-statistical-checks)
620     (when (symbol-value check)
621       (setq nnimap-split-download-body-default t))))
622
623 (add-hook 'gnus-get-new-news-hook 'spam-setup-widening)
624
625 \f
626 ;;;; Regex headers
627
628 (defun spam-check-regex-headers ()
629   (let (ret found)
630     (dolist (h-regex spam-regex-headers-ham)
631       (unless found
632         (goto-char (point-min))
633         (when (re-search-forward h-regex nil t)
634           (message "Ham regex header search positive.")
635           (setq found t))))
636     (dolist (s-regex spam-regex-headers-spam)
637       (unless found
638         (goto-char (point-min))
639         (when (re-search-forward s-regex nil t)
640           (message "Spam regex header search positive." (match-string 1))
641           (setq found t)
642           (setq ret spam-split-group))))
643     ret))
644
645 \f
646 ;;;; Blackholes.
647
648 (defun spam-check-blackholes ()
649   "Check the Received headers for blackholed relays."
650   (let ((headers (message-fetch-field "received"))
651         ips matches)
652     (when headers
653       (with-temp-buffer
654         (insert headers)
655         (goto-char (point-min))
656         (gnus-message 5 "Checking headers for relay addresses")
657         (while (re-search-forward
658                 "\\[\\([0-9]+.[0-9]+.[0-9]+.[0-9]+\\)\\]" nil t)
659           (gnus-message 9 "Blackhole search found host IP %s." (match-string 1))
660           (push (mapconcat 'identity
661                            (nreverse (split-string (match-string 1) "\\."))
662                            ".")
663                 ips)))
664       (dolist (server spam-blackhole-servers)
665         (dolist (ip ips)
666           (unless (and spam-blackhole-good-server-regex
667                        (string-match spam-blackhole-good-server-regex ip))
668             (let ((query-string (concat ip "." server)))
669               (if spam-use-dig
670                   (let ((query-result (query-dig query-string)))
671                     (when query-result
672                       (gnus-message 5 "(DIG): positive blackhole check '%s'" 
673                                     query-result)
674                       (push (list ip server query-result)
675                             matches)))
676                 ;; else, if not using dig.el
677                 (when (query-dns query-string)
678                   (gnus-message 5 "positive blackhole check")
679                   (push (list ip server (query-dns query-string 'TXT))
680                         matches))))))))
681     (when matches
682       spam-split-group)))
683 \f
684 ;;;; Hashcash.
685
686 (condition-case nil
687     (progn
688       (require 'hashcash)
689       
690       (defun spam-check-hashcash ()
691         "Check the headers for hashcash payments."
692         (mail-check-payment)))          ;mail-check-payment returns a boolean
693
694   (file-error (progn
695                 (defalias 'mail-check-payment 'ignore)
696                 (defalias 'spam-check-hashcash 'ignore))))
697 \f
698 ;;;; BBDB 
699
700 ;;; original idea for spam-check-BBDB from Alexander Kotelnikov
701 ;;; <sacha@giotto.sj.ru>
702
703 ;; all this is done inside a condition-case to trap errors
704
705 (condition-case nil
706     (progn
707       (require 'bbdb)
708       (require 'bbdb-com)
709       
710   (defun spam-enter-ham-BBDB (from)
711     "Enter an address into the BBDB; implies ham (non-spam) sender"
712     (when (stringp from)
713       (let* ((parsed-address (gnus-extract-address-components from))
714              (name (or (car parsed-address) "Ham Sender"))
715              (net-address (car (cdr parsed-address))))
716         (gnus-message 5 "Adding address %s to BBDB" from)
717         (when (and net-address
718                    (not (bbdb-search-simple nil net-address)))
719           (bbdb-create-internal name nil net-address nil nil 
720                                 "ham sender added by spam.el")))))
721
722   (defun spam-BBDB-register-routine ()
723     (spam-generic-register-routine 
724      ;; spam function
725      nil
726      ;; ham function
727      (lambda (article)
728        (spam-enter-ham-BBDB (spam-fetch-field-from-fast article)))))
729
730   (defun spam-check-BBDB ()
731     "Mail from people in the BBDB is classified as ham or non-spam"
732     (let ((who (message-fetch-field "from")))
733       (when who
734         (setq who (cadr (gnus-extract-address-components who)))
735         (if (bbdb-search-simple nil who)
736             t 
737           (if spam-use-BBDB-exclusive
738               spam-split-group
739             nil))))))
740
741   (file-error (progn
742                 (defalias 'bbdb-search-simple 'ignore)
743                 (defalias 'spam-check-BBDB 'ignore)
744                 (defalias 'spam-BBDB-register-routine 'ignore)
745                 (defalias 'spam-enter-ham-BBDB 'ignore)
746                 (defalias 'bbdb-create-internal 'ignore)
747                 (defalias 'bbdb-records 'ignore))))
748
749 \f
750 ;;;; ifile
751
752 ;;; check the ifile backend; return nil if the mail was NOT classified
753 ;;; as spam
754
755 (defun spam-get-ifile-database-parameter ()
756   "Get the command-line parameter for ifile's database from spam-ifile-database-path."
757   (if spam-ifile-database-path
758       (format "--db-file=%s" spam-ifile-database-path)
759     nil))
760     
761 (defun spam-check-ifile ()
762   "Check the ifile backend for the classification of this message"
763   (let ((article-buffer-name (buffer-name)) 
764         category return)
765     (with-temp-buffer
766       (let ((temp-buffer-name (buffer-name))
767             (db-param (spam-get-ifile-database-parameter)))
768         (save-excursion
769           (set-buffer article-buffer-name)
770           (if db-param
771               (call-process-region (point-min) (point-max) spam-ifile-path
772                                    nil temp-buffer-name nil "-q" "-c" db-param)
773             (call-process-region (point-min) (point-max) spam-ifile-path
774                                  nil temp-buffer-name nil "-q" "-c")))
775         (goto-char (point-min))
776         (if (not (eobp))
777             (setq category (buffer-substring (point) (spam-point-at-eol))))
778         (when (not (zerop (length category))) ; we need a category here
779           (if spam-ifile-all-categories
780               (setq return category)
781             ;; else, if spam-ifile-all-categories is not set...
782             (when (string-equal spam-ifile-spam-category category)
783               (setq return spam-split-group))))))
784     return))
785
786 (defun spam-ifile-register-with-ifile (article-string category)
787   "Register an article, given as a string, with a category.
788 Uses `gnus-newsgroup-name' if category is nil (for ham registration)."
789   (when (stringp article-string)
790     (let ((category (or category gnus-newsgroup-name))
791           (db-param (spam-get-ifile-database-parameter)))
792       (with-temp-buffer
793         (insert article-string)
794         (if db-param
795             (call-process-region (point-min) (point-max) spam-ifile-path 
796                                  nil nil nil 
797                                  "-h" "-i" category db-param)
798           (call-process-region (point-min) (point-max) spam-ifile-path 
799                                nil nil nil 
800                                "-h" "-i" category))))))
801
802 (defun spam-ifile-register-spam-routine ()
803   (spam-generic-register-routine 
804    (lambda (article)
805      (spam-ifile-register-with-ifile 
806       (spam-get-article-as-string article) spam-ifile-spam-category))
807    nil))
808
809 (defun spam-ifile-register-ham-routine ()
810   (spam-generic-register-routine 
811    nil
812    (lambda (article)
813      (spam-ifile-register-with-ifile 
814       (spam-get-article-as-string article) spam-ifile-ham-category))))
815
816 \f
817 ;;;; spam-stat
818
819 (condition-case nil
820     (progn
821       (let ((spam-stat-install-hooks nil))
822         (require 'spam-stat))
823       
824       (defun spam-check-stat ()
825         "Check the spam-stat backend for the classification of this message"
826         (let ((spam-stat-split-fancy-spam-group spam-split-group) ; override
827               (spam-stat-buffer (buffer-name)) ; stat the current buffer
828               category return)
829           (spam-stat-split-fancy)))
830
831       (defun spam-stat-register-spam-routine ()
832         (spam-generic-register-routine 
833          (lambda (article)
834            (let ((article-string (spam-get-article-as-string article)))
835              (with-temp-buffer
836                (insert article-string)
837                (spam-stat-buffer-is-spam))))
838          nil))
839
840       (defun spam-stat-register-ham-routine ()
841         (spam-generic-register-routine 
842          nil
843          (lambda (article)
844            (let ((article-string (spam-get-article-as-string article)))
845              (with-temp-buffer
846                (insert article-string)
847                (spam-stat-buffer-is-non-spam))))))
848
849       (defun spam-maybe-spam-stat-load ()
850         (when spam-use-stat (spam-stat-load)))
851       
852       (defun spam-maybe-spam-stat-save ()
853         (when spam-use-stat (spam-stat-save)))
854
855       ;; Add hooks for loading and saving the spam stats
856       (add-hook 'gnus-save-newsrc-hook 'spam-maybe-spam-stat-save)
857       (add-hook 'gnus-get-top-new-news-hook 'spam-maybe-spam-stat-load)
858       (add-hook 'gnus-startup-hook 'spam-maybe-spam-stat-load))
859
860   (file-error (progn
861                 (defalias 'spam-stat-register-ham-routine 'ignore)
862                 (defalias 'spam-stat-register-spam-routine 'ignore)
863                 (defalias 'spam-stat-buffer-is-spam 'ignore)
864                 (defalias 'spam-stat-buffer-is-non-spam 'ignore)
865                 (defalias 'spam-stat-split-fancy 'ignore)
866                 (defalias 'spam-stat-load 'ignore)
867                 (defalias 'spam-stat-save 'ignore)
868                 (defalias 'spam-check-stat 'ignore))))
869
870 \f
871
872 ;;;; Blacklists and whitelists.
873
874 (defvar spam-whitelist-cache nil)
875 (defvar spam-blacklist-cache nil)
876
877 (defun spam-enter-whitelist (address)
878   "Enter ADDRESS into the whitelist."
879   (interactive "sAddress: ")
880   (spam-enter-list address spam-whitelist)
881   (setq spam-whitelist-cache nil))
882
883 (defun spam-enter-blacklist (address)
884   "Enter ADDRESS into the blacklist."
885   (interactive "sAddress: ")
886   (spam-enter-list address spam-blacklist)
887   (setq spam-blacklist-cache nil))
888
889 (defun spam-enter-list (address file)
890   "Enter ADDRESS into the given FILE, either the whitelist or the blacklist."
891   (unless (file-exists-p (file-name-directory file))
892     (make-directory (file-name-directory file) t))
893   (save-excursion
894     (set-buffer
895      (find-file-noselect file))
896     (goto-char (point-max))
897     (unless (bobp)
898       (insert "\n"))
899     (insert address "\n")
900     (save-buffer)))
901
902 ;;; returns t if the sender is in the whitelist, nil or spam-split-group otherwise
903 (defun spam-check-whitelist ()
904   ;; FIXME!  Should it detect when file timestamps change?
905   (unless spam-whitelist-cache
906     (setq spam-whitelist-cache (spam-parse-list spam-whitelist)))
907   (if (spam-from-listed-p spam-whitelist-cache) 
908       t
909     (if spam-use-whitelist-exclusive
910         spam-split-group
911       nil)))
912
913 (defun spam-check-blacklist ()
914   ;; FIXME!  Should it detect when file timestamps change?
915   (unless spam-blacklist-cache
916     (setq spam-blacklist-cache (spam-parse-list spam-blacklist)))
917   (and (spam-from-listed-p spam-blacklist-cache) spam-split-group))
918
919 (defun spam-parse-list (file)
920   (when (file-readable-p file)
921     (let (contents address)
922       (with-temp-buffer
923         (insert-file-contents file)
924         (while (not (eobp))
925           (setq address (buffer-substring (point) (spam-point-at-eol)))
926           (forward-line 1)
927           (unless (zerop (length address))
928             (setq address (regexp-quote address))
929             (while (string-match "\\\\\\*" address)
930               (setq address (replace-match ".*" t t address)))
931             (push address contents))))
932       (nreverse contents))))
933
934 (defun spam-from-listed-p (cache)
935   (let ((from (message-fetch-field "from"))
936         found)
937     (while cache
938       (when (string-match (pop cache) from)
939         (setq found t
940               cache nil)))
941     found))
942
943 (defun spam-blacklist-register-routine ()
944   (spam-generic-register-routine 
945    ;; the spam function
946    (lambda (article)
947      (let ((from (spam-fetch-field-from-fast article)))
948        (when (stringp from)
949            (spam-enter-blacklist from))))
950    ;; the ham function
951    nil))
952
953 (defun spam-whitelist-register-routine ()
954   (spam-generic-register-routine 
955    ;; the spam function
956    nil 
957    ;; the ham function
958    (lambda (article)
959      (let ((from (spam-fetch-field-from-fast article)))
960        (when (stringp from)
961            (spam-enter-whitelist from))))))
962
963 \f
964 ;;;; Bogofilter
965
966 (defun spam-check-bogofilter-headers (&optional score)
967   (let ((header (message-fetch-field spam-bogofilter-header)))
968       (when (and header
969                  (string-match spam-bogofilter-bogosity-positive-spam-header
970                                header))
971           (if score
972               (when (string-match "spamicity=\\([0-9.]+\\)" header)
973                 (match-string 1 header))
974             spam-split-group))))
975
976 ;; return something sensible if the score can't be determined
977 (defun spam-bogofilter-score ()
978   "Get the Bogofilter spamicity score"
979   (interactive)
980   (save-window-excursion
981     (gnus-summary-show-article t)
982     (set-buffer gnus-article-buffer)
983     (let ((score (or (spam-check-bogofilter-headers t)
984                      (spam-check-bogofilter t))))
985       (message "Spamicity score %s" score)
986       (or score "0"))))
987
988 (defun spam-check-bogofilter (&optional score)
989   "Check the Bogofilter backend for the classification of this message"
990   (let ((article-buffer-name (buffer-name)) 
991         return)
992     (with-temp-buffer
993       (let ((temp-buffer-name (buffer-name)))
994         (save-excursion
995           (set-buffer article-buffer-name)
996           (if spam-bogofilter-database-directory
997               (call-process-region (point-min) (point-max) 
998                                    spam-bogofilter-path
999                                    nil temp-buffer-name nil "-v"
1000                                    "-d" spam-bogofilter-database-directory)
1001             (call-process-region (point-min) (point-max) spam-bogofilter-path
1002                                  nil temp-buffer-name nil "-v")))
1003         (setq return (spam-check-bogofilter-headers score))))
1004     return))
1005
1006 (defun spam-bogofilter-register-with-bogofilter (article-string spam)
1007   "Register an article, given as a string, as spam or non-spam."
1008   (when (stringp article-string)
1009     (let ((switch (if spam spam-bogofilter-spam-switch 
1010                     spam-bogofilter-ham-switch)))
1011       (with-temp-buffer
1012         (insert article-string)
1013         (if spam-bogofilter-database-directory
1014             (call-process-region (point-min) (point-max) 
1015                                  spam-bogofilter-path
1016                                  nil nil nil "-v" switch
1017                                  "-d" spam-bogofilter-database-directory)
1018           (call-process-region (point-min) (point-max) spam-bogofilter-path
1019                                nil nil nil "-v" switch))))))
1020
1021 (defun spam-bogofilter-register-spam-routine ()
1022   (spam-generic-register-routine 
1023    (lambda (article)
1024      (spam-bogofilter-register-with-bogofilter
1025       (spam-get-article-as-string article) t))
1026    nil))
1027
1028 (defun spam-bogofilter-register-ham-routine ()
1029   (spam-generic-register-routine 
1030    nil
1031    (lambda (article)
1032      (spam-bogofilter-register-with-bogofilter
1033       (spam-get-article-as-string article) nil))))
1034
1035 (provide 'spam)
1036
1037 ;;; spam.el ends here.