363ec7300b49b8bb91deb1e16ed4bf1a43e89524
[gnus] / lisp / proto-stream.el
1 ;;; proto-stream.el --- negotiating TLS, STARTTLS and other connections
2 ;; Copyright (C) 2010 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 3, 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., 51 Franklin Street, Fifth Floor,
22 ;; Boston, MA 02110-1301, USA.
23
24 ;;; Commentary:
25
26 ;; This library is meant to provide the glue between modules that want
27 ;; to establish a network connection to a server for protocols such as
28 ;; IMAP, NNTP, SMTP and POP3.
29
30 ;; The main problem is that there's more than a couple of interfaces
31 ;; towards doing this.  You have normal, plain connections, which are
32 ;; no trouble at all, but you also have TLS/SSL connections, and you
33 ;; have STARTTLS.  Negotiating this for each protocol can be rather
34 ;; tedious, so this library provides a single entry point, and hides
35 ;; much of the ugliness.
36
37 ;; Usage example:
38
39 ;; (open-protocol-stream
40 ;;  "*nnimap*" buffer address port
41 ;;  :type 'network
42 ;;  :capability-command "1 CAPABILITY\r\n"
43 ;;  :success " OK "
44 ;;  :starttls-function
45 ;;  (lambda (capabilities)
46 ;;    (if (not (string-match "STARTTLS" capabilities))
47 ;;        nil
48 ;;      "1 STARTTLS\r\n")))
49
50 ;;; Code:
51
52 (eval-when-compile
53   (require 'cl))
54 (require 'tls)
55 (require 'starttls)
56 (require 'format-spec)
57
58 (defcustom proto-stream-always-use-starttls (fboundp 'open-gnutls-stream)
59   "If non-nil, always try to upgrade network connections with STARTTLS."
60   :version "24.1"
61   :type 'boolean
62   :group 'comm)
63
64 (declare-function gnutls-negotiate "gnutls"
65                   (proc type &optional priority-string trustfiles keyfiles))
66
67 ;;;###autoload
68 (defun open-protocol-stream (name buffer host service &rest parameters)
69   "Open a network stream to HOST.
70 The first four parameters have the same meaning as in
71 `open-network-stream'.  The function returns a list where the
72 first element is the stream, the second element is the greeting
73 the server replied with after connecting, and the third element
74 is a string representing the capabilities of the server (if any).
75
76 The PARAMETERS is a keyword list that can have the following
77 values:
78
79 :type -- either `network', `tls', `shell' or `starttls'.  If
80 omitted, the default is `network'.
81
82 :end-of-command -- a regexp saying what the end of a command is.
83 This defaults to \"\\n\".
84
85 :success -- a regexp saying whether the STARTTLS command was
86 successful or not.  For instance, for NNTP this is \"^3\".
87
88 :capability-command -- a string representing the command used to
89 query server for capabilities.  For instance, for IMAP this is
90 \"1 CAPABILITY\\r\\n\".
91
92 :starttls-function -- a function that takes one parameter, which
93 is the response to the capaibility command.  It should return nil
94 if it turns out that the server doesn't support STARTTLS, or the
95 command to switch on STARTTLS otherwise."
96   (let ((type (or (cadr (memq :type parameters)) 'network)))
97     (when (and (eq type 'starttls)
98                (fboundp 'open-gnutls-stream))
99       (setq type 'network))
100     (when (eq type 'ssl)
101       (setq type 'tls))
102     (destructuring-bind (stream greeting capabilities)
103         (funcall (intern (format "proto-stream-open-%s" type) obarray)
104                  name buffer host service parameters)
105       (list (and stream
106                  (memq (process-status stream)
107                        '(open run))
108                  stream)
109             greeting capabilities))))
110
111 (defun proto-stream-open-network (name buffer host service parameters)
112   (let* ((start (with-current-buffer buffer (point)))
113          (stream (open-network-stream name buffer host service))
114          (capability-command (cadr (memq :capability-command parameters)))
115          (eoc (proto-stream-eoc parameters))
116          (type (cadr (memq :type parameters)))
117          (greeting (proto-stream-get-response stream start eoc))
118          success)
119     (if (not capability-command)
120         (list stream greeting nil)
121       (let* ((capabilities
122               (proto-stream-command stream capability-command eoc))
123              (starttls-command
124               (funcall (cadr (memq :starttls-function parameters))
125                        capabilities)))
126         (cond
127           ;; If this server doesn't support STARTTLS, but we have
128           ;; requested it explicitly, then close the connection and
129           ;; return nil.
130          ((or (not starttls-command)
131               (and (not (eq type 'starttls))
132                    (not proto-stream-always-use-starttls)))
133           (if (eq type 'starttls)
134               (progn
135                 (delete-process stream)
136                 nil)
137             ;; Otherwise, just return this plain network connection.
138             (list stream greeting capabilities)))
139          ;; We have some kind of STARTTLS support, so we try to
140          ;; upgrade the connection opportunistically.
141          ((or (fboundp 'open-gnutls-stream)
142               (executable-find "gnutls-cli"))
143           (unless (fboundp 'open-gnutls-stream)
144             (delete-process stream)
145             (setq start (with-current-buffer buffer (point-max)))
146             (let* ((starttls-use-gnutls t)
147                    (starttls-extra-arguments
148                     (if (not (eq type 'starttls))
149                         ;; When doing opportunistic TLS upgrades we
150                         ;; don't really care about the identity of the
151                         ;; peer.
152                         (cons "--insecure" starttls-extra-arguments)
153                       starttls-extra-arguments)))
154               (setq stream (starttls-open-stream name buffer host service)))
155             (proto-stream-get-response stream start eoc))
156           (if (not
157                (string-match
158                 (cadr (memq :success parameters))
159                 (proto-stream-command stream starttls-command eoc)))
160               ;; We got an error back from the STARTTLS command.
161               (progn
162                 (if (eq type 'starttls)
163                     (progn
164                       (delete-process stream)
165                       nil)
166                   (list stream greeting capabilities)))
167             ;; The server said it was OK to start doing STARTTLS negotiations.
168             (if (fboundp 'open-gnutls-stream)
169                 (gnutls-negotiate stream nil)
170               (unless (starttls-negotiate stream)
171                 (delete-process stream)
172                 (setq stream nil)))
173             (when (or (null stream)
174                       (not (memq (process-status stream)
175                                  '(open run))))
176               ;; It didn't successfully negotiate STARTTLS, so we reopen
177               ;; the connection.
178               (setq stream (open-network-stream name buffer host service))
179               (proto-stream-get-response stream start eoc))
180             ;; Re-get the capabilities, since they may have changed
181             ;; after switching to TLS.
182             (list stream greeting
183                   (proto-stream-command stream capability-command eoc))))
184          ;; We don't have STARTTLS support available, but the caller
185          ;; requested a STARTTLS connection, so we give up.
186          ((eq (cadr (memq :type parameters)) 'starttls)
187           (delete-process stream)
188           nil)
189          ;; Fall back on using a plain network stream.
190          (t
191           (list stream greeting capabilities)))))))
192
193 (defun proto-stream-command (stream command eoc)
194   (let ((start (with-current-buffer (process-buffer stream) (point-max))))
195     (process-send-string stream command)
196     (proto-stream-get-response stream start eoc)))
197
198 (defun proto-stream-get-response (stream start end-of-command)
199   (with-current-buffer (process-buffer stream)
200     (save-excursion
201       (goto-char start)
202       (while (and (memq (process-status stream)
203                         '(open run))
204                   (not (re-search-forward end-of-command nil t)))
205         (accept-process-output stream 0 50)
206         (goto-char start))
207       (if (= start (point))
208           ;; The process died; return nil.
209           nil
210         ;; Return the data we got back.
211         (buffer-substring start (point))))))
212
213 (defun proto-stream-open-tls (name buffer host service parameters)
214   (with-current-buffer buffer
215     (let ((start (point-max))
216           (stream
217            (funcall (if (fboundp 'open-gnutls-stream)
218                         'open-gnutls-stream
219                       'open-tls-stream)
220                     name buffer host service)))
221       ;; If we're using tls.el, we have to delete the output from
222       ;; openssl/gnutls-cli.
223       (unless (fboundp 'open-gnutls-stream)
224         (proto-stream-get-response
225          stream start (proto-stream-eoc parameters))
226         (goto-char (point-min))
227         (when (re-search-forward (proto-stream-eoc parameters) nil t)
228           (goto-char (match-beginning 0))
229           (delete-region (point-min) (line-beginning-position))))
230       (proto-stream-capability-open start stream parameters))))
231
232 (defun proto-stream-open-shell (name buffer host service parameters)
233   (proto-stream-capability-open
234    (with-current-buffer buffer (point))
235    (let ((process-connection-type nil))
236      (start-process name buffer shell-file-name
237                     shell-command-switch
238                     (format-spec
239                      (cadr (memq :shell-command parameters))
240                      (format-spec-make
241                       ?s host
242                       ?p service))))
243    parameters))
244
245 (defun proto-stream-capability-open (start stream parameters)
246   (let ((capability-command (cadr (memq :capability-command parameters)))
247         (greeting (proto-stream-get-response
248                    stream start (proto-stream-eoc parameters))))
249     (list stream greeting
250           (and capability-command
251                (proto-stream-command
252                 stream capability-command (proto-stream-eoc parameters))))))
253
254 (defun proto-stream-eoc (parameters)
255   (or (cadr (memq :end-of-command parameters))
256       "\r\n"))
257
258 (provide 'proto-stream)
259
260 ;;; proto-stream.el ends here