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