ffecadfdf886fa6c27d88258c31e4c8394ba8f20
[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 '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-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-spam-contents-p (group)
294   (if (stringp group)
295       (or (member group spam-junk-mailgroups)
296           (memq 'gnus-group-spam-classification-spam 
297                 (gnus-parameter-spam-contents group)))
298     nil))
299   
300 (defun spam-group-ham-contents-p (group)
301   (if (stringp group)
302       (memq 'gnus-group-spam-classification-ham 
303             (gnus-parameter-spam-contents group))
304     nil))
305
306 (defun spam-group-processor-p (group processor)
307   (if (and (stringp group)
308            (symbolp processor))
309       (member processor (car (gnus-parameter-spam-process group)))
310     nil))
311
312 (defun spam-group-spam-processor-bogofilter-p (group)
313   (spam-group-processor-p group 'gnus-group-spam-exit-processor-bogofilter))
314
315 (defun spam-group-spam-processor-blacklist-p (group)
316   (spam-group-processor-p group 'gnus-group-spam-exit-processor-blacklist))
317
318 (defun spam-group-spam-processor-ifile-p (group)
319   (spam-group-processor-p group 'gnus-group-spam-exit-processor-ifile))
320
321 (defun spam-group-ham-processor-ifile-p (group)
322   (spam-group-processor-p group 'gnus-group-ham-exit-processor-ifile))
323
324 (defun spam-group-ham-processor-bogofilter-p (group)
325   (spam-group-processor-p group 'gnus-group-ham-exit-processor-bogofilter))
326
327 (defun spam-group-spam-processor-stat-p (group)
328   (spam-group-processor-p group 'gnus-group-spam-exit-processor-stat))
329
330 (defun spam-group-ham-processor-stat-p (group)
331   (spam-group-processor-p group 'gnus-group-ham-exit-processor-stat))
332
333 (defun spam-group-ham-processor-whitelist-p (group)
334   (spam-group-processor-p group 'gnus-group-ham-exit-processor-whitelist))
335
336 (defun spam-group-ham-processor-BBDB-p (group)
337   (spam-group-processor-p group 'gnus-group-ham-exit-processor-BBDB))
338
339 ;;; Summary entry and exit processing.
340
341 (defun spam-summary-prepare ()
342   (spam-mark-junk-as-spam-routine))
343
344 (add-hook 'gnus-summary-prepare-hook 'spam-summary-prepare)
345
346 (defun spam-summary-prepare-exit ()
347   ;; The spam processors are invoked for any group, spam or ham or neither
348   (gnus-message 6 "Exiting summary buffer and applying spam rules")
349   (when (and spam-bogofilter-path
350              (spam-group-spam-processor-bogofilter-p gnus-newsgroup-name))
351     (gnus-message 5 "Registering spam with bogofilter")
352     (spam-bogofilter-register-spam-routine))
353   
354   (when (and spam-ifile-path
355              (spam-group-spam-processor-ifile-p gnus-newsgroup-name))
356     (gnus-message 5 "Registering spam with ifile")
357     (spam-ifile-register-spam-routine))
358   
359   (when (spam-group-spam-processor-stat-p gnus-newsgroup-name)
360     (gnus-message 5 "Registering spam with spam-stat")
361     (spam-stat-register-spam-routine))
362
363   (when (spam-group-spam-processor-blacklist-p gnus-newsgroup-name)
364     (gnus-message 5 "Registering spam with the blacklist")
365     (spam-blacklist-register-routine))
366
367   (if spam-move-spam-nonspam-groups-only      
368       (when (not (spam-group-spam-contents-p gnus-newsgroup-name))
369         (spam-mark-spam-as-expired-and-move-routine
370          (gnus-parameter-spam-process-destination gnus-newsgroup-name)))
371     (gnus-message 5 "Marking spam as expired and moving it")
372     (spam-mark-spam-as-expired-and-move-routine 
373      (gnus-parameter-spam-process-destination gnus-newsgroup-name)))
374
375   ;; now we redo spam-mark-spam-as-expired-and-move-routine to only
376   ;; expire spam, in case the above did not expire them
377   (spam-mark-spam-as-expired-and-move-routine nil)
378
379   (when (spam-group-ham-contents-p gnus-newsgroup-name)
380     (when (spam-group-ham-processor-whitelist-p gnus-newsgroup-name)
381       (gnus-message 5 "Registering ham with the whitelist")
382       (spam-whitelist-register-routine))
383     (when (spam-group-ham-processor-ifile-p gnus-newsgroup-name)
384       (gnus-message 5 "Registering ham with ifile")
385       (spam-ifile-register-ham-routine))
386     (when (spam-group-ham-processor-bogofilter-p gnus-newsgroup-name)
387       (gnus-message 5 "Registering ham with Bogofilter")
388       (spam-bogofilter-register-ham-routine))
389     (when (spam-group-ham-processor-stat-p gnus-newsgroup-name)
390       (gnus-message 5 "Registering ham with spam-stat")
391       (spam-stat-register-ham-routine))
392     (when (spam-group-ham-processor-BBDB-p gnus-newsgroup-name)
393       (gnus-message 5 "Registering ham with the BBDB")
394       (spam-BBDB-register-routine)))
395
396   ;; now move all ham articles out of spam groups
397   (when (spam-group-spam-contents-p gnus-newsgroup-name)
398     (gnus-message 5 "Moving ham messages from spam group")
399     (spam-ham-move-routine
400      (gnus-parameter-ham-process-destination gnus-newsgroup-name))))
401
402 (add-hook 'gnus-summary-prepare-exit-hook 'spam-summary-prepare-exit)
403
404 (defun spam-mark-junk-as-spam-routine ()
405   ;; check the global list of group names spam-junk-mailgroups and the
406   ;; group parameters
407   (when (spam-group-spam-contents-p gnus-newsgroup-name)
408     (gnus-message 5 "Marking unread articles as spam")
409     (let ((articles gnus-newsgroup-articles)
410           article)
411       (while articles
412         (setq article (pop articles))
413         (when (eq (gnus-summary-article-mark article) gnus-unread-mark)
414           (gnus-summary-mark-article article gnus-spam-mark))))))
415
416 (defun spam-mark-spam-as-expired-and-move-routine (&optional group)
417   (let ((articles gnus-newsgroup-articles)
418         article)
419     (while articles
420       (setq article (pop articles))
421       (when (eq (gnus-summary-article-mark article) gnus-spam-mark)
422         (gnus-summary-mark-article article gnus-expirable-mark)
423         (when (stringp group)
424           (let ((gnus-current-article article))
425             (gnus-summary-move-article nil group)))))))
426  
427 (defun spam-ham-move-routine (&optional group)
428   (let ((articles gnus-newsgroup-articles)
429         article ham-mark-values mark)
430
431     (dolist (mark spam-ham-marks)
432       (push (symbol-value mark) ham-mark-values))
433     
434     (dolist (article articles)
435       (when (and (memq (gnus-summary-article-mark article) ham-mark-values)
436                  (stringp group))
437         (let ((gnus-current-article article))
438           (gnus-summary-move-article nil group))))))
439  
440 (defun spam-generic-register-routine (spam-func ham-func)
441   (let ((articles gnus-newsgroup-articles)
442         article mark ham-articles spam-articles spam-mark-values 
443         ham-mark-values)
444
445     ;; marks are stored as symbolic values, so we have to dereference
446     ;; them for memq to work.  we wouldn't have to do this if
447     ;; gnus-summary-article-mark returned a symbol.
448     (dolist (mark spam-ham-marks)
449       (push (symbol-value mark) ham-mark-values))
450
451     (dolist (mark spam-spam-marks)
452       (push (symbol-value mark) spam-mark-values))
453
454     (while articles
455       (setq article (pop articles)
456             mark (gnus-summary-article-mark article))
457       (cond ((memq mark spam-mark-values) (push article spam-articles))
458             ((memq article gnus-newsgroup-saved))
459             ((memq mark ham-mark-values) (push article ham-articles))))
460     (when (and ham-articles ham-func)
461       (mapc ham-func ham-articles))     ; we use mapc because unlike
462                                         ; mapcar it discards the
463                                         ; return values
464     (when (and spam-articles spam-func)
465       (mapc spam-func spam-articles)))) ; we use mapc because unlike
466                                         ; mapcar it discards the
467                                         ; return values
468
469 (eval-and-compile
470   (defalias 'spam-point-at-eol (if (fboundp 'point-at-eol)
471                                    'point-at-eol
472                                  'line-end-position)))
473
474 (defun spam-get-article-as-string (article)
475   (let ((article-buffer (spam-get-article-as-buffer article))
476                         article-string)
477     (when article-buffer
478       (save-window-excursion
479         (set-buffer article-buffer)
480         (setq article-string (buffer-string))))
481   article-string))
482
483 (defun spam-get-article-as-buffer (article)
484   (let ((article-buffer))
485     (when (numberp article)
486       (save-window-excursion
487         (gnus-summary-goto-subject article)
488         (gnus-summary-show-article t)
489         (setq article-buffer (get-buffer gnus-article-buffer))))
490     article-buffer))
491
492 (defun spam-get-article-as-filename (article)
493   (let ((article-filename))
494     (when (numberp article)
495       (nnml-possibly-change-directory (gnus-group-real-name gnus-newsgroup-name))
496       (setq article-filename (expand-file-name (int-to-string article) nnml-current-directory)))
497     (if (file-exists-p article-filename)
498         article-filename
499       nil)))
500
501 (defun spam-fetch-field-from-fast (article)
502   "Fetch the `from' field quickly, using the internal gnus-data-list function"
503   (if (and (numberp article)
504            (assoc article (gnus-data-list nil)))
505       (mail-header-from (gnus-data-header (assoc article (gnus-data-list nil))))
506     nil))
507
508 (defun spam-fetch-field-subject-fast (article)
509   "Fetch the `subject' field quickly, using the internal gnus-data-list function"
510   (if (and (numberp article)
511            (assoc article (gnus-data-list nil)))
512       (mail-header-subject (gnus-data-header (assoc article (gnus-data-list nil))))
513     nil))
514
515 \f
516 ;;;; Spam determination.
517
518 (defvar spam-list-of-checks
519   '((spam-use-blacklist                 .       spam-check-blacklist)
520     (spam-use-regex-headers             .       spam-check-regex-headers)
521     (spam-use-whitelist                 .       spam-check-whitelist)
522     (spam-use-BBDB                      .       spam-check-BBDB)
523     (spam-use-ifile                     .       spam-check-ifile)
524     (spam-use-stat                      .       spam-check-stat)
525     (spam-use-blackholes                .       spam-check-blackholes)
526     (spam-use-bogofilter-headers        .       spam-check-bogofilter-headers)
527     (spam-use-bogofilter                .       spam-check-bogofilter))
528 "The spam-list-of-checks list contains pairs associating a parameter
529 variable with a spam checking function.  If the parameter variable is
530 true, then the checking function is called, and its value decides what
531 happens.  Each individual check may return nil, t, or a mailgroup
532 name.  The value nil means that the check does not yield a decision,
533 and so, that further checks are needed.  The value t means that the
534 message is definitely not spam, and that further spam checks should be
535 inhibited.  Otherwise, a mailgroup name is returned where the mail
536 should go, and further checks are also inhibited.  The usual mailgroup
537 name is the value of `spam-split-group', meaning that the message is
538 definitely a spam.")
539
540 (defun spam-split ()
541   "Split this message into the `spam' group if it is spam.
542 This function can be used as an entry in `nnmail-split-fancy', for
543 example like this: (: spam-split)
544
545 See the Info node `(gnus)Fancy Mail Splitting' for more details."
546   (interactive)
547   
548   ;; load the spam-stat tables if needed
549   (when spam-use-stat (spam-stat-load))
550
551   (let ((list-of-checks spam-list-of-checks)
552         decision)
553     (while (and list-of-checks (not decision))
554       (let ((pair (pop list-of-checks)))
555         (when (symbol-value (car pair))
556           (gnus-message 5 "spam-split: calling the %s function" (symbol-name (cdr pair)))
557           (setq decision (funcall (cdr pair))))))
558     (if (eq decision t)
559         nil
560       decision)))
561 \f
562 ;;;; Regex headers
563
564 (defun spam-check-regex-headers ()
565   (let (ret found)
566     (dolist (h-regex spam-regex-headers-ham)
567       (unless found
568         (goto-char (point-min))
569         (when (re-search-forward h-regex nil t)
570           (message "Ham regex header search positive.")
571           (setq found t))))
572     (dolist (s-regex spam-regex-headers-spam)
573       (unless found
574         (goto-char (point-min))
575         (when (re-search-forward s-regex nil t)
576           (message "Spam regex header search positive." (match-string 1))
577           (setq found t)
578           (setq ret spam-split-group))))
579     ret))
580
581 \f
582 ;;;; Blackholes.
583
584 (defun spam-check-blackholes ()
585   "Check the Received headers for blackholed relays."
586   (let ((headers (message-fetch-field "received"))
587         ips matches)
588     (when headers
589       (with-temp-buffer
590         (insert headers)
591         (goto-char (point-min))
592         (gnus-message 5 "Checking headers for relay addresses")
593         (while (re-search-forward
594                 "\\[\\([0-9]+.[0-9]+.[0-9]+.[0-9]+\\)\\]" nil t)
595           (gnus-message 9 "Blackhole search found host IP %s." (match-string 1))
596           (push (mapconcat 'identity
597                            (nreverse (split-string (match-string 1) "\\."))
598                            ".")
599                 ips)))
600       (dolist (server spam-blackhole-servers)
601         (dolist (ip ips)
602           (unless (and spam-blackhole-good-server-regex
603                        (string-match spam-blackhole-good-server-regex ip))
604             (let ((query-string (concat ip "." server)))
605               (if spam-use-dig
606                   (let ((query-result (query-dig query-string)))
607                     (when query-result
608                       (gnus-message 5 "(DIG): positive blackhole check '%s'" query-result)
609                       (push (list ip server query-result)
610                             matches)))
611                 ;; else, if not using dig.el
612                 (when (query-dns query-string)
613                   (gnus-message 5 "positive blackhole check")
614                   (push (list ip server (query-dns query-string 'TXT))
615                         matches))))))))
616     (when matches
617       spam-split-group)))
618 \f
619 ;;;; BBDB 
620
621 ;;; original idea for spam-check-BBDB from Alexander Kotelnikov
622 ;;; <sacha@giotto.sj.ru>
623
624 ;; all this is done inside a condition-case to trap errors
625
626 (condition-case nil
627     (progn
628       (require 'bbdb)
629       (require 'bbdb-com)
630       
631   (defun spam-enter-ham-BBDB (from)
632     "Enter an address into the BBDB; implies ham (non-spam) sender"
633     (when (stringp from)
634       (let* ((parsed-address (gnus-extract-address-components from))
635              (name (or (car parsed-address) "Ham Sender"))
636              (net-address (car (cdr parsed-address))))
637         (gnus-message 5 "Adding address %s to BBDB" from)
638         (when (and net-address
639                    (not (bbdb-search-simple nil net-address)))
640           (bbdb-create-internal name nil net-address nil nil 
641                                 "ham sender added by spam.el")))))
642
643   (defun spam-BBDB-register-routine ()
644     (spam-generic-register-routine 
645      ;; spam function
646      nil
647      ;; ham function
648      (lambda (article)
649        (spam-enter-ham-BBDB (spam-fetch-field-from-fast article)))))
650
651   (defun spam-check-BBDB ()
652     "Mail from people in the BBDB is classified as ham or non-spam"
653     (let ((who (message-fetch-field "from")))
654       (when who
655         (setq who (cadr (gnus-extract-address-components who)))
656         (if (bbdb-search-simple nil who)
657             t 
658           (if spam-use-BBDB-exclusive
659               spam-split-group
660             nil))))))
661
662   (file-error (progn
663                 (defalias 'bbdb-search-simple 'ignore)
664                 (defalias 'spam-check-BBDB 'ignore)
665                 (defalias 'spam-BBDB-register-routine 'ignore)
666                 (defalias 'spam-enter-ham-BBDB 'ignore)
667                 (defalias 'bbdb-create-internal 'ignore)
668                 (defalias 'bbdb-records 'ignore))))
669
670 \f
671 ;;;; ifile
672
673 ;;; check the ifile backend; return nil if the mail was NOT classified
674 ;;; as spam
675
676 (defun spam-get-ifile-database-parameter ()
677   "Get the command-line parameter for ifile's database from spam-ifile-database-path."
678   (if spam-ifile-database-path
679       (format "--db-file=%s" spam-ifile-database-path)
680     nil))
681     
682 (defun spam-check-ifile ()
683   "Check the ifile backend for the classification of this message"
684   (let ((article-buffer-name (buffer-name)) 
685         category return)
686     (with-temp-buffer
687       (let ((temp-buffer-name (buffer-name))
688             (db-param (spam-get-ifile-database-parameter)))
689         (save-excursion
690           (set-buffer article-buffer-name)
691           (if db-param
692               (call-process-region (point-min) (point-max) spam-ifile-path
693                                    nil temp-buffer-name nil "-q" "-c" db-param)
694             (call-process-region (point-min) (point-max) spam-ifile-path
695                                  nil temp-buffer-name nil "-q" "-c")))
696         (goto-char (point-min))
697         (if (not (eobp))
698             (setq category (buffer-substring (point) (spam-point-at-eol))))
699         (when (not (zerop (length category))) ; we need a category here
700           (if spam-ifile-all-categories
701               (setq return category)
702             ;; else, if spam-ifile-all-categories is not set...
703             (when (string-equal spam-ifile-spam-category category)
704               (setq return spam-split-group))))))
705     return))
706
707 (defun spam-ifile-register-with-ifile (article-string category)
708   "Register an article, given as a string, with a category.
709 Uses `gnus-newsgroup-name' if category is nil (for ham registration)."
710   (when (stringp article-string)
711     (let ((category (or category gnus-newsgroup-name))
712           (db-param (spam-get-ifile-database-parameter)))
713       (with-temp-buffer
714         (insert-string article-string)
715         (if db-param
716             (call-process-region (point-min) (point-max) spam-ifile-path 
717                                  nil nil nil 
718                                  "-h" "-i" category db-param)
719           (call-process-region (point-min) (point-max) spam-ifile-path 
720                                nil nil nil 
721                                "-h" "-i" category))))))
722
723 (defun spam-ifile-register-spam-routine ()
724   (spam-generic-register-routine 
725    (lambda (article)
726      (spam-ifile-register-with-ifile 
727       (spam-get-article-as-string article) spam-ifile-spam-category))
728    nil))
729
730 (defun spam-ifile-register-ham-routine ()
731   (spam-generic-register-routine 
732    nil
733    (lambda (article)
734      (spam-ifile-register-with-ifile 
735       (spam-get-article-as-string article) spam-ifile-ham-category))))
736
737 \f
738 ;;;; spam-stat
739
740 (condition-case nil
741     (progn
742       (let ((spam-stat-install-hooks nil))
743         (require 'spam-stat))
744       
745       (defun spam-check-stat ()
746         "Check the spam-stat backend for the classification of this message"
747         (let ((spam-stat-split-fancy-spam-group spam-split-group) ; override
748               (spam-stat-buffer (buffer-name)) ; stat the current buffer
749               category return)
750           (spam-stat-split-fancy)))
751
752       (defun spam-stat-register-spam-routine ()
753         (spam-generic-register-routine 
754          (lambda (article)
755            (let ((article-string (spam-get-article-as-string article)))
756              (with-temp-buffer
757                (insert-string article-string)
758                (spam-stat-buffer-is-spam))))
759          nil)
760         (spam-stat-save))
761
762       (defun spam-stat-register-ham-routine ()
763         (spam-generic-register-routine 
764          nil
765          (lambda (article)
766            (let ((article-string (spam-get-article-as-string article)))
767              (with-temp-buffer
768                (insert-string article-string)
769                (spam-stat-buffer-is-non-spam)))))
770         (spam-stat-save)))
771
772   (file-error (progn
773                 (defalias 'spam-stat-register-ham-routine 'ignore)
774                 (defalias 'spam-stat-register-spam-routine 'ignore)
775                 (defalias 'spam-stat-buffer-is-spam 'ignore)
776                 (defalias 'spam-stat-buffer-is-non-spam 'ignore)
777                 (defalias 'spam-stat-split-fancy 'ignore)
778                 (defalias 'spam-stat-load 'ignore)
779                 (defalias 'spam-stat-save 'ignore)
780                 (defalias 'spam-check-stat 'ignore))))
781
782 \f
783
784 ;;;; Blacklists and whitelists.
785
786 (defvar spam-whitelist-cache nil)
787 (defvar spam-blacklist-cache nil)
788
789 (defun spam-enter-whitelist (address)
790   "Enter ADDRESS into the whitelist."
791   (interactive "sAddress: ")
792   (spam-enter-list address spam-whitelist)
793   (setq spam-whitelist-cache nil))
794
795 (defun spam-enter-blacklist (address)
796   "Enter ADDRESS into the blacklist."
797   (interactive "sAddress: ")
798   (spam-enter-list address spam-blacklist)
799   (setq spam-blacklist-cache nil))
800
801 (defun spam-enter-list (address file)
802   "Enter ADDRESS into the given FILE, either the whitelist or the blacklist."
803   (unless (file-exists-p (file-name-directory file))
804     (make-directory (file-name-directory file) t))
805   (save-excursion
806     (set-buffer
807      (find-file-noselect file))
808     (goto-char (point-max))
809     (unless (bobp)
810       (insert "\n"))
811     (insert address "\n")
812     (save-buffer)))
813
814 ;;; returns t if the sender is in the whitelist, nil or spam-split-group otherwise
815 (defun spam-check-whitelist ()
816   ;; FIXME!  Should it detect when file timestamps change?
817   (unless spam-whitelist-cache
818     (setq spam-whitelist-cache (spam-parse-list spam-whitelist)))
819   (if (spam-from-listed-p spam-whitelist-cache) 
820       t
821     (if spam-use-whitelist-exclusive
822         spam-split-group
823       nil)))
824
825 (defun spam-check-blacklist ()
826   ;; FIXME!  Should it detect when file timestamps change?
827   (unless spam-blacklist-cache
828     (setq spam-blacklist-cache (spam-parse-list spam-blacklist)))
829   (and (spam-from-listed-p spam-blacklist-cache) spam-split-group))
830
831 (defun spam-parse-list (file)
832   (when (file-readable-p file)
833     (let (contents address)
834       (with-temp-buffer
835         (insert-file-contents file)
836         (while (not (eobp))
837           (setq address (buffer-substring (point) (spam-point-at-eol)))
838           (forward-line 1)
839           (unless (zerop (length address))
840             (setq address (regexp-quote address))
841             (while (string-match "\\\\\\*" address)
842               (setq address (replace-match ".*" t t address)))
843             (push address contents))))
844       (nreverse contents))))
845
846 (defun spam-from-listed-p (cache)
847   (let ((from (message-fetch-field "from"))
848         found)
849     (while cache
850       (when (string-match (pop cache) from)
851         (setq found t
852               cache nil)))
853     found))
854
855 (defun spam-blacklist-register-routine ()
856   (spam-generic-register-routine 
857    ;; the spam function
858    (lambda (article)
859      (let ((from (spam-fetch-field-from-fast article)))
860        (when (stringp from)
861            (spam-enter-blacklist from))))
862    ;; the ham function
863    nil))
864
865 (defun spam-whitelist-register-routine ()
866   (spam-generic-register-routine 
867    ;; the spam function
868    nil 
869    ;; the ham function
870    (lambda (article)
871      (let ((from (spam-fetch-field-from-fast article)))
872        (when (stringp from)
873            (spam-enter-whitelist from))))))
874
875 \f
876 ;;;; Bogofilter
877
878 (defun spam-check-bogofilter-headers (&optional score)
879   (let ((header (message-fetch-field spam-bogofilter-header)))
880       (when (and header
881                  (string-match spam-bogofilter-bogosity-positive-spam-header
882                                header))
883           (if score
884               (when (string-match "spamicity=\\([0-9.]+\\)" header)
885                 (match-string 1 header))
886             spam-split-group))))
887
888 ;; return something sensible if the score can't be determined
889 (defun spam-bogofilter-score ()
890   "Get the Bogofilter spamicity score"
891   (interactive)
892   (save-window-excursion
893     (gnus-summary-show-article t)
894     (set-buffer gnus-article-buffer)
895     (let ((score (spam-check-bogofilter t)))
896       (message "Spamicity score %s" score)
897       (or score "0"))))
898
899 (defun spam-check-bogofilter (&optional score)
900   "Check the Bogofilter backend for the classification of this message"
901   (let ((article-buffer-name (buffer-name)) 
902         return)
903     (with-temp-buffer
904       (let ((temp-buffer-name (buffer-name)))
905         (save-excursion
906           (set-buffer article-buffer-name)
907           (if spam-bogofilter-database-directory
908               (call-process-region (point-min) (point-max) 
909                                    spam-bogofilter-path
910                                    nil temp-buffer-name nil "-v"
911                                    "-d" spam-bogofilter-database-directory)
912             (call-process-region (point-min) (point-max) spam-bogofilter-path
913                                  nil temp-buffer-name nil "-v")))
914         (setq return (spam-check-bogofilter-headers score))))
915     return))
916
917 (defun spam-bogofilter-register-with-bogofilter (article-string spam)
918   "Register an article, given as a string, as spam or non-spam."
919   (when (stringp article-string)
920     (let ((switch (if spam "-s" "-n")))
921       (with-temp-buffer
922         (insert-string article-string)
923         (if spam-bogofilter-database-directory
924             (call-process-region (point-min) (point-max) 
925                                  spam-bogofilter-path
926                                  nil nil nil "-v" switch
927                                  "-d" spam-bogofilter-database-directory)
928           (call-process-region (point-min) (point-max) spam-bogofilter-path
929                                nil nil nil "-v" switch))))))
930
931 (defun spam-bogofilter-register-spam-routine ()
932   (spam-generic-register-routine 
933    (lambda (article)
934      (spam-bogofilter-register-with-bogofilter
935       (spam-get-article-as-string article) t))
936    nil))
937
938 (defun spam-bogofilter-register-ham-routine ()
939   (spam-generic-register-routine 
940    nil
941    (lambda (article)
942      (spam-bogofilter-register-with-bogofilter
943       (spam-get-article-as-string article) nil))))
944
945 (provide 'spam)
946
947 ;;; spam.el ends here.