(smtp-open-connection): Don't use `as-binary-process'.
[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 ;;      Daiki Ueno <ueno@unixuser.org>
9 ;; Keywords: SMTP, mail
10
11 ;; This file is part of FLIM (Faithful Library about Internet Message).
12
13 ;; This program is free software; you can redistribute it and/or
14 ;; modify it under the terms of the GNU General Public License as
15 ;; published by the Free Software Foundation; either version 2, or (at
16 ;; your option) any later version.
17
18 ;; This program is distributed in the hope that it will be useful, but
19 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21 ;; General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with this program; see the file COPYING.  If not, write to the
25 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26 ;; Boston, MA 02111-1307, USA.
27
28
29 ;;; Commentary:
30 ;; 
31
32 ;;; Code:
33
34 (require 'pces)
35 (require 'custom)
36 (require 'mail-utils)                   ; mail-strip-quoted-names
37 (require 'sasl)
38 (require 'luna)
39
40 (defgroup smtp nil
41   "SMTP protocol for sending mail."
42   :group 'mail)
43
44 (defgroup smtp-extensions nil
45   "SMTP service extensions (RFC1869)."
46   :group 'smtp)
47
48 (defcustom smtp-default-server nil
49   "Specify default SMTP server."
50   :type '(choice (const nil) string)
51   :group 'smtp)
52
53 (defcustom smtp-server (or (getenv "SMTPSERVER") smtp-default-server)
54   "The name of the host running SMTP server.
55 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-local-domain nil
68   "Local domain name without a host name.
69 If the function (system-name) returns the full internet address,
70 don't define this value."
71   :type '(choice (const nil) string)
72   :group 'smtp)
73
74 (defcustom smtp-fqdn nil
75   "Fully qualified domain name used for Message-ID."
76   :type '(choice (const nil) string)
77   :group 'smtp)
78
79 (defcustom smtp-use-8bitmime t
80   "If non-nil, use ESMTP 8BITMIME (RFC1652) if available."
81   :type 'boolean
82   :group 'smtp-extensions)
83
84 (defcustom smtp-use-size t
85   "If non-nil, use ESMTP SIZE (RFC1870) if available."
86   :type 'boolean
87   :group 'smtp-extensions)
88
89 (defcustom smtp-use-starttls nil
90   "If non-nil, use STARTTLS (RFC2595) if available."
91   :type 'boolean
92   :group 'smtp-extensions)
93
94 (defcustom smtp-use-sasl nil
95   "If non-nil, use SMTP Authentication (RFC2554) if available."
96   :type 'boolean
97   :group 'smtp-extensions)
98
99 (defcustom smtp-sasl-user-name (user-login-name)
100   "Identification to be used for authorization."
101   :type 'string
102   :group 'smtp-extensions)
103
104 (defcustom smtp-sasl-properties nil
105   "Properties set to SASL client."
106   :type 'string
107   :group 'smtp-extensions)
108
109 (defcustom smtp-sasl-mechanisms nil
110   "List of authentication mechanisms."
111   :type '(repeat string)
112   :group 'smtp-extensions)
113
114 (defvar sasl-mechanisms)
115   
116 (defvar smtp-open-connection-function #'open-network-stream)
117
118 (defvar smtp-read-point nil)
119
120 (defvar smtp-connection-alist nil)
121
122 (defvar smtp-submit-package-function #'smtp-submit-package)
123
124 ;;; @ SMTP package
125 ;;; A package contains a mail message, an envelope sender address,
126 ;;; and one or more envelope recipient addresses.  In ESMTP model
127 ;;; the current sending package should be guaranteed to be accessible
128 ;;; anywhere from the hook methods (or SMTP commands).
129
130 (eval-and-compile
131   (luna-define-class smtp-package ()
132                      (sender
133                       recipients
134                       buffer))
135
136   (luna-define-internal-accessors 'smtp-package))
137
138 (defun smtp-make-package (sender recipients buffer)
139   "Create a new package structure.
140 A package is a unit of SMTP message
141 SENDER specifies the package sender, a string.
142 RECIPIENTS is a list of recipients.
143 BUFFER may be a buffer or a buffer name which contains mail message."
144   (luna-make-entity 'smtp-package :sender sender :recipients recipients :buffer buffer))
145
146 (defun smtp-package-buffer-internal-size (package)
147   "Return the size of PACKAGE, an integer."
148   (save-excursion
149     (set-buffer (smtp-package-buffer-internal package))
150     (let ((size
151            (+ (buffer-size)
152               ;; Add one byte for each change-of-line
153               ;; because or CR-LF representation:
154               (count-lines (point-min) (point-max))
155               ;; For some reason, an empty line is
156               ;; added to the message.  Maybe this
157               ;; is a bug, but it can't hurt to add
158               ;; those two bytes anyway:
159               2)))
160       (goto-char (point-min))
161       (while (re-search-forward "^\\." nil t)
162         (setq size (1+ size)))
163       size)))
164
165 ;;; @ SMTP connection
166 ;;; We should consider the function `open-network-stream' is a emulation
167 ;;; for another network stream.  They are likely to be implemented with an
168 ;;; external program and the function `process-contact' returns the
169 ;;; process id instead of `(HOST SERVICE)' pair.
170
171 (eval-and-compile
172   (luna-define-class smtp-connection ()
173                      (process
174                       server
175                       service
176                       extensions
177                       encoder
178                       decoder))
179
180   (luna-define-internal-accessors 'smtp-connection))
181
182 (defun smtp-make-connection (process server service)
183   "Create a new connection structure.
184 PROCESS is an internal subprocess-object.  SERVER is name of the host
185 to connect to.  SERVICE is name of the service desired."
186   (luna-make-entity 'smtp-connection :process process :server server :service service))
187
188 (luna-define-generic smtp-connection-opened (connection)
189   "Say whether the CONNECTION to server has been opened.")
190
191 (luna-define-generic smtp-close-connection (connection)
192   "Close the CONNECTION to server.")
193
194 (luna-define-method smtp-connection-opened ((connection smtp-connection))
195   (let ((process (smtp-connection-process-internal connection)))
196     (if (memq (process-status process) '(open run))
197         t)))
198
199 (luna-define-method smtp-close-connection ((connection smtp-connection))
200   (let ((process (smtp-connection-process-internal connection)))
201     (delete-process process)))
202
203 (defun smtp-make-fqdn ()
204   "Return user's fully qualified domain name."
205   (if smtp-fqdn
206       smtp-fqdn
207     (let ((system-name (system-name)))
208       (cond
209        (smtp-local-domain
210         (concat system-name "." smtp-local-domain))
211        ((string-match "[^.]\\.[^.]" system-name)
212         system-name)
213        (t
214         (error "Cannot generate valid FQDN"))))))
215
216 (defun smtp-find-connection (buffer)
217   "Find the connection delivering to BUFFER."
218   (let ((entry (assq buffer smtp-connection-alist))
219         connection)
220     (when entry
221       (setq connection (nth 1 entry))
222       (if (smtp-connection-opened connection)
223           connection
224         (setq smtp-connection-alist
225               (delq entry smtp-connection-alist))
226         nil))))
227
228 (eval-and-compile
229   (autoload 'starttls-open-stream "starttls")
230   (autoload 'starttls-negotiate "starttls"))
231
232 (defun smtp-open-connection (buffer server service)
233   "Open a SMTP connection for a service to a host.
234 Return a newly allocated connection-object.
235 BUFFER is the buffer to associate with the connection.  SERVER is name
236 of the host to connect to.  SERVICE is name of the service desired."
237   (let* ((coding-system-for-read  'binary)
238          (coding-system-for-write 'binary)
239          (process
240           (funcall smtp-open-connection-function
241                    "SMTP" buffer  server service))
242          connection)
243     (when process
244       (setq connection (smtp-make-connection process server service))
245       (set-process-filter process 'smtp-process-filter)
246       (setq smtp-connection-alist
247             (cons (list buffer connection)
248                   smtp-connection-alist))
249       connection)))
250
251 ;;;###autoload
252 (defun smtp-via-smtp (sender recipients buffer)
253   (condition-case nil
254       (progn
255         (smtp-send-buffer sender recipients buffer)
256         t)
257     (smtp-error)))
258
259 (make-obsolete 'smtp-via-smtp "It's old API.")
260
261 ;;;###autoload
262 (defun smtp-send-buffer (sender recipients buffer)
263   (let ((server
264          (if (functionp smtp-server)
265              (funcall smtp-server sender recipients)
266            smtp-server))
267         (package
268          (smtp-make-package sender recipients buffer))
269         (smtp-open-connection-function
270          (if smtp-use-starttls
271              #'starttls-open-stream
272            smtp-open-connection-function)))
273     (save-excursion
274       (set-buffer
275        (get-buffer-create
276         (format "*trace of SMTP session to %s*" server)))
277       (erase-buffer)
278       (buffer-disable-undo)
279       (unless (smtp-find-connection (current-buffer))
280         (smtp-open-connection (current-buffer) server smtp-service))
281       (make-local-variable 'smtp-read-point)
282       (setq smtp-read-point (point-min))
283       (funcall smtp-submit-package-function package))))
284
285 (defun smtp-submit-package (package)
286   (unwind-protect
287       (progn
288         (smtp-primitive-greeting package)
289         (condition-case nil
290             (smtp-primitive-ehlo package)
291           (smtp-response-error
292            (smtp-primitive-helo package)))
293         (if smtp-use-starttls
294             (smtp-primitive-starttls package))
295         (if smtp-use-sasl
296             (smtp-primitive-auth package))
297         (smtp-primitive-mailfrom package)
298         (smtp-primitive-rcptto package)
299         (smtp-primitive-data package))
300     (let ((connection (smtp-find-connection (current-buffer))))
301       (when (smtp-connection-opened connection)
302         (smtp-primitive-quit package)
303         (smtp-close-connection connection)))))
304
305 ;;; @ hook methods for `smtp-submit-package'
306 ;;;
307
308 (defun smtp-primitive-greeting (package)
309   (let* ((connection
310           (smtp-find-connection (current-buffer)))
311          (response
312           (smtp-read-response connection)))
313     (if (/= (car response) 220)
314         (smtp-response-error response))))
315
316 (defun smtp-primitive-ehlo (package)
317   (let* ((connection
318           (smtp-find-connection (current-buffer)))
319          response)
320     (smtp-send-command connection (format "EHLO %s" (smtp-make-fqdn)))
321     (setq response (smtp-read-response connection))
322     (if (/= (car response) 250)
323         (smtp-response-error response))
324     (smtp-connection-set-extensions-internal
325      connection (mapcar
326                  (lambda (extension)
327                    (let ((extensions
328                           (split-string extension)))
329                      (setcar extensions
330                              (car (read-from-string
331                                    (downcase (car extensions)))))
332                      extensions))
333                  (cdr response)))))
334
335 (defun smtp-primitive-helo (package)
336   (let* ((connection
337           (smtp-find-connection (current-buffer)))
338          response)
339     (smtp-send-command connection (format "HELO %s" (smtp-make-fqdn)))
340     (setq response (smtp-read-response connection))
341     (if (/= (car response) 250)
342         (smtp-response-error response))))
343
344 (defun smtp-primitive-auth (package)
345   (let* ((connection
346           (smtp-find-connection (current-buffer)))
347          (mechanisms
348           (cdr (assq 'auth (smtp-connection-extensions-internal connection))))
349          (sasl-mechanisms
350           (or smtp-sasl-mechanisms sasl-mechanisms))
351          (mechanism
352           (sasl-find-mechanism mechanisms))
353          client
354          name
355          step
356          response)
357     (unless mechanism
358       (error "No authentication mechanism available"))
359     (setq client (sasl-make-client mechanism smtp-sasl-user-name "smtp"
360                                    (smtp-connection-server-internal connection)))
361     (if smtp-sasl-properties
362         (sasl-client-set-properties client smtp-sasl-properties))
363     (setq name (sasl-mechanism-name mechanism)
364           ;; Retrieve the initial response
365           step (sasl-next-step client nil))
366     (smtp-send-command
367      connection
368      (if (sasl-step-data step)
369          (format "AUTH %s %s" name (base64-encode-string (sasl-step-data step) t))
370        (format "AUTH %s" name)))
371     (catch 'done
372       (while t
373         (setq response (smtp-read-response connection))
374         (when (= (car response) 235)
375           ;; The authentication process is finished.
376           (setq step (sasl-next-step client step))
377           (if (null step)
378               (throw 'done nil))
379           (smtp-response-error response)) ;Bogus server?
380         (if (/= (car response) 334)
381             (smtp-response-error response))
382         (sasl-step-set-data step (base64-decode-string (nth 1 response)))
383         (setq step (sasl-next-step client step))
384         (smtp-send-command
385          connection
386          (if (sasl-step-data step)
387              (base64-encode-string (sasl-step-data step) t)
388            ""))))
389 ;;;    (smtp-connection-set-encoder-internal
390 ;;;     connection (sasl-client-encoder client))
391 ;;;    (smtp-connection-set-decoder-internal
392 ;;;     connection (sasl-client-decoder client))
393     ))
394
395 (defun smtp-primitive-starttls (package)
396   (let* ((connection
397           (smtp-find-connection (current-buffer)))
398          response)
399     ;; STARTTLS --- begin a TLS negotiation (RFC 2595)
400     (smtp-send-command connection "STARTTLS")
401     (setq response (smtp-read-response connection))
402     (if (/= (car response) 220)
403         (smtp-response-error response))
404     (starttls-negotiate (smtp-connection-process-internal connection))))
405
406 (defun smtp-primitive-mailfrom (package)
407   (let* ((connection
408           (smtp-find-connection (current-buffer)))
409          (extensions
410           (smtp-connection-extensions-internal
411            connection))
412          (sender
413           (smtp-package-sender-internal package))
414          extension
415          response)
416     ;; SIZE --- Message Size Declaration (RFC1870)
417     (if (and smtp-use-size
418              (assq 'size extensions))
419         (setq extension (format "SIZE=%d" (smtp-package-buffer-internal-size package))))
420     ;; 8BITMIME --- 8bit-MIMEtransport (RFC1652)
421     (if (and smtp-use-8bitmime
422              (assq '8bitmime extensions))
423         (setq extension (concat extension " BODY=8BITMIME")))
424     (smtp-send-command
425      connection
426      (if extension
427          (format "MAIL FROM:<%s> %s" sender extension)
428        (format "MAIL FROM:<%s>" sender)))
429     (setq response (smtp-read-response connection))
430     (if (/= (car response) 250)
431         (smtp-response-error response))))
432
433 (defun smtp-primitive-rcptto (package)
434   (let* ((connection
435           (smtp-find-connection (current-buffer)))
436          (recipients
437           (smtp-package-recipients-internal package))
438          response)
439     (while recipients
440       (smtp-send-command
441        connection (format "RCPT TO:<%s>" (pop recipients)))
442       (setq response (smtp-read-response connection))
443       (unless (memq (car response) '(250 251))
444         (smtp-response-error response)))))
445
446 (defun smtp-primitive-data (package)
447   (let* ((connection
448           (smtp-find-connection (current-buffer)))
449          response)
450     (smtp-send-command connection "DATA")
451     (setq response (smtp-read-response connection))
452     (if (/= (car response) 354)
453         (smtp-response-error response))
454     (save-excursion
455       (set-buffer (smtp-package-buffer-internal package))
456       (goto-char (point-min))
457       (while (not (eobp))
458         (smtp-send-data
459          connection (buffer-substring (point) (progn (end-of-line)(point))))
460         (beginning-of-line 2)))
461     (smtp-send-command connection ".")
462     (setq response (smtp-read-response connection))
463     (if (/= (car response) 250)
464         (smtp-response-error response))))
465
466 (defun smtp-primitive-quit (package)
467   (let* ((connection
468           (smtp-find-connection (current-buffer)))
469          response)
470     (smtp-send-command connection "QUIT")
471     (setq response (smtp-read-response connection))
472     (if (/= (car response) 221)
473         (smtp-response-error response))))
474
475 ;;; @ low level process manipulating function
476 ;;;
477 (defun smtp-process-filter (process output)
478   (save-excursion
479     (set-buffer (process-buffer process))
480     (goto-char (point-max))
481     (insert output)))
482
483 (put 'smtp-error 'error-message "SMTP error")
484 (put 'smtp-error 'error-conditions '(smtp-error error))
485
486 (put 'smtp-response-error 'error-message "SMTP response error")
487 (put 'smtp-response-error 'error-conditions '(smtp-response-error smtp-error error))
488
489 (defun smtp-response-error (response)
490   (signal 'smtp-response-error response))
491
492 (defun smtp-read-response (connection)
493   (let ((decoder
494          (smtp-connection-decoder-internal connection))
495         (response-continue t)
496         response)
497     (while response-continue
498       (goto-char smtp-read-point)
499       (while (not (search-forward "\r\n" nil t))
500         (accept-process-output (smtp-connection-process-internal connection))
501         (goto-char smtp-read-point))
502       (if decoder
503           (let ((string (buffer-substring smtp-read-point (- (point) 2))))
504             (delete-region smtp-read-point (point))
505             (insert (funcall decoder string) "\r\n")))
506       (setq response
507             (nconc response
508                    (list (buffer-substring
509                           (+ 4 smtp-read-point)
510                           (- (point) 2)))))
511       (goto-char
512        (prog1 smtp-read-point
513          (setq smtp-read-point (point))))
514       (if (looking-at "[1-5][0-9][0-9] ")
515           (setq response (cons (read (point-marker)) response)
516                 response-continue nil)))
517     response))
518
519 (defun smtp-send-command (connection command)
520   (save-excursion
521     (let ((process
522            (smtp-connection-process-internal connection))
523           (encoder
524            (smtp-connection-encoder-internal connection)))
525       (set-buffer (process-buffer process))
526       (goto-char (point-max))
527       (setq command (concat command "\r\n"))
528       (insert command)
529       (setq smtp-read-point (point))
530       (if encoder
531           (setq command (funcall encoder command)))
532       (process-send-string process command))))
533
534 (defun smtp-send-data (connection data)
535   (let ((process
536          (smtp-connection-process-internal connection))
537         (encoder
538          (smtp-connection-encoder-internal connection)))
539     ;; Escape "." at start of a line.
540     (if (eq (string-to-char data) ?.)
541         (setq data (concat "." data "\r\n"))
542       (setq data (concat data "\r\n")))
543     (if encoder
544         (setq data (funcall encoder data)))
545     (process-send-string process data)))
546
547 (defun smtp-deduce-address-list (smtp-text-buffer header-start header-end)
548   "Get address list suitable for smtp RCPT TO:<address>."
549   (let ((simple-address-list "")
550         this-line
551         this-line-end
552         addr-regexp
553         (smtp-address-buffer (generate-new-buffer " *smtp-mail*")))
554     (unwind-protect
555         (save-excursion
556           ;;
557           (set-buffer smtp-address-buffer)
558           (setq case-fold-search t)
559           (erase-buffer)
560           (insert (save-excursion
561                     (set-buffer smtp-text-buffer)
562                     (buffer-substring-no-properties header-start header-end)))
563           (goto-char (point-min))
564           ;; RESENT-* fields should stop processing of regular fields.
565           (save-excursion
566             (if (re-search-forward "^RESENT-TO:" header-end t)
567                 (setq addr-regexp
568                       "^\\(RESENT-TO:\\|RESENT-CC:\\|RESENT-BCC:\\)")
569               (setq addr-regexp  "^\\(TO:\\|CC:\\|BCC:\\)")))
570
571           (while (re-search-forward addr-regexp header-end t)
572             (replace-match "")
573             (setq this-line (match-beginning 0))
574             (forward-line 1)
575             ;; get any continuation lines.
576             (while (and (looking-at "^[ \t]+") (< (point) header-end))
577               (forward-line 1))
578             (setq this-line-end (point-marker))
579             (setq simple-address-list
580                   (concat simple-address-list " "
581                           (mail-strip-quoted-names
582                            (buffer-substring this-line this-line-end)))))
583           (erase-buffer)
584           (insert-string " ")
585           (insert-string simple-address-list)
586           (insert-string "\n")
587           ;; newline --> blank
588           (subst-char-in-region (point-min) (point-max) 10 ?  t)
589           ;; comma   --> blank
590           (subst-char-in-region (point-min) (point-max) ?, ?  t)
591           ;; tab     --> blank
592           (subst-char-in-region (point-min) (point-max)  9 ?  t)
593
594           (goto-char (point-min))
595           ;; tidyness in case hook is not robust when it looks at this
596           (while (re-search-forward "[ \t]+" header-end t) (replace-match " "))
597
598           (goto-char (point-min))
599           (let (recipient-address-list)
600             (while (re-search-forward " \\([^ ]+\\) " (point-max) t)
601               (backward-char 1)
602               (setq recipient-address-list
603                     (cons (buffer-substring (match-beginning 1) (match-end 1))
604                           recipient-address-list)))
605             recipient-address-list))
606       (kill-buffer smtp-address-buffer))))
607
608 (provide 'smtp)
609
610 ;;; smtp.el ends here