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