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