Fix XEmacs compilation
[gnus] / lisp / proto-stream.el
1 ;;; proto-stream.el --- negotiating TLS, STARTTLS and other connections
2
3 ;; Copyright (C) 2010-2014 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 'network
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 (autoload 'gnutls-negotiate "gnutls")
55 (autoload 'open-gnutls-stream "gnutls")
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   nil or `network'
69              -- Begin with an ordinary network connection, and if
70                 the parameters :success and :capability-command
71                 are also supplied, try to upgrade to an encrypted
72                 connection via STARTTLS.  Even if that
73                 fails (e.g. if HOST does not support TLS), retain
74                 an unencrypted connection.
75   `plain'    -- An ordinary, unencrypted network connection.
76   `starttls' -- Begin with an ordinary connection, and try
77                 upgrading via STARTTLS.  If that fails for any
78                 reason, drop the connection; in that case the
79                 returned object is a killed process.
80   `tls'      -- A TLS connection.
81   `ssl'      -- Equivalent to `tls'.
82   `shell'    -- A shell connection.
83
84 :return-list specifies this function's return value.
85   If omitted or nil, return a process object.  A non-nil means to
86   return (PROC . PROPS), where PROC is a process object and PROPS
87   is a plist of connection properties, with these keywords:
88    :greeting -- the greeting returned by HOST (a string), or nil.
89    :capabilities -- a string representing HOST's capabilities,
90                     or nil if none could be found.
91    :type -- the resulting connection type; `plain' (unencrypted)
92             or `tls' (TLS-encrypted).
93
94 :end-of-command specifies a regexp matching the end of a command.
95   If non-nil, it defaults to \"\\n\".
96
97 :end-of-capability specifies a regexp matching the end of the
98   response to the command specified for :capability-command.
99   It defaults to the regexp specified for :end-of-command.
100
101 :success specifies a regexp matching a message indicating a
102   successful STARTTLS negotiation.  For instance, the default
103   should be \"^3\" for an NNTP connection.
104
105 :capability-command specifies a command used to query the HOST
106   for its capabilities.  For instance, for IMAP this should be
107   \"1 CAPABILITY\\r\\n\".
108
109 :starttls-function specifies a function for handling STARTTLS.
110   This function should take one parameter, the response to the
111   capability command, and should return the command to switch on
112   STARTTLS if the server supports STARTTLS, and nil otherwise."
113   (let ((type (plist-get parameters :type))
114         (return-list (plist-get parameters :return-list)))
115     (if (and (not return-list)
116              (or (eq type 'plain)
117                  (and (memq type '(nil network))
118                       (not (and (plist-get parameters :success)
119                                 (plist-get parameters :capability-command))))))
120         ;; The simplest case is equivalent to `open-network-stream'.
121         (open-network-stream name buffer host service)
122       ;; For everything else, refer to proto-stream-open-*.
123       (unless (plist-get parameters :end-of-command)
124         (setq parameters (append '(:end-of-command "\r\n") parameters)))
125       (let* ((connection-function
126               (cond
127                ((eq type 'plain) 'proto-stream-open-plain)
128                ((memq type '(nil network starttls))
129                 'proto-stream-open-starttls)
130                ((memq type '(tls ssl)) 'proto-stream-open-tls)
131                ((eq type 'shell) 'proto-stream-open-shell)
132                (t (error "Invalid connection type %s" type))))
133              (result (funcall connection-function
134                               name buffer host service parameters)))
135         (if return-list
136             (list (car result)
137                   :greeting     (nth 1 result)
138                   :capabilities (nth 2 result)
139                   :type         (nth 3 result))
140           (car result))))))
141
142 (defun proto-stream-open-plain (name buffer host service parameters)
143   (let ((start (with-current-buffer buffer (point)))
144         (stream (open-network-stream name buffer host service)))
145     (list stream
146           (proto-stream-get-response stream start
147                                      (plist-get parameters :end-of-command))
148           nil
149           'plain)))
150
151 (defun proto-stream-open-starttls (name buffer host service parameters)
152   (let* ((start (with-current-buffer buffer (point)))
153          (require-tls    (eq (plist-get parameters :type) 'starttls))
154          (starttls-function  (plist-get parameters :starttls-function))
155          (success-string     (plist-get parameters :success))
156          (capability-command (plist-get parameters :capability-command))
157          (eoc                (plist-get parameters :end-of-command))
158          (eo-capa            (or (plist-get parameters :end-of-capability)
159                                  eoc))
160          ;; Return (STREAM GREETING CAPABILITIES RESULTING-TYPE)
161          (stream (open-network-stream name buffer host service))
162          (greeting (proto-stream-get-response stream start eoc))
163          (capabilities (when capability-command
164                          (proto-stream-command stream
165                                                capability-command
166                                                (or eo-capa eoc))))
167          (resulting-type 'plain)
168          (builtin-starttls (and (fboundp 'gnutls-available-p)
169                                 (gnutls-available-p)))
170          starttls-command)
171
172     ;; If we have built-in STARTTLS support, try to upgrade the
173     ;; connection.
174     (when (and (or builtin-starttls
175                    (and require-tls
176                         (executable-find "gnutls-cli")))
177                capabilities success-string starttls-function
178                (setq starttls-command
179                      (funcall starttls-function capabilities)))
180       ;; If using external STARTTLS, drop this connection and start
181       ;; anew with `starttls-open-stream'.
182       (unless builtin-starttls
183         (delete-process stream)
184         (setq start (with-current-buffer buffer (point-max)))
185         (let* ((starttls-use-gnutls t)
186                (starttls-extra-arguments
187                 (if require-tls
188                     starttls-extra-arguments
189                   ;; For opportunistic TLS upgrades, we don't really
190                   ;; care about the identity of the peer.
191                   (cons "--insecure" starttls-extra-arguments))))
192           (setq stream (starttls-open-stream name buffer host service)))
193         (proto-stream-get-response stream start eoc))
194       (when (string-match success-string
195                           (proto-stream-command stream starttls-command eoc))
196         ;; The server said it was OK to begin STARTTLS negotiations.
197         (if builtin-starttls
198             (gnutls-negotiate :process stream :hostname host)
199           (unless (starttls-negotiate stream)
200             (delete-process stream)))
201         (if (memq (process-status stream) '(open run))
202             (setq resulting-type 'tls)
203           ;; We didn't successfully negotiate STARTTLS; if TLS
204           ;; isn't demanded, reopen an unencrypted connection.
205           (unless require-tls
206             (setq stream (open-network-stream name buffer host service))
207             (proto-stream-get-response stream start eoc)))
208         ;; Re-get the capabilities, which may have now changed.
209         (setq capabilities
210               (proto-stream-command stream capability-command eo-capa))))
211
212     ;; If TLS is mandatory, close the connection if it's unencrypted.
213     (and require-tls
214          (eq resulting-type 'plain)
215          (delete-process stream))
216     ;; Return value:
217     (list stream greeting capabilities resulting-type)))
218
219 (defun proto-stream-command (stream command eoc)
220   (let ((start (with-current-buffer (process-buffer stream) (point-max))))
221     (process-send-string stream command)
222     (proto-stream-get-response stream start eoc)))
223
224 (defun proto-stream-get-response (stream start end-of-command)
225   (with-current-buffer (process-buffer stream)
226     (save-excursion
227       (goto-char start)
228       (while (and (memq (process-status stream)
229                         '(open run))
230                   (not (re-search-forward end-of-command nil t)))
231         (accept-process-output stream 0 50)
232         (goto-char start))
233       (if (= start (point))
234           ;; The process died; return nil.
235           nil
236         ;; Return the data we got back.
237         (buffer-substring start (point))))))
238
239 (defun proto-stream-open-tls (name buffer host service parameters)
240   (with-current-buffer buffer
241     (let* ((start (point-max))
242            (builtin-starttls (and (fboundp 'gnutls-available-p)
243                                   (gnutls-available-p)))
244            (stream
245             (funcall (if builtin-starttls
246                          'open-gnutls-stream
247                        'open-tls-stream)
248                      name buffer host service))
249            (eoc (plist-get parameters :end-of-command)))
250       (if (null stream)
251           (list nil nil nil 'plain)
252         ;; If we're using tls.el, we have to delete the output from
253         ;; openssl/gnutls-cli.
254         (unless builtin-starttls
255           (proto-stream-get-response stream start eoc)
256           (goto-char (point-min))
257           (when (re-search-forward eoc nil t)
258             (goto-char (match-beginning 0))
259             (delete-region (point-min) (line-beginning-position))))
260         (proto-stream-capability-open start stream parameters 'tls)))))
261
262 (defun proto-stream-open-shell (name buffer host service parameters)
263   (require 'format-spec)
264   (proto-stream-capability-open
265    (with-current-buffer buffer (point))
266    (let ((process-connection-type nil))
267      (start-process name buffer shell-file-name
268                     shell-command-switch
269                     (format-spec
270                      (plist-get parameters :shell-command)
271                      (format-spec-make
272                       ?s host
273                       ?p service))))
274    parameters 'plain))
275
276 (defun proto-stream-capability-open (start stream parameters stream-type)
277   (let* ((capability-command (plist-get parameters :capability-command))
278          (greeting (proto-stream-get-response
279                     stream start
280                     (plist-get parameters :end-of-command))))
281     (list stream greeting
282           (and capability-command
283                (proto-stream-command
284                 stream capability-command
285                 (or
286                  (plist-get parameters :end-of-capability)
287                  (plist-get parameters :end-of-command))))
288           stream-type)))
289
290 (provide 'proto-stream)
291
292 ;;; proto-stream.el ends here