Use built-in TLS support if `gnutls-available-p' is true.
[emacs.git] / lisp / net / network-stream.el
blob94507f165407bfe792f1106b37e94f19a058822c
1 ;;; network-stream.el --- open network processes, possibly with encryption
3 ;; Copyright (C) 2010-2011 Free Software Foundation, Inc.
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: network
8 ;; This file is part of GNU Emacs.
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.
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.
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/>.
23 ;;; Commentary:
25 ;; This library provides the function `open-network-stream', which provides a
26 ;; higher-level interface for opening TCP network processes than the built-in
27 ;; function `make-network-process'. In addition to plain connections, it
28 ;; supports TLS/SSL and STARTTLS connections.
30 ;; Usage example:
32 ;; (open-network-stream
33 ;; "*nnimap*" buffer address port
34 ;; :type 'network
35 ;; :capability-command "1 CAPABILITY\r\n"
36 ;; :success " OK "
37 ;; :starttls-function
38 ;; (lambda (capabilities)
39 ;; (if (not (string-match "STARTTLS" capabilities))
40 ;; nil
41 ;; "1 STARTTLS\r\n")))
43 ;;; Code:
45 (require 'tls)
46 (require 'starttls)
47 (require 'auth-source)
49 (autoload 'gnutls-negotiate "gnutls")
50 (autoload 'open-gnutls-stream "gnutls")
52 ;;;###autoload
53 (defun open-network-stream (name buffer host service &rest parameters)
54 "Open a TCP connection to HOST, optionally with encryption.
55 Normally, return a network process object; with a non-nil
56 :return-list parameter, return a list instead (see below).
57 Input and output work as for subprocesses; `delete-process'
58 closes it.
60 NAME is the name for the process. It is modified if necessary to
61 make it unique.
62 BUFFER is a buffer or buffer name to associate with the process.
63 Process output goes at end of that buffer. BUFFER may be nil,
64 meaning that the process is not associated with any buffer.
65 HOST is the name or IP address of the host to connect to.
66 SERVICE is the name of the service desired, or an integer specifying
67 a port number to connect to.
69 The remaining PARAMETERS should be a sequence of keywords and
70 values:
72 :type specifies the connection type, one of the following:
73 nil or `network'
74 -- Begin with an ordinary network connection, and if
75 the parameters :success and :capability-command
76 are also supplied, try to upgrade to an encrypted
77 connection via STARTTLS. Even if that
78 fails (e.g. if HOST does not support TLS), retain
79 an unencrypted connection.
80 `plain' -- An ordinary, unencrypted network connection.
81 `starttls' -- Begin with an ordinary connection, and try
82 upgrading via STARTTLS. If that fails for any
83 reason, drop the connection; in that case the
84 returned object is a killed process.
85 `tls' -- A TLS connection.
86 `ssl' -- Equivalent to `tls'.
87 `shell' -- A shell connection.
89 :return-list specifies this function's return value.
90 If omitted or nil, return a process object. A non-nil means to
91 return (PROC . PROPS), where PROC is a process object and PROPS
92 is a plist of connection properties, with these keywords:
93 :greeting -- the greeting returned by HOST (a string), or nil.
94 :capabilities -- a string representing HOST's capabilities,
95 or nil if none could be found.
96 :type -- the resulting connection type; `plain' (unencrypted)
97 or `tls' (TLS-encrypted).
99 :end-of-command specifies a regexp matching the end of a command.
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.
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\".
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.
114 :always-query-capabilies says whether to query the server for
115 capabilities, even if we're doing a `plain' network connection.
117 :client-certificate should either be a list where the first
118 element is the certificate key file name, and the second
119 element is the certificate file name itself, or `t', which
120 means that `auth-source' will be queried for the key and the
121 certificate. This parameter will only be used when doing TLS
122 or STARTTLS connections.
124 If :use-starttls-if-possible is non-nil, do opportunistic
125 STARTTLS upgrades even if Emacs doesn't have built-in TLS
126 functionality.
128 :nowait is a boolean that says the connection should be made
129 asynchronously, if possible."
130 (unless (featurep 'make-network-process)
131 (error "Emacs was compiled without networking support"))
132 (let ((type (plist-get parameters :type))
133 (return-list (plist-get parameters :return-list)))
134 (if (and (not return-list)
135 (or (eq type 'plain)
136 (and (memq type '(nil network))
137 (not (and (plist-get parameters :success)
138 (plist-get parameters :capability-command))))))
139 ;; The simplest case: wrapper around `make-network-process'.
140 (make-network-process :name name :buffer buffer
141 :host host :service service
142 :nowait (plist-get parameters :nowait))
143 (let ((work-buffer (or buffer
144 (generate-new-buffer " *stream buffer*")))
145 (fun (cond ((and (eq type 'plain)
146 (not (plist-get parameters
147 :always-query-capabilities)))
148 'network-stream-open-plain)
149 ((memq type '(nil network starttls plain))
150 'network-stream-open-starttls)
151 ((memq type '(tls ssl)) 'network-stream-open-tls)
152 ((eq type 'shell) 'network-stream-open-shell)
153 (t (error "Invalid connection type %s" type))))
154 result)
155 (unwind-protect
156 (setq result (funcall fun name work-buffer host service parameters))
157 (unless buffer
158 (and (processp (car result))
159 (set-process-buffer (car result) nil))
160 (kill-buffer work-buffer)))
161 (if return-list
162 (list (car result)
163 :greeting (nth 1 result)
164 :capabilities (nth 2 result)
165 :type (nth 3 result))
166 (car result))))))
168 (defun network-stream-certificate (host service parameters)
169 (let ((spec (plist-get :client-certificate parameters)))
170 (cond
171 ((listp spec)
172 ;; Either nil or a list with a key/certificate pair.
173 spec)
174 ((eq spec t)
175 (let* ((auth-info
176 (car (auth-source-search :max 1
177 :host host
178 :port service)))
179 (key (plist-get auth-info :key))
180 (cert (plist-get auth-info :cert)))
181 (and key cert
182 (list key cert)))))))
184 ;;;###autoload
185 (defalias 'open-protocol-stream 'open-network-stream)
187 (defun network-stream-open-plain (name buffer host service parameters)
188 (let ((start (with-current-buffer buffer (point)))
189 (stream (make-network-process :name name :buffer buffer
190 :host host :service service
191 :nowait (plist-get parameters :nowait))))
192 (list stream
193 (network-stream-get-response stream start
194 (plist-get parameters :end-of-command))
196 'plain)))
198 (defun network-stream-open-starttls (name buffer host service parameters)
199 (let* ((start (with-current-buffer buffer (point)))
200 (require-tls (eq (plist-get parameters :type) 'starttls))
201 (starttls-function (plist-get parameters :starttls-function))
202 (success-string (plist-get parameters :success))
203 (capability-command (plist-get parameters :capability-command))
204 (eoc (plist-get parameters :end-of-command))
205 ;; Return (STREAM GREETING CAPABILITIES RESULTING-TYPE)
206 (stream (make-network-process :name name :buffer buffer
207 :host host :service service))
208 (greeting (network-stream-get-response stream start eoc))
209 (capabilities (network-stream-command stream capability-command eoc))
210 (resulting-type 'plain)
211 (builtin-starttls (and (fboundp 'gnutls-available-p)
212 (gnutls-available-p)))
213 starttls-command)
215 ;; If we have built-in STARTTLS support, try to upgrade the
216 ;; connection.
217 (when (and (or builtin-starttls
218 (and (or require-tls
219 (plist-get parameters :use-starttls-if-possible))
220 (executable-find "gnutls-cli")))
221 capabilities success-string starttls-function
222 (setq starttls-command
223 (funcall starttls-function capabilities))
224 (not (eq (plist-get parameters :type) 'plain)))
225 ;; If using external STARTTLS, drop this connection and start
226 ;; anew with `starttls-open-stream'.
227 (unless builtin-starttls
228 (delete-process stream)
229 (setq start (with-current-buffer buffer (point-max)))
230 (let* ((starttls-use-gnutls t)
231 (starttls-extra-arguments
232 (if require-tls
233 starttls-extra-arguments
234 ;; For opportunistic TLS upgrades, we don't really
235 ;; care about the identity of the peer.
236 (cons "--insecure" starttls-extra-arguments)))
237 (cert (network-stream-certificate host service parameters)))
238 ;; There are client certificates requested, so add them to
239 ;; the command line.
240 (when cert
241 (setq starttls-extra-arguments
242 (nconc (list "--x509keyfile" (expand-file-name (nth 0 cert))
243 "--x509certfile" (expand-file-name (nth 1 cert)))
244 starttls-extra-arguments)))
245 (setq stream (starttls-open-stream name buffer host service)))
246 (network-stream-get-response stream start eoc))
247 ;; Requery capabilities for protocols that require it; i.e.,
248 ;; EHLO for SMTP.
249 (when (plist-get parameters :always-query-capabilities)
250 (network-stream-command stream capability-command eoc))
251 (when (string-match success-string
252 (network-stream-command stream starttls-command eoc))
253 ;; The server said it was OK to begin STARTTLS negotiations.
254 (if builtin-starttls
255 (let ((cert (network-stream-certificate host service parameters)))
256 (gnutls-negotiate :process stream :hostname host
257 :keylist (and cert (list cert))))
258 (unless (starttls-negotiate stream)
259 (delete-process stream)))
260 (if (memq (process-status stream) '(open run))
261 (setq resulting-type 'tls)
262 ;; We didn't successfully negotiate STARTTLS; if TLS
263 ;; isn't demanded, reopen an unencrypted connection.
264 (unless require-tls
265 (setq stream
266 (make-network-process :name name :buffer buffer
267 :host host :service service))
268 (network-stream-get-response stream start eoc)))
269 ;; Re-get the capabilities, which may have now changed.
270 (setq capabilities
271 (network-stream-command stream capability-command eoc))))
273 ;; If TLS is mandatory, close the connection if it's unencrypted.
274 (and require-tls
275 (eq resulting-type 'plain)
276 (delete-process stream))
277 ;; Return value:
278 (list stream greeting capabilities resulting-type)))
280 (defun network-stream-command (stream command eoc)
281 (when command
282 (let ((start (with-current-buffer (process-buffer stream) (point-max))))
283 (process-send-string stream command)
284 (network-stream-get-response stream start eoc))))
286 (defun network-stream-get-response (stream start end-of-command)
287 (when end-of-command
288 (with-current-buffer (process-buffer stream)
289 (save-excursion
290 (goto-char start)
291 (while (and (memq (process-status stream) '(open run))
292 (not (re-search-forward end-of-command nil t)))
293 (accept-process-output stream 0 50)
294 (goto-char start))
295 ;; Return the data we got back, or nil if the process died.
296 (unless (= start (point))
297 (buffer-substring start (point)))))))
299 (defun network-stream-open-tls (name buffer host service parameters)
300 (with-current-buffer buffer
301 (let* ((start (point-max))
302 (use-builtin-gnutls (and (fboundp 'gnutls-available-p)
303 (gnutls-available-p)))
304 (stream
305 (funcall (if use-builtin-gnutls
306 'open-gnutls-stream
307 'open-tls-stream)
308 name buffer host service))
309 (eoc (plist-get parameters :end-of-command)))
310 (if (null stream)
311 (list nil nil nil 'plain)
312 ;; If we're using tls.el, we have to delete the output from
313 ;; openssl/gnutls-cli.
314 (when (and (null use-builtin-gnutls)
315 eoc)
316 (network-stream-get-response stream start eoc)
317 (goto-char (point-min))
318 (when (re-search-forward eoc nil t)
319 (goto-char (match-beginning 0))
320 (delete-region (point-min) (line-beginning-position))))
321 (let* ((capability-command (plist-get parameters :capability-command)))
322 (list stream
323 (network-stream-get-response stream start eoc)
324 (network-stream-command stream capability-command eoc)
325 'tls))))))
327 (defun network-stream-open-shell (name buffer host service parameters)
328 (require 'format-spec)
329 (let* ((capability-command (plist-get parameters :capability-command))
330 (eoc (plist-get parameters :end-of-command))
331 (start (with-current-buffer buffer (point)))
332 (stream (let ((process-connection-type nil))
333 (start-process name buffer shell-file-name
334 shell-command-switch
335 (format-spec
336 (plist-get parameters :shell-command)
337 (format-spec-make
338 ?s host
339 ?p service))))))
340 (list stream
341 (network-stream-get-response stream start eoc)
342 (network-stream-command stream capability-command eoc)
343 'plain)))
345 (provide 'network-stream)
347 ;;; network-stream.el ends here