Merge from emacs--devo--0
[gnus] / lisp / hashcash.el
1 ;;; hashcash.el --- Add hashcash payments to email
2
3 ;; Copyright (C) 2003, 2004, 2005, 2007, 2008  Free Software Foundation
4
5 ;; Written by: Paul Foley <mycroft@actrix.gen.nz> (1997-2002)
6 ;; Maintainer: Paul Foley <mycroft@actrix.gen.nz>
7 ;; Keywords: mail, hashcash
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; The hashcash binary is at http://www.hashcash.org/.
27 ;;
28 ;; Call mail-add-payment to add a hashcash payment to a mail message
29 ;; in the current buffer.
30 ;;
31 ;; Call mail-add-payment-async after writing the addresses but before
32 ;; writing the mail to start calculating the hashcash payment
33 ;; asynchronously.
34 ;;
35 ;; The easiest way to do this automatically for all outgoing mail
36 ;; is to set `message-generate-hashcash' to t.  If you want more
37 ;; control, try the following hooks.
38 ;;
39 ;; To automatically add payments to all outgoing mail when sending:
40 ;;    (add-hook 'message-send-hook 'mail-add-payment)
41 ;;
42 ;; To start calculations automatically when addresses are prefilled:
43 ;;    (add-hook 'message-setup-hook 'mail-add-payment-async)
44 ;;
45 ;; To check whether calculations are done before sending:
46 ;;    (add-hook 'message-send-hook 'hashcash-wait-or-cancel)
47
48 ;;; Code:
49
50 (eval-and-compile
51   (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
52
53 (defgroup hashcash nil
54   "Hashcash configuration."
55   :group 'mail)
56
57 (defcustom hashcash-default-payment 20
58   "*The default number of bits to pay to unknown users.
59 If this is zero, no payment header will be generated.
60 See `hashcash-payment-alist'."
61   :type 'integer
62   :group 'hashcash)
63
64 (defcustom hashcash-payment-alist '()
65   "*An association list mapping email addresses to payment amounts.
66 Elements may consist of (ADDR AMOUNT) or (ADDR STRING AMOUNT), where
67 ADDR is the email address of the intended recipient and AMOUNT is
68 the value of hashcash payment to be made to that user.  STRING, if
69 present, is the string to be hashed; if not present ADDR will be used."
70   :type '(repeat (choice (list :tag "Normal"
71                                (string :name "Address")
72                                (integer :name "Amount"))
73                          (list :tag "Replace hash input"
74                                (string :name "Address")
75                                (string :name "Hash input")
76                                (integer :name "Amount"))))
77   :group 'hashcash)
78
79 (defcustom hashcash-default-accept-payment 20
80   "*The default minimum number of bits to accept on incoming payments."
81   :type 'integer
82   :group 'hashcash)
83
84 (defcustom hashcash-accept-resources `((,user-mail-address nil))
85   "*An association list mapping hashcash resources to payment amounts.
86 Resources named here are to be accepted in incoming payments.  If the
87 corresponding AMOUNT is NIL, the value of `hashcash-default-accept-payment'
88 is used instead."
89   :group 'hashcash)
90
91 (defcustom hashcash-path (executable-find "hashcash")
92   "*The path to the hashcash binary."
93   :group 'hashcash)
94
95 (defcustom hashcash-extra-generate-parameters nil
96   "*A list of parameter strings passed to `hashcash-path' when minting.
97 For example, you may want to set this to '(\"-Z2\") to reduce header length."
98   :type '(repeat string)
99   :group 'hashcash)
100
101 (defcustom hashcash-double-spend-database "hashcash.db"
102   "*The path to the double-spending database."
103   :group 'hashcash)
104
105 (defcustom hashcash-in-news nil
106   "*Specifies whether or not hashcash payments should be made to newsgroups."
107   :type 'boolean
108   :group 'hashcash)
109
110 (defvar hashcash-process-alist nil
111   "Alist of asynchronous hashcash processes and buffers.")
112
113 (require 'mail-utils)
114
115 (eval-and-compile
116   (unless (fboundp 'declare-function) (defmacro declare-function (&rest r)))
117
118   (if (fboundp 'point-at-bol)
119       (defalias 'hashcash-point-at-bol 'point-at-bol)
120     (defalias 'hashcash-point-at-bol 'line-beginning-position))
121
122   (if (fboundp 'point-at-eol)
123       (defalias 'hashcash-point-at-eol 'point-at-eol)
124     (defalias 'hashcash-point-at-eol 'line-end-position)))
125
126 (defun hashcash-strip-quoted-names (addr)
127   (setq addr (mail-strip-quoted-names addr))
128   (if (and addr (string-match "\\`\\([^+@]+\\)\\+[^@]*\\(@.+\\)" addr))
129       (concat (match-string 1 addr) (match-string 2 addr))
130     addr))
131
132 (declare-function  message-narrow-to-headers-or-head "message" ())
133 (declare-function  message-fetch-field "message" (header &optional not-all))
134 (declare-function  message-goto-eoh "message" ())
135 (declare-function  message-narrow-to-headers "message" ())
136
137 (defun hashcash-token-substring ()
138   (save-excursion
139     (let ((token ""))
140       (loop
141         (setq token
142           (concat token (buffer-substring (point) (hashcash-point-at-eol))))
143         (goto-char (hashcash-point-at-eol))
144         (forward-char 1)
145         (unless (looking-at "[ \t]") (return token))
146         (while (looking-at "[ \t]") (forward-char 1))))))
147
148 (defun hashcash-payment-required (addr)
149   "Return the hashcash payment value required for the given address."
150   (let ((val (assoc addr hashcash-payment-alist)))
151     (or (nth 2 val) (nth 1 val) hashcash-default-payment)))
152
153 (defun hashcash-payment-to (addr)
154   "Return the string with which hashcash payments should collide."
155   (let ((val (assoc addr hashcash-payment-alist)))
156     (or (nth 1 val) (nth 0 val) addr)))
157
158 (defun hashcash-generate-payment (str val)
159   "Generate a hashcash payment by finding a VAL-bit collison on STR."
160   (if (and (> val 0)
161            hashcash-path)
162       (save-excursion
163         (set-buffer (get-buffer-create " *hashcash*"))
164         (erase-buffer)
165         (apply 'call-process hashcash-path nil t nil
166                "-m" "-q" "-b" (number-to-string val) str
167                hashcash-extra-generate-parameters)
168         (goto-char (point-min))
169         (hashcash-token-substring))
170     (error "No `hashcash' binary found")))
171
172 (defun hashcash-generate-payment-async (str val callback)
173   "Generate a hashcash payment by finding a VAL-bit collison on STR.
174 Return immediately.  Call CALLBACK with process and result when ready."
175   (if (and (> val 0)
176            hashcash-path)
177       (let ((process (apply 'start-process "hashcash" nil
178                             hashcash-path "-m" "-q"
179                             "-b" (number-to-string val) str
180                             hashcash-extra-generate-parameters)))
181         (setq hashcash-process-alist (cons
182                                       (cons process (current-buffer))
183                                       hashcash-process-alist))
184         (set-process-filter process `(lambda (process output)
185                                        (funcall ,callback process output))))
186     (funcall callback nil nil)))
187
188 (defun hashcash-check-payment (token str val)
189   "Check the validity of a hashcash payment."
190   (if hashcash-path
191       (zerop (call-process hashcash-path nil nil nil "-c"
192                            "-d" "-f" hashcash-double-spend-database
193                            "-b" (number-to-string val)
194                            "-r" str
195                            token))
196     (progn
197       (message "No hashcash binary found")
198       (sleep-for 1)
199       nil)))
200
201 (defun hashcash-version (token)
202   "Find the format version of a hashcash token."
203   ;; Version 1.2 looks like n:yymmdd:rrrrr:xxxxxxxxxxxxxxxx
204   ;;   This carries its own version number embedded in the token,
205   ;;   so no further format number changes should be necessary
206   ;;   in the X-Payment header.
207   ;;
208   ;; Version 1.1 looks like yymmdd:rrrrr:xxxxxxxxxxxxxxxx
209   ;;   You need to upgrade your hashcash binary.
210   ;;
211   ;; Version 1.0 looked like nnnnnrrrrrxxxxxxxxxxxxxxxx
212   ;;   This is no longer supported.
213   (cond ((equal (aref token 1) ?:) 1.2)
214         ((equal (aref token 6) ?:) 1.1)
215         (t (error "Unknown hashcash format version"))))
216
217 (defun hashcash-already-paid-p (recipient)
218   "Check for hashcash token to RECIPIENT in current buffer."
219   (save-excursion
220     (save-restriction
221       (message-narrow-to-headers-or-head)
222       (let ((token (message-fetch-field "x-hashcash"))
223             (case-fold-search t))
224         (and (stringp token)
225              (string-match (regexp-quote recipient) token))))))
226
227 ;;;###autoload
228 (defun hashcash-insert-payment (arg)
229   "Insert X-Payment and X-Hashcash headers with a payment for ARG"
230   (interactive "sPay to: ")
231   (unless (hashcash-already-paid-p arg)
232     (let ((pay (hashcash-generate-payment (hashcash-payment-to arg)
233                                           (hashcash-payment-required arg))))
234       (when pay
235         (insert-before-markers "X-Hashcash: " pay "\n")))))
236
237 ;;;###autoload
238 (defun hashcash-insert-payment-async (arg)
239   "Insert X-Payment and X-Hashcash headers with a payment for ARG
240 Only start calculation.  Results are inserted when ready."
241   (interactive "sPay to: ")
242   (unless (hashcash-already-paid-p arg)
243     (hashcash-generate-payment-async
244      (hashcash-payment-to arg)
245      (hashcash-payment-required arg)
246      `(lambda (process payment)
247         (hashcash-insert-payment-async-2 ,(current-buffer) process payment)))))
248
249 (defun hashcash-insert-payment-async-2 (buffer process pay)
250   (when (buffer-live-p buffer)
251     (with-current-buffer buffer
252       (save-excursion
253         (save-restriction
254           (setq hashcash-process-alist (delq
255                                         (assq process hashcash-process-alist)
256                                         hashcash-process-alist))
257           (message-goto-eoh)
258           (when pay
259             (insert-before-markers "X-Hashcash: " pay)))))))
260
261 (defun hashcash-cancel-async (&optional buffer)
262   "Delete any hashcash processes associated with BUFFER.
263 BUFFER defaults to the current buffer."
264   (interactive)
265   (unless buffer (setq buffer (current-buffer)))
266   (let (entry)
267     (while (setq entry (rassq buffer hashcash-process-alist))
268       (delete-process (car entry))
269       (setq hashcash-process-alist
270             (delq entry hashcash-process-alist)))))
271
272 (defun hashcash-wait-async (&optional buffer)
273   "Wait for asynchronous hashcash processes in BUFFER to finish.
274 BUFFER defaults to the current buffer."
275   (interactive)
276   (unless buffer (setq buffer (current-buffer)))
277   (let (entry)
278     (while (setq entry (rassq buffer hashcash-process-alist))
279       (accept-process-output (car entry)))))
280
281 (defun hashcash-processes-running-p (buffer)
282   "Return non-nil if hashcash processes in BUFFER are still running."
283   (rassq buffer hashcash-process-alist))
284
285 (defun hashcash-wait-or-cancel ()
286   "Ask user whether to wait for hashcash processes to finish."
287   (interactive)
288   (when (hashcash-processes-running-p (current-buffer))
289     (if (y-or-n-p 
290           "Hashcash process(es) still running; wait for them to finish? ")
291         (hashcash-wait-async)
292       (hashcash-cancel-async))))
293
294 ;;;###autoload
295 (defun hashcash-verify-payment (token &optional resource amount)
296   "Verify a hashcash payment"
297   (let* ((split (split-string token ":"))
298          (key (if (< (hashcash-version token) 1.2)
299                   (nth 1 split)
300                   (case (string-to-number (nth 0 split))
301                     (0 (nth 2 split))
302                     (1 (nth 3 split))))))
303     (cond ((null resource)
304            (let ((elt (assoc key hashcash-accept-resources)))
305              (and elt (hashcash-check-payment token (car elt)
306                         (or (cadr elt) hashcash-default-accept-payment)))))
307           ((equal token key)
308            (hashcash-check-payment token resource
309                                 (or amount hashcash-default-accept-payment)))
310           (t nil))))
311
312 ;;;###autoload
313 (defun mail-add-payment (&optional arg async)
314   "Add X-Payment: and X-Hashcash: headers with a hashcash payment
315 for each recipient address.  Prefix arg sets default payment temporarily.
316 Set ASYNC to t to start asynchronous calculation.  (See
317 `mail-add-payment-async')."
318   (interactive "P")
319   (let ((hashcash-default-payment (if arg (prefix-numeric-value arg)
320                                     hashcash-default-payment))
321         (addrlist nil))
322     (save-excursion
323       (save-restriction
324         (message-narrow-to-headers)
325         (let ((to (hashcash-strip-quoted-names (mail-fetch-field "To" nil t)))
326               (cc (hashcash-strip-quoted-names (mail-fetch-field "Cc" nil t)))
327               (ng (hashcash-strip-quoted-names (mail-fetch-field "Newsgroups"
328                                                                  nil t))))
329           (when to
330             (setq addrlist (split-string to ",[ \t\n]*")))
331           (when cc
332             (setq addrlist (nconc addrlist (split-string cc ",[ \t\n]*"))))
333           (when (and hashcash-in-news ng)
334             (setq addrlist (nconc addrlist (split-string ng ",[ \t\n]*")))))
335         (when addrlist
336           (mapc (if async
337                     #'hashcash-insert-payment-async
338                   #'hashcash-insert-payment)
339                 addrlist)))))
340   t)
341
342 ;;;###autoload
343 (defun mail-add-payment-async (&optional arg)
344   "Add X-Payment: and X-Hashcash: headers with a hashcash payment
345 for each recipient address.  Prefix arg sets default payment temporarily.
346 Calculation is asynchronous."
347   (interactive "P")
348   (mail-add-payment arg t))
349
350 ;;;###autoload
351 (defun mail-check-payment (&optional arg)
352   "Look for a valid X-Payment: or X-Hashcash: header.
353 Prefix arg sets default accept amount temporarily."
354   (interactive "P")
355   (let ((hashcash-default-accept-payment (if arg (prefix-numeric-value arg)
356                                            hashcash-default-accept-payment))
357         (version (hashcash-version (hashcash-generate-payment "x" 1))))
358     (save-excursion
359       (goto-char (point-min))
360       (search-forward "\n\n")
361       (beginning-of-line)
362       (let ((end (point))
363             (ok nil))
364         (goto-char (point-min))
365         (while (and (not ok) (search-forward "X-Payment: hashcash " end t))
366           (let ((value (split-string (hashcash-token-substring) " ")))
367             (when (equal (car value) (number-to-string version))
368               (setq ok (hashcash-verify-payment (cadr value))))))
369         (goto-char (point-min))
370         (while (and (not ok) (search-forward "X-Hashcash: " end t))
371           (setq ok (hashcash-verify-payment (hashcash-token-substring))))
372         (when ok
373           (message "Payment valid"))
374         ok))))
375
376 (provide 'hashcash)
377
378 ;; arch-tag: 0e7fe983-a124-4392-9788-0dbcbd2c4d62