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