]> code.delx.au - gnu-emacs/blob - lisp/net/network-stream.el
* lisp/simple.el (shell-command): Add save-match-data comment
[gnu-emacs] / lisp / net / network-stream.el
1 ;;; network-stream.el --- open network processes, possibly with encryption
2
3 ;; Copyright (C) 2010-2016 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 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.
29
30 ;; Usage example:
31
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")))
42
43 ;;; Code:
44
45 (require 'tls)
46 (require 'starttls)
47 (require 'auth-source)
48 (require 'nsm)
49 (require 'puny)
50
51 (autoload 'gnutls-negotiate "gnutls")
52 (autoload 'open-gnutls-stream "gnutls")
53
54 ;;;###autoload
55 (defun open-network-stream (name buffer host service &rest parameters)
56 "Open a TCP connection to HOST, optionally with encryption.
57 Normally, return a network process object; with a non-nil
58 :return-list parameter, return a list instead (see below).
59 Input and output work as for subprocesses; `delete-process'
60 closes it.
61
62 NAME is the name for the process. It is modified if necessary to
63 make it unique.
64 BUFFER is a buffer or buffer name to associate with the process.
65 Process output goes at end of that buffer. BUFFER may be nil,
66 meaning that the process is not associated with any buffer.
67 HOST is the name or IP address of the host to connect to.
68 SERVICE is the name of the service desired, or an integer or
69 integer string specifying a port number to connect to.
70
71 The remaining PARAMETERS should be a sequence of keywords and
72 values:
73
74 :type specifies the connection type, one of the following:
75 nil or `network'
76 -- Begin with an ordinary network connection, and if
77 the parameters :success and :capability-command
78 are also supplied, try to upgrade to an encrypted
79 connection via STARTTLS. Even if that
80 fails (e.g. if HOST does not support TLS), retain
81 an unencrypted connection.
82 `plain' -- An ordinary, unencrypted network connection.
83 `starttls' -- Begin with an ordinary connection, and try
84 upgrading via STARTTLS. If that fails for any
85 reason, drop the connection; in that case the
86 returned object is a killed process.
87 `tls' -- A TLS connection.
88 `ssl' -- Equivalent to `tls'.
89 `shell' -- A shell connection.
90
91 :return-list specifies this function's return value.
92 If omitted or nil, return a process object. A non-nil means to
93 return (PROC . PROPS), where PROC is a process object and PROPS
94 is a plist of connection properties, with these keywords:
95 :greeting -- the greeting returned by HOST (a string), or nil.
96 :capabilities -- a string representing HOST's capabilities,
97 or nil if none could be found.
98 :type -- the resulting connection type; `plain' (unencrypted)
99 or `tls' (TLS-encrypted).
100
101 :end-of-command specifies a regexp matching the end of a command.
102
103 :end-of-capability specifies a regexp matching the end of the
104 response to the command specified for :capability-command.
105 It defaults to the regexp specified for :end-of-command.
106
107 :success specifies a regexp matching a message indicating a
108 successful STARTTLS negotiation. For instance, the default
109 should be \"^3\" for an NNTP connection.
110
111 :capability-command specifies a command used to query the HOST
112 for its capabilities. For instance, for IMAP this should be
113 \"1 CAPABILITY\\r\\n\".
114
115 :starttls-function specifies a function for handling STARTTLS.
116 This function should take one parameter, the response to the
117 capability command, and should return the command to switch on
118 STARTTLS if the server supports STARTTLS, and nil otherwise.
119
120 :always-query-capabilities says whether to query the server for
121 capabilities, even if we're doing a `plain' network connection.
122
123 :client-certificate should either be a list where the first
124 element is the certificate key file name, and the second
125 element is the certificate file name itself, or t, which
126 means that `auth-source' will be queried for the key and the
127 certificate. This parameter will only be used when doing TLS
128 or STARTTLS connections.
129
130 :use-starttls-if-possible is a boolean that says to do opportunistic
131 STARTTLS upgrades even if Emacs doesn't have built-in TLS functionality.
132
133 :warn-unless-encrypted is a boolean which, if :return-list is
134 non-nil, is used warn the user if the connection isn't encrypted.
135
136 :nogreeting is a boolean that can be used to inhibit waiting for
137 a greeting from the server.
138
139 :nowait, if non-nil, says the connection should be made
140 asynchronously, if possible.
141
142 :tls-parameters is a list that should be supplied if you're
143 opening a TLS connection. The first element is the TLS
144 type (either `gnutls-x509pki' or `gnutls-anon'), and the
145 remaining elements should be a keyword list accepted by
146 gnutls-boot (as returned by `gnutls-boot-parameters')."
147 (unless (featurep 'make-network-process)
148 (error "Emacs was compiled without networking support"))
149 (let ((type (plist-get parameters :type))
150 (return-list (plist-get parameters :return-list)))
151 (if (and (not return-list)
152 (or (eq type 'plain)
153 (and (memq type '(nil network))
154 (not (and (plist-get parameters :success)
155 (plist-get parameters :capability-command))))))
156 ;; The simplest case: wrapper around `make-network-process'.
157 (make-network-process :name name :buffer buffer
158 :host (puny-encode-domain host) :service service
159 :nowait (plist-get parameters :nowait)
160 :tls-parameters
161 (plist-get parameters :tls-parameters))
162 (let ((work-buffer (or buffer
163 (generate-new-buffer " *stream buffer*")))
164 (fun (cond ((and (eq type 'plain)
165 (not (plist-get parameters
166 :always-query-capabilities)))
167 'network-stream-open-plain)
168 ((memq type '(nil network starttls plain))
169 'network-stream-open-starttls)
170 ((memq type '(tls ssl)) 'network-stream-open-tls)
171 ((eq type 'shell) 'network-stream-open-shell)
172 (t (error "Invalid connection type %s" type))))
173 result)
174 (unwind-protect
175 (setq result (funcall fun name work-buffer host service parameters))
176 (unless buffer
177 (and (processp (car result))
178 (set-process-buffer (car result) nil))
179 (kill-buffer work-buffer)))
180 (if return-list
181 (list (car result)
182 :greeting (nth 1 result)
183 :capabilities (nth 2 result)
184 :type (nth 3 result)
185 :error (nth 4 result))
186 (car result))))))
187
188 (defun network-stream-certificate (host service parameters)
189 (let ((spec (plist-get :client-certificate parameters)))
190 (cond
191 ((listp spec)
192 ;; Either nil or a list with a key/certificate pair.
193 spec)
194 ((eq spec t)
195 (let* ((auth-info
196 (car (auth-source-search :max 1
197 :host host
198 :port service)))
199 (key (plist-get auth-info :key))
200 (cert (plist-get auth-info :cert)))
201 (and key cert
202 (list key cert)))))))
203
204 ;;;###autoload
205 (defalias 'open-protocol-stream 'open-network-stream)
206 (define-obsolete-function-alias 'open-protocol-stream 'open-network-stream
207 "25.2")
208
209 (defun network-stream-open-plain (name buffer host service parameters)
210 (let ((start (with-current-buffer buffer (point)))
211 (stream (make-network-process :name name :buffer buffer
212 :host (puny-encode-domain host)
213 :service service
214 :nowait (plist-get parameters :nowait))))
215 (when (plist-get parameters :warn-unless-encrypted)
216 (setq stream (nsm-verify-connection stream host service nil t)))
217 (list stream
218 (network-stream-get-response stream start
219 (plist-get parameters :end-of-command))
220 nil
221 'plain)))
222
223 (defun network-stream-open-starttls (name buffer host service parameters)
224 (let* ((start (with-current-buffer buffer (point)))
225 (require-tls (eq (plist-get parameters :type) 'starttls))
226 (starttls-function (plist-get parameters :starttls-function))
227 (success-string (plist-get parameters :success))
228 (capability-command (plist-get parameters :capability-command))
229 (eoc (plist-get parameters :end-of-command))
230 (eo-capa (or (plist-get parameters :end-of-capability)
231 eoc))
232 ;; Return (STREAM GREETING CAPABILITIES RESULTING-TYPE)
233 (stream (make-network-process :name name :buffer buffer
234 :host (puny-encode-domain host)
235 :service service))
236 (greeting (and (not (plist-get parameters :nogreeting))
237 (network-stream-get-response stream start eoc)))
238 (capabilities (network-stream-command stream capability-command
239 eo-capa))
240 (resulting-type 'plain)
241 starttls-available starttls-command error)
242
243 ;; First check whether the server supports STARTTLS at all.
244 (when (and capabilities success-string starttls-function)
245 (setq starttls-command
246 (funcall starttls-function capabilities)))
247 ;; If we have built-in STARTTLS support, try to upgrade the
248 ;; connection.
249 (when (and starttls-command
250 (setq starttls-available
251 (or (gnutls-available-p)
252 (and (or require-tls
253 (plist-get parameters :use-starttls-if-possible))
254 (starttls-available-p))))
255 (not (eq (plist-get parameters :type) 'plain)))
256 ;; If using external STARTTLS, drop this connection and start
257 ;; anew with `starttls-open-stream'.
258 (unless (gnutls-available-p)
259 (delete-process stream)
260 (setq start (with-current-buffer buffer (point-max)))
261 (let* ((starttls-extra-arguments
262 (if (or require-tls
263 (member "--insecure" starttls-extra-arguments))
264 starttls-extra-arguments
265 ;; For opportunistic TLS upgrades, we don't really
266 ;; care about the identity of the peer.
267 (cons "--insecure" starttls-extra-arguments)))
268 (starttls-extra-args starttls-extra-args)
269 (cert (network-stream-certificate host service parameters)))
270 ;; There are client certificates requested, so add them to
271 ;; the command line.
272 (when cert
273 (setq starttls-extra-arguments
274 (nconc (list "--x509keyfile" (expand-file-name (nth 0 cert))
275 "--x509certfile" (expand-file-name (nth 1 cert)))
276 starttls-extra-arguments)
277 starttls-extra-args
278 (nconc (list "--key-file" (expand-file-name (nth 0 cert))
279 "--cert-file" (expand-file-name (nth 1 cert)))
280 starttls-extra-args)))
281 (setq stream (starttls-open-stream name buffer host service)))
282 (network-stream-get-response stream start eoc)
283 ;; Requery capabilities for protocols that require it; i.e.,
284 ;; EHLO for SMTP.
285 (when (plist-get parameters :always-query-capabilities)
286 (network-stream-command stream capability-command eo-capa)))
287 (when (let ((response
288 (network-stream-command stream starttls-command eoc)))
289 (and response (string-match success-string response)))
290 ;; The server said it was OK to begin STARTTLS negotiations.
291 (if (gnutls-available-p)
292 (let ((cert (network-stream-certificate host service parameters)))
293 (condition-case nil
294 (gnutls-negotiate :process stream :hostname host
295 :keylist (and cert (list cert)))
296 ;; If we get a gnutls-specific error (for instance if
297 ;; the certificate the server gives us is completely
298 ;; syntactically invalid), then close the connection
299 ;; and possibly (further down) try to create a
300 ;; non-encrypted connection.
301 (gnutls-error
302 (delete-process stream))))
303 (unless (starttls-negotiate stream)
304 (delete-process stream)))
305 (if (memq (process-status stream) '(open run))
306 (setq resulting-type 'tls)
307 ;; We didn't successfully negotiate STARTTLS; if TLS
308 ;; isn't demanded, reopen an unencrypted connection.
309 (unless require-tls
310 (setq stream
311 (make-network-process :name name :buffer buffer
312 :host (puny-encode-domain host)
313 :service service))
314 (network-stream-get-response stream start eoc)))
315 (unless (process-live-p stream)
316 (error "Unable to negotiate a TLS connection with %s/%s"
317 host service))
318 ;; Re-get the capabilities, which may have now changed.
319 (setq capabilities
320 (network-stream-command stream capability-command eo-capa))))
321
322 ;; If TLS is mandatory, close the connection if it's unencrypted.
323 (when (and require-tls
324 ;; ... but Emacs wasn't able to -- either no built-in
325 ;; support, or no gnutls-cli installed.
326 (eq resulting-type 'plain))
327 (setq error
328 (if (or (null starttls-command)
329 starttls-available)
330 "Server does not support TLS"
331 ;; See `starttls-available-p'. If this predicate
332 ;; changes to allow running under Windows, the error
333 ;; message below should be amended.
334 (if (memq system-type '(windows-nt ms-dos))
335 (concat "Emacs does not support TLS")
336 (concat "Emacs does not support TLS, and no external `"
337 (if starttls-use-gnutls
338 starttls-gnutls-program
339 starttls-program)
340 "' program was found"))))
341 (delete-process stream)
342 (setq stream nil))
343 ;; Check certificate validity etc.
344 (when (gnutls-available-p)
345 (setq stream (nsm-verify-connection
346 stream host service
347 (eq resulting-type 'tls)
348 (plist-get parameters :warn-unless-encrypted))))
349 ;; Return value:
350 (list stream greeting capabilities resulting-type error)))
351
352 (defun network-stream-command (stream command eoc)
353 (when command
354 (let ((start (with-current-buffer (process-buffer stream) (point-max))))
355 (process-send-string stream command)
356 (network-stream-get-response stream start eoc))))
357
358 (defun network-stream-get-response (stream start end-of-command)
359 (when end-of-command
360 (with-current-buffer (process-buffer stream)
361 (save-excursion
362 (goto-char start)
363 (while (and (memq (process-status stream) '(open run))
364 (not (re-search-forward end-of-command nil t)))
365 (accept-process-output stream 0 50)
366 (goto-char start))
367 ;; Return the data we got back, or nil if the process died.
368 (unless (= start (point))
369 (buffer-substring start (point)))))))
370
371 (defun network-stream-open-tls (name buffer host service parameters)
372 (with-current-buffer buffer
373 (let* ((start (point-max))
374 (stream
375 (if (gnutls-available-p)
376 (open-gnutls-stream name buffer host service
377 (plist-get parameters :nowait))
378 (open-tls-stream name buffer host service)))
379 (eoc (plist-get parameters :end-of-command)))
380 (if (plist-get parameters :nowait)
381 (list stream nil nil 'tls)
382 ;; Check certificate validity etc.
383 (when (and (gnutls-available-p) stream)
384 (setq stream (nsm-verify-connection stream host service)))
385 (if (null stream)
386 (list nil nil nil 'plain)
387 ;; If we're using tls.el, we have to delete the output from
388 ;; openssl/gnutls-cli.
389 (when (and (not (gnutls-available-p))
390 eoc)
391 (network-stream-get-response stream start eoc)
392 (goto-char (point-min))
393 (when (re-search-forward eoc nil t)
394 (goto-char (match-beginning 0))
395 (delete-region (point-min) (line-beginning-position))))
396 (let ((capability-command (plist-get parameters :capability-command))
397 (eo-capa (or (plist-get parameters :end-of-capability)
398 eoc)))
399 (list stream
400 (network-stream-get-response stream start eoc)
401 (network-stream-command stream capability-command eo-capa)
402 'tls)))))))
403
404 (defun network-stream-open-shell (name buffer host service parameters)
405 (require 'format-spec)
406 (let* ((capability-command (plist-get parameters :capability-command))
407 (eoc (plist-get parameters :end-of-command))
408 (start (with-current-buffer buffer (point)))
409 (stream (let ((process-connection-type nil))
410 (start-process name buffer shell-file-name
411 shell-command-switch
412 (format-spec
413 (plist-get parameters :shell-command)
414 (format-spec-make
415 ?s host
416 ?p service))))))
417 (list stream
418 (network-stream-get-response stream start eoc)
419 (network-stream-command stream capability-command
420 (or (plist-get parameters :end-of-capability)
421 eoc))
422 'plain)))
423
424 (provide 'network-stream)
425
426 ;;; network-stream.el ends here