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