Merge changes made in Emacs trunk.
[gnus] / lisp / proto-stream.el
1 ;;; proto-stream.el --- negotiating TLS, STARTTLS and other connections
2
3 ;; Copyright (C) 2010-2011 Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: network
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;; This library is meant to provide the glue between modules that want
26 ;; to establish a network connection to a server for protocols such as
27 ;; IMAP, NNTP, SMTP and POP3.
28
29 ;; The main problem is that there's more than a couple of interfaces
30 ;; towards doing this.  You have normal, plain connections, which are
31 ;; no trouble at all, but you also have TLS/SSL connections, and you
32 ;; have STARTTLS.  Negotiating this for each protocol can be rather
33 ;; tedious, so this library provides a single entry point, and hides
34 ;; much of the ugliness.
35
36 ;; Usage example:
37
38 ;; (open-protocol-stream
39 ;;  "*nnimap*" buffer address port
40 ;;  :type 'try-starttls
41 ;;  :capability-command "1 CAPABILITY\r\n"
42 ;;  :success " OK "
43 ;;  :starttls-function
44 ;;  (lambda (capabilities)
45 ;;    (if (not (string-match "STARTTLS" capabilities))
46 ;;        nil
47 ;;      "1 STARTTLS\r\n")))
48
49 ;;; Code:
50
51 (require 'tls)
52 (require 'starttls)
53
54 (declare-function gnutls-negotiate "gnutls"
55                   (proc type &optional priority-string trustfiles keyfiles))
56
57 ;;;###autoload
58 (defun open-protocol-stream (name buffer host service &rest parameters)
59   "Open a network stream to HOST, possibly with encryption.
60 Normally, return a network process object; with a non-nil
61 :return-list parameter, return a list instead (see below).
62
63 The first four parameters, NAME, BUFFER, HOST, and SERVICE, have
64 the same meanings as in `open-network-stream'.  The remaining
65 PARAMETERS should be a sequence of keywords and values:
66
67 :type specifies the connection type, one of the following:
68   `default'  -- An ordinary network connection.
69   `try-starttls'
70              -- Begin an ordinary network connection, and try
71                 upgrading it to an encrypted connection via
72                 STARTTLS if both HOST and Emacs support TLS.  If
73                 that fails, keep the unencrypted connection.
74   `starttls' -- Begin an ordinary connection, and try upgrading
75                 it via STARTTLS.  If that fails for any reason,
76                 drop the connection; in this case, the returned
77                 process object is a killed process.
78   `tls' or `ssl' -- A TLS connection.
79   `shell'    -- A shell connection.
80
81 :return-list specifies this function's return value.
82   If omitted or nil, return a process object.  A non-nil means to
83   return (PROC . PROPS), where PROC is a process object and PROPS
84   is a plist of connection properties, with these keywords:
85    :greeting -- the greeting returned by HOST (a string), or nil.
86    :capabilities -- a string representing HOST's capabilities,
87                     or nil if none could be found.
88    :type -- the actual connection type; either `default' for an
89             unencrypted connection, or `tls'.
90
91 :end-of-command specifies a regexp matching the end of a command.
92   If non-nil, it defaults to \"\\n\".
93
94 :success specifies a regexp matching a message indicating a
95   successful STARTTLS negotiation.  For instance, the default
96   should be \"^3\" for an NNTP connection.  If this is not
97   supplied, STARTTLS will always fail.
98
99 :capability-command specifies a command used to query the HOST
100   for its capabilities.  For instance, for IMAP this should be
101   \"1 CAPABILITY\\r\\n\".
102
103 :starttls-function specifies a function for handling STARTTLS.
104   This function should take one parameter, the response to the
105   capability command, and should return the command to switch on
106   STARTTLS if the server supports STARTTLS, and nil otherwise."
107   (let ((type (plist-get parameters :type))
108         (return-list (plist-get parameters :return-list)))
109     (if (and (null return-list) (memq type '(nil default)))
110         ;; The simplest case---no encryption, and no need to report
111         ;; connection properties.  Like `open-network-stream', this
112         ;; doesn't read anything into BUFFER yet.
113         (open-network-stream name buffer host service)
114       ;; For everything else, refer to proto-stream-open-*.
115       (unless (plist-get parameters :end-of-command)
116         (setq parameters
117               (append '(:end-of-command "\r\n") parameters)))
118       (let* ((connection-function
119               (cond
120                ((memq type '(nil default))
121                 'proto-stream-open-default)
122                ((memq type '(try-starttls starttls))
123                 'proto-stream-open-starttls)
124                ((memq type '(tls ssl))
125                 'proto-stream-open-tls)
126                ((eq type 'shell)
127                 'proto-stream-open-shell)
128                (t
129                 (error "Invalid connection type %s" type))))
130              (result (funcall connection-function
131                               name buffer host service parameters)))
132         (if return-list
133             (list (car result)
134                   :greeting     (nth 1 result)
135                   :capabilities (nth 2 result)
136                   :type         (nth 3 result))
137           (car result))))))
138
139 (defun proto-stream-open-default (name buffer host service parameters)
140   (let ((start (with-current-buffer buffer (point)))
141         (stream (open-network-stream name buffer host service)))
142     (list stream
143           (proto-stream-get-response stream start
144                                      (plist-get parameters :end-of-command))
145           nil
146           'default)))
147
148 (defun proto-stream-open-starttls (name buffer host service parameters)
149   (let* ((start (with-current-buffer buffer (point)))
150          ;; This should be `starttls' or `try-starttls'.
151          (type               (plist-get parameters :type))
152          (starttls-function  (plist-get parameters :starttls-function))
153          (success-string     (plist-get parameters :success))
154          (capability-command (plist-get parameters :capability-command))
155          (eoc                (plist-get parameters :end-of-command))
156          ;; Return (STREAM GREETING CAPABILITIES RESULTING-TYPE)
157          (stream (open-network-stream name buffer host service))
158          (greeting (proto-stream-get-response stream start eoc))
159          (capabilities (when capability-command
160                          (proto-stream-command stream
161                                                capability-command eoc)))
162          (resulting-type 'default)
163          starttls-command)
164
165     ;; If we have STARTTLS support, try to upgrade the connection.
166     (when (and (or (fboundp 'open-gnutls-stream)
167                    (executable-find "gnutls-cli"))
168                capabilities success-string starttls-function
169                (setq starttls-command
170                      (funcall starttls-function capabilities)))
171       ;; If using external STARTTLS, drop this connection and start
172       ;; anew with `starttls-open-stream'.
173       (unless (fboundp 'open-gnutls-stream)
174         (delete-process stream)
175         (setq start (with-current-buffer buffer (point-max)))
176         (let* ((starttls-use-gnutls t)
177                (starttls-extra-arguments
178                 (if (not (eq type 'starttls))
179                     ;; For opportunistic TLS upgrades, we don't
180                     ;; really care about the identity of the peer.
181                     (cons "--insecure" starttls-extra-arguments)
182                   starttls-extra-arguments)))
183           (setq stream (starttls-open-stream name buffer host service)))
184         (proto-stream-get-response stream start eoc))
185       (when (string-match success-string
186                           (proto-stream-command stream starttls-command eoc))
187         ;; The server said it was OK to begin STARTTLS negotiations.
188         (if (fboundp 'open-gnutls-stream)
189             (gnutls-negotiate stream nil)
190           (unless (starttls-negotiate stream)
191             (delete-process stream)))
192         (if (memq (process-status stream) '(open run))
193             (setq resulting-type 'tls)
194           ;; We didn't successfully negotiate STARTTLS; if TLS
195           ;; isn't demanded, reopen an unencrypted connection.
196           (when (eq type 'try-starttls)
197             (setq stream (open-network-stream name buffer host service))
198             (proto-stream-get-response stream start eoc)))
199         ;; Re-get the capabilities, which may have now changed.
200         (setq capabilities
201               (proto-stream-command stream capability-command eoc))))
202
203     ;; If TLS is mandatory, close the connection if it's unencrypted.
204     (and (eq type 'starttls)
205          (eq resulting-type 'default)
206          (delete-process stream))
207     ;; Return value:
208     (list stream greeting capabilities resulting-type)))
209
210 (defun proto-stream-command (stream command eoc)
211   (let ((start (with-current-buffer (process-buffer stream) (point-max))))
212     (process-send-string stream command)
213     (proto-stream-get-response stream start eoc)))
214
215 (defun proto-stream-get-response (stream start end-of-command)
216   (with-current-buffer (process-buffer stream)
217     (save-excursion
218       (goto-char start)
219       (while (and (memq (process-status stream)
220                         '(open run))
221                   (not (re-search-forward end-of-command nil t)))
222         (accept-process-output stream 0 50)
223         (goto-char start))
224       (if (= start (point))
225           ;; The process died; return nil.
226           nil
227         ;; Return the data we got back.
228         (buffer-substring start (point))))))
229
230 (defun proto-stream-open-tls (name buffer host service parameters)
231   (with-current-buffer buffer
232     (let ((start (point-max))
233           (stream
234            (funcall (if (fboundp 'open-gnutls-stream)
235                         'open-gnutls-stream
236                       'open-tls-stream)
237                     name buffer host service))
238           (eoc (plist-get parameters :end-of-command)))
239       (if (null stream)
240           (list nil nil nil 'default)
241         ;; If we're using tls.el, we have to delete the output from
242         ;; openssl/gnutls-cli.
243         (unless (fboundp 'open-gnutls-stream)
244           (proto-stream-get-response stream start eoc)
245           (goto-char (point-min))
246           (when (re-search-forward eoc nil t)
247             (goto-char (match-beginning 0))
248             (delete-region (point-min) (line-beginning-position))))
249         (proto-stream-capability-open start stream parameters 'tls)))))
250
251 (defun proto-stream-open-shell (name buffer host service parameters)
252   (require 'format-spec)
253   (proto-stream-capability-open
254    (with-current-buffer buffer (point))
255    (let ((process-connection-type nil))
256      (start-process name buffer shell-file-name
257                     shell-command-switch
258                     (format-spec
259                      (plist-get parameters :shell-command)
260                      (format-spec-make
261                       ?s host
262                       ?p service))))
263    parameters 'default))
264
265 (defun proto-stream-capability-open (start stream parameters stream-type)
266   (let* ((capability-command (plist-get parameters :capability-command))
267          (eoc                (plist-get parameters :end-of-command))
268          (greeting (proto-stream-get-response stream start eoc)))
269     (list stream greeting
270           (and capability-command
271                (proto-stream-command stream capability-command eoc))
272           stream-type)))
273
274 (provide 'proto-stream)
275
276 ;;; proto-stream.el ends here