* smtp.el (smtp-auth-cram-md5): Update to delete
[elisp/flim.git] / smtp.el
1 ;;; smtp.el --- basic functions to send mail with SMTP server
2
3 ;; Copyright (C) 1995, 1996, 1998, 1999 Free Software Foundation, Inc.
4
5 ;; Author: Tomoji Kagatani <kagatani@rbc.ncl.omron.co.jp>
6 ;;         Simon Leinen <simon@switch.ch> (ESMTP support)
7 ;;         Shuhei KOBAYASHI <shuhei@aqua.ocn.ne.jp>
8 ;;         Kenichi OKADA <okada@opaopa.org> (SASL support)
9 ;;         Daiki Ueno <ueno@ueda.info.waseda.ac.jp>
10 ;; Maintainer: Kenichi OKADA <okada@opaopa.org>
11 ;; Keywords: SMTP, mail, SASL
12
13 ;; This file is part of FLIM (Faithful Library about Internet Message).
14
15 ;; This program is free software; you can redistribute it and/or
16 ;; modify it under the terms of the GNU General Public License as
17 ;; published by the Free Software Foundation; either version 2, or (at
18 ;; your option) any later version.
19
20 ;; This program is distributed in the hope that it will be useful, but
21 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
22 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
23 ;; General Public License for more details.
24
25 ;; You should have received a copy of the GNU General Public License
26 ;; along with this program; see the file COPYING.  If not, write to the
27 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
28 ;; Boston, MA 02111-1307, USA.
29
30 ;;; Code:
31
32 (require 'poe)
33 (require 'poem)
34 (require 'pcustom)
35 (require 'mail-utils)                   ; mail-strip-quoted-names
36
37 (eval-and-compile
38   (autoload 'starttls-open-stream "starttls")
39   (autoload 'starttls-negotiate "starttls")
40   (autoload 'sasl-cram-md5 "sasl")
41   (autoload 'sasl-plain "sasl"))
42                        
43 (eval-when-compile (require 'cl))       ; push
44
45 (defgroup smtp nil
46   "SMTP protocol for sending mail."
47   :group 'mail)
48
49 (defcustom smtp-default-server nil
50   "*Specify default SMTP server."
51   :type '(choice (const nil) string)
52   :group 'smtp)
53
54 (defcustom smtp-server (or (getenv "SMTPSERVER") smtp-default-server)
55   "*The name of the host running SMTP server.  It can also be a function
56 called from `smtp-via-smtp' with arguments SENDER and RECIPIENTS."
57   :type '(choice (string :tag "Name")
58                  (function :tag "Function"))
59   :group 'smtp)
60
61 (defcustom smtp-service "smtp"
62   "*SMTP service port number. \"smtp\" or 25."
63   :type '(choice (integer :tag "25" 25)
64                  (string :tag "smtp" "smtp"))
65   :group 'smtp)
66
67 (defcustom smtp-use-8bitmime t
68   "*If non-nil, use ESMTP 8BITMIME if available."
69   :type 'boolean
70   :group 'smtp)
71
72 (defcustom smtp-local-domain nil
73   "*Local domain name without a host name.
74 If the function (system-name) returns the full internet address,
75 don't define this value."
76   :type '(choice (const nil) string)
77   :group 'smtp)
78
79 (defcustom smtp-debug-info nil
80   "*smtp debug info printout. messages and process buffer."
81   :type 'boolean
82   :group 'smtp)
83
84 (defcustom smtp-notify-success nil
85   "*If non-nil, notification for successful mail delivery is returned 
86  to user (RFC1891)."
87   :type 'boolean
88   :group 'smtp)
89
90 (defcustom smtp-authentication-type nil
91   "*SMTP authentication mechanism (RFC2554)."
92   :type 'symbol
93   :group 'smtp)
94
95 (defvar smtp-authentication-user nil)
96 (defvar smtp-authentication-passphrase nil)
97
98 (defvar smtp-authentication-method-alist
99   '((cram-md5 smtp-auth-cram-md5)
100     (plain smtp-auth-plain)
101     (login smtp-auth-login)
102     ))
103
104 (defcustom smtp-connection-type nil
105   "*SMTP connection type."
106   :type '(choice (const nil) (const :tag "TLS" starttls))
107   :group 'smtp)
108  
109 (defvar smtp-read-point nil)
110
111 (defun smtp-make-fqdn ()
112   "Return user's fully qualified domain name."
113   (let ((system-name (system-name)))
114     (cond
115      (smtp-local-domain
116       (concat system-name "." smtp-local-domain))
117      ((string-match "[^.]\\.[^.]" system-name)
118       system-name)
119      (t
120       (error "Cannot generate valid FQDN. Set `smtp-local-domain' correctly.")))))
121
122 (defun smtp-via-smtp (sender recipients smtp-text-buffer)
123   (let ((server (if (functionp smtp-server)
124                     (funcall smtp-server sender recipients)
125                   smtp-server))
126         process response extensions)
127     (save-excursion
128       (set-buffer
129        (get-buffer-create
130         (format "*trace of SMTP session to %s*" server)))
131       (erase-buffer)
132       (make-local-variable 'smtp-read-point)
133       (setq smtp-read-point (point-min))
134
135       (unwind-protect
136           (catch 'done
137             (setq process 
138                   (if smtp-connection-type
139                       (starttls-open-stream
140                        "SMTP" (current-buffer) server smtp-service)
141                     (open-network-stream-as-binary
142                      "SMTP" (current-buffer) server smtp-service)))
143             (or process (throw 'done nil))
144
145             (set-process-filter process 'smtp-process-filter)
146
147             (if (eq smtp-connection-type 'force)
148                 (starttls-negotiate process))
149
150             ;; Greeting
151             (setq response (smtp-read-response process))
152             (if (or (null (car response))
153                     (not (integerp (car response)))
154                     (>= (car response) 400))
155                 (throw 'done (car (cdr response))))
156
157             ;; EHLO
158             (smtp-send-command process
159                                (format "EHLO %s" (smtp-make-fqdn)))
160             (setq response (smtp-read-response process))
161             (if (or (null (car response))
162                     (not (integerp (car response)))
163                     (>= (car response) 400))
164                 (progn
165                   ;; HELO
166                   (smtp-send-command process
167                                      (format "HELO %s" (smtp-make-fqdn)))
168                   (setq response (smtp-read-response process))
169                   (if (or (null (car response))
170                           (not (integerp (car response)))
171                           (>= (car response) 400))
172                       (throw 'done (car (cdr response)))))
173               (let ((extension-lines (cdr (cdr response)))
174                     extension)
175                 (while extension-lines
176                   (if (string-match
177                        "^auth "
178                        (setq extension
179                              (downcase (substring (car extension-lines) 4))))
180                       (while (string-match "\\([^ ]+\\)" extension (match-end 1))
181                         (push (intern (match-string 1 extension)) extensions))
182                     (push (intern extension) extensions))
183                   (setq extension-lines (cdr extension-lines)))))
184
185             ;; STARTTLS --- begin a TLS negotiation (RFC 2595)
186             (when (and smtp-connection-type 
187                        (null (eq smtp-connection-type 'force))
188                        (memq 'starttls extensions))
189               (smtp-send-command process "STARTTLS")
190               (setq response (smtp-read-response process))
191               (if (or (null (car response))
192                       (not (integerp (car response)))
193                       (>= (car response) 400))
194                   (throw 'done (car (cdr response))))
195               (starttls-negotiate process))
196
197             ;; AUTH --- SMTP Service Extension for Authentication (RFC2554)
198             (when smtp-authentication-type
199               (let ((auth (intern smtp-authentication-type)) method)
200                 (if (and 
201                      (memq auth extensions)
202                      (setq method (nth 1 (assq auth smtp-authentication-method-alist))))
203                     (funcall method process)
204                   (throw 'smtp-error
205                          (format "AUTH mechanism %s not available" auth)))))
206
207             ;; ONEX --- One message transaction only (sendmail extension?)
208             (if (or (memq 'onex extensions)
209                     (memq 'xone extensions))
210                 (progn
211                   (smtp-send-command process "ONEX")
212                   (setq response (smtp-read-response process))
213                   (if (or (null (car response))
214                           (not (integerp (car response)))
215                           (>= (car response) 400))
216                       (throw 'done (car (cdr response))))))
217
218             ;; VERB --- Verbose (sendmail extension?)
219             (if (and smtp-debug-info
220                      (or (memq 'verb extensions)
221                          (memq 'xvrb extensions)))
222                 (progn
223                   (smtp-send-command process "VERB")
224                   (setq response (smtp-read-response process))
225                   (if (or (null (car response))
226                           (not (integerp (car response)))
227                           (>= (car response) 400))
228                       (throw 'done (car (cdr response))))))
229
230             ;; XUSR --- Initial (user) submission (sendmail extension?)
231             (if (memq 'xusr extensions)
232                 (progn
233                   (smtp-send-command process "XUSR")
234                   (setq response (smtp-read-response process))
235                   (if (or (null (car response))
236                           (not (integerp (car response)))
237                           (>= (car response) 400))
238                       (throw 'done (car (cdr response))))))
239
240             ;; MAIL FROM:<sender>
241             (smtp-send-command
242              process
243              (format "MAIL FROM:<%s>%s%s"
244                      sender
245                      ;; SIZE --- Message Size Declaration (RFC1870)
246                      (if (memq 'size extensions)
247                          (format " SIZE=%d"
248                                  (save-excursion
249                                    (set-buffer smtp-text-buffer)
250                                    (+ (- (point-max) (point-min))
251                                       ;; Add one byte for each change-of-line
252                                       ;; because or CR-LF representation:
253                                       (count-lines (point-min) (point-max))
254                                       ;; For some reason, an empty line is
255                                       ;; added to the message.  Maybe this
256                                       ;; is a bug, but it can't hurt to add
257                                       ;; those two bytes anyway:
258                                       2)))
259                        "")
260                      ;; 8BITMIME --- 8bit-MIMEtransport (RFC1652)
261                      (if (and (memq '8bitmime extensions)
262                               smtp-use-8bitmime)
263                          " BODY=8BITMIME"
264                        "")))
265             (setq response (smtp-read-response process))
266             (if (or (null (car response))
267                     (not (integerp (car response)))
268                     (>= (car response) 400))
269                 (throw 'done (car (cdr response))))
270
271             ;; RCPT TO:<recipient>
272             (while recipients
273               (smtp-send-command process
274                                  (format
275                                   (if smtp-notify-success
276                                       "RCPT TO:<%s> NOTIFY=SUCCESS" 
277                                     "RCPT TO:<%s>")
278                                   (car recipients)))
279               (setq recipients (cdr recipients))
280               (setq response (smtp-read-response process))
281               (if (or (null (car response))
282                       (not (integerp (car response)))
283                       (>= (car response) 400))
284                   (throw 'done (car (cdr response)))))
285
286             ;; DATA
287             (smtp-send-command process "DATA")
288             (setq response (smtp-read-response process))
289             (if (or (null (car response))
290                     (not (integerp (car response)))
291                     (>= (car response) 400))
292                 (throw 'done (car (cdr response))))
293
294             ;; Mail contents
295             (smtp-send-data process smtp-text-buffer)
296
297             ;; DATA end "."
298             (smtp-send-command process ".")
299             (setq response (smtp-read-response process))
300             (if (or (null (car response))
301                     (not (integerp (car response)))
302                     (>= (car response) 400))
303                 (throw 'done (car (cdr response))))
304
305             t)
306
307         (if (and process
308                  (eq (process-status process) 'open))
309             (progn
310               ;; QUIT
311               (smtp-send-command process "QUIT")
312               (smtp-read-response process)
313               (delete-process process)))))))
314
315 (defun smtp-process-filter (process output)
316   (save-excursion
317     (set-buffer (process-buffer process))
318     (goto-char (point-max))
319     (insert output)))
320
321 (defun smtp-read-response (process)
322   (let ((case-fold-search nil)
323         (response-strings nil)
324         (response-continue t)
325         (return-value '(nil ()))
326         match-end)
327
328     (while response-continue
329       (goto-char smtp-read-point)
330       (while (not (search-forward "\r\n" nil t))
331         (accept-process-output process)
332         (goto-char smtp-read-point))
333
334       (setq match-end (point))
335       (setq response-strings
336             (cons (buffer-substring smtp-read-point (- match-end 2))
337                   response-strings))
338         
339       (goto-char smtp-read-point)
340       (if (looking-at "[0-9]+ ")
341           (let ((begin (match-beginning 0))
342                 (end (match-end 0)))
343             (if smtp-debug-info
344                 (message "%s" (car response-strings)))
345
346             (setq smtp-read-point match-end)
347
348             ;; ignore lines that start with "0"
349             (if (looking-at "0[0-9]+ ")
350                 nil
351               (setq response-continue nil)
352               (setq return-value
353                     (cons (string-to-int
354                            (buffer-substring begin end))
355                           (nreverse response-strings)))))
356         
357         (if (looking-at "[0-9]+-")
358             (progn (if smtp-debug-info
359                      (message "%s" (car response-strings)))
360                    (setq smtp-read-point match-end)
361                    (setq response-continue t))
362           (progn
363             (setq smtp-read-point match-end)
364             (setq response-continue nil)
365             (setq return-value
366                   (cons nil (nreverse response-strings)))))))
367     (setq smtp-read-point match-end)
368     return-value))
369
370 (defun smtp-send-command (process command)
371   (goto-char (point-max))
372   (insert command "\r\n")
373   (setq smtp-read-point (point))
374   (process-send-string process command)
375   (process-send-string process "\r\n"))
376
377 (defun smtp-send-data-1 (process data)
378   (goto-char (point-max))
379   (if smtp-debug-info
380       (insert data "\r\n"))
381   (setq smtp-read-point (point))
382   ;; Escape "." at start of a line.
383   (if (eq (string-to-char data) ?.)
384       (process-send-string process "."))
385   (process-send-string process data)
386   (process-send-string process "\r\n"))
387
388 (defun smtp-send-data (process buffer)
389   (let ((data-continue t)
390         (sending-data nil)
391         this-line
392         this-line-end)
393
394     (save-excursion
395       (set-buffer buffer)
396       (goto-char (point-min)))
397
398     (while data-continue
399       (save-excursion
400         (set-buffer buffer)
401         (beginning-of-line)
402         (setq this-line (point))
403         (end-of-line)
404         (setq this-line-end (point))
405         (setq sending-data nil)
406         (setq sending-data (buffer-substring this-line this-line-end))
407         (if (or (/= (forward-line 1) 0) (eobp))
408             (setq data-continue nil)))
409
410       (smtp-send-data-1 process sending-data))))
411
412 (defun smtp-deduce-address-list (smtp-text-buffer header-start header-end)
413   "Get address list suitable for smtp RCPT TO:<address>."
414   (let ((case-fold-search t)
415         (simple-address-list "")
416         this-line
417         this-line-end
418         addr-regexp
419         (smtp-address-buffer (generate-new-buffer " *smtp-mail*")))
420     (unwind-protect
421         (save-excursion
422           ;;
423           (set-buffer smtp-address-buffer)
424           (erase-buffer)
425           (insert (save-excursion
426                     (set-buffer smtp-text-buffer)
427                     (buffer-substring-no-properties header-start header-end)))
428           (goto-char (point-min))
429           ;; RESENT-* fields should stop processing of regular fields.
430           (save-excursion
431             (if (re-search-forward "^RESENT-TO:" header-end t)
432                 (setq addr-regexp
433                       "^\\(RESENT-TO:\\|RESENT-CC:\\|RESENT-BCC:\\)")
434               (setq addr-regexp  "^\\(TO:\\|CC:\\|BCC:\\)")))
435
436           (while (re-search-forward addr-regexp header-end t)
437             (replace-match "")
438             (setq this-line (match-beginning 0))
439             (forward-line 1)
440             ;; get any continuation lines.
441             (while (and (looking-at "^[ \t]+") (< (point) header-end))
442               (forward-line 1))
443             (setq this-line-end (point-marker))
444             (setq simple-address-list
445                   (concat simple-address-list " "
446                           (mail-strip-quoted-names
447                            (buffer-substring this-line this-line-end)))))
448           (erase-buffer)
449           (insert-string " ")
450           (insert-string simple-address-list)
451           (insert-string "\n")
452           ;; newline --> blank
453           (subst-char-in-region (point-min) (point-max) 10 ?  t)
454           ;; comma   --> blank
455           (subst-char-in-region (point-min) (point-max) ?, ?  t)
456           ;; tab     --> blank
457           (subst-char-in-region (point-min) (point-max)  9 ?  t)
458
459           (goto-char (point-min))
460           ;; tidyness in case hook is not robust when it looks at this
461           (while (re-search-forward "[ \t]+" header-end t) (replace-match " "))
462
463           (goto-char (point-min))
464           (let (recipient-address-list)
465             (while (re-search-forward " \\([^ ]+\\) " (point-max) t)
466               (backward-char 1)
467               (setq recipient-address-list
468                     (cons (buffer-substring (match-beginning 1) (match-end 1))
469                           recipient-address-list)))
470             recipient-address-list))
471       (kill-buffer smtp-address-buffer))))
472
473 (defun smtp-auth-cram-md5 (process)
474   (let ((secure-word (copy-sequence smtp-authentication-passphrase))
475         response)
476     (smtp-send-command process "AUTH CRAM-MD5")
477     (setq response (smtp-read-response process))
478     (if (or (null (car response))
479             (not (integerp (car response)))
480             (>= (car response) 400))
481         (throw 'done (car (cdr response))))
482     (smtp-send-command
483      process
484      (setq secure-word (unwind-protect
485                            (sasl-cram-md5
486                             smtp-authentication-user secure-word
487                             (base64-decode-string
488                              (substring (car (cdr response)) 4)))
489                          (fillarray secure-word 0))
490            secure-word (unwind-protect
491                            (base64-encode-string secure-word)
492                          (fillarray secure-word 0))))
493     (fillarray secure-word 0)
494     (setq response (smtp-read-response process))
495     (if (or (null (car response))
496             (not (integerp (car response)))
497             (>= (car response) 400))
498         (throw 'done (car (cdr response))))))
499  
500 (defun smtp-auth-plain (process)
501   (let ((secure-word (copy-sequence smtp-authentication-passphrase))
502         response)
503     (smtp-send-command
504      process
505      (setq secure-word (unwind-protect
506                         (sasl-plain "" smtp-authentication-user secure-word)
507                       (fillarray secure-word 0))
508            secure-word (unwind-protect
509                         (base64-encode-string secure-word)
510                       (fillarray secure-word 0))
511            secure-word (unwind-protect
512                         (concat "AUTH PLAIN " secure-word)
513                       (fillarray secure-word 0))))
514     (fillarray secure-word 0)
515     (setq response (smtp-read-response process))
516     (if (or (null (car response))
517             (not (integerp (car response)))
518             (>= (car response) 400))
519         (throw 'done (car (cdr response))))))
520
521 (defun smtp-auth-login (process)
522   (let ((secure-word (copy-sequence smtp-authentication-passphrase))
523         response)
524     (smtp-send-command
525      process
526      (concat "AUTH LOGIN " smtp-authentication-user))
527     (setq response (smtp-read-response process))
528     (if (or (null (car response))
529             (not (integerp (car response)))
530             (>= (car response) 400))
531         (throw 'done (car (cdr response))))
532     (smtp-send-command
533      process
534      (setq secure-word (unwind-protect
535                         (base64-encode-string secure-word)
536                       (fillarray secure-word 0))))
537     (fillarray secure-word 0)
538     (setq response (smtp-read-response process))
539     (if (or (null (car response))
540             (not (integerp (car response)))
541             (>= (car response) 400))
542         (throw 'done (car (cdr response))))))
543  
544 (provide 'smtp)
545
546 ;;; smtp.el ends here