]> code.delx.au - gnu-emacs/blob - lisp/net/network-stream.el
; Merge from origin/emacs-25
[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 specifying
69 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 is a boolean that says the connection should be made
140 asynchronously, if possible."
141 (unless (featurep 'make-network-process)
142 (error "Emacs was compiled without networking support"))
143 (let ((type (plist-get parameters :type))
144 (return-list (plist-get parameters :return-list)))
145 (if (and (not return-list)
146 (or (eq type 'plain)
147 (and (memq type '(nil network))
148 (not (and (plist-get parameters :success)
149 (plist-get parameters :capability-command))))))
150 ;; The simplest case: wrapper around `make-network-process'.
151 (make-network-process :name name :buffer buffer
152 :host (puny-encode-domain host) :service service
153 :nowait (plist-get parameters :nowait))
154 (let ((work-buffer (or buffer
155 (generate-new-buffer " *stream buffer*")))
156 (fun (cond ((and (eq type 'plain)
157 (not (plist-get parameters
158 :always-query-capabilities)))
159 'network-stream-open-plain)
160 ((memq type '(nil network starttls plain))
161 'network-stream-open-starttls)
162 ((memq type '(tls ssl)) 'network-stream-open-tls)
163 ((eq type 'shell) 'network-stream-open-shell)
164 (t (error "Invalid connection type %s" type))))
165 result)
166 (unwind-protect
167 (setq result (funcall fun name work-buffer host service parameters))
168 (unless buffer
169 (and (processp (car result))
170 (set-process-buffer (car result) nil))
171 (kill-buffer work-buffer)))
172 (if return-list
173 (list (car result)
174 :greeting (nth 1 result)
175 :capabilities (nth 2 result)
176 :type (nth 3 result)
177 :error (nth 4 result))
178 (car result))))))
179
180 (defun network-stream-certificate (host service parameters)
181 (let ((spec (plist-get :client-certificate parameters)))
182 (cond
183 ((listp spec)
184 ;; Either nil or a list with a key/certificate pair.
185 spec)
186 ((eq spec t)
187 (let* ((auth-info
188 (car (auth-source-search :max 1
189 :host host
190 :port service)))
191 (key (plist-get auth-info :key))
192 (cert (plist-get auth-info :cert)))
193 (and key cert
194 (list key cert)))))))
195
196 ;;;###autoload
197 (defalias 'open-protocol-stream 'open-network-stream)
198 (define-obsolete-function-alias 'open-protocol-stream 'open-network-stream
199 "25.2")
200
201 (defun network-stream-open-plain (name buffer host service parameters)
202 (let ((start (with-current-buffer buffer (point)))
203 (stream (make-network-process :name name :buffer buffer
204 :host (puny-encode-domain host)
205 :service service
206 :nowait (plist-get parameters :nowait))))
207 (when (plist-get parameters :warn-unless-encrypted)
208 (setq stream (nsm-verify-connection stream host service nil t)))
209 (list stream
210 (network-stream-get-response stream start
211 (plist-get parameters :end-of-command))
212 nil
213 'plain)))
214
215 (defun network-stream-open-starttls (name buffer host service parameters)
216 (let* ((start (with-current-buffer buffer (point)))
217 (require-tls (eq (plist-get parameters :type) 'starttls))
218 (starttls-function (plist-get parameters :starttls-function))
219 (success-string (plist-get parameters :success))
220 (capability-command (plist-get parameters :capability-command))
221 (eoc (plist-get parameters :end-of-command))
222 (eo-capa (or (plist-get parameters :end-of-capability)
223 eoc))
224 ;; Return (STREAM GREETING CAPABILITIES RESULTING-TYPE)
225 (stream (make-network-process :name name :buffer buffer
226 :host (puny-encode-domain host)
227 :service service))
228 (greeting (and (not (plist-get parameters :nogreeting))
229 (network-stream-get-response stream start eoc)))
230 (capabilities (network-stream-command stream capability-command
231 eo-capa))
232 (resulting-type 'plain)
233 starttls-available starttls-command error)
234
235 ;; First check whether the server supports STARTTLS at all.
236 (when (and capabilities success-string starttls-function)
237 (setq starttls-command
238 (funcall starttls-function capabilities)))
239 ;; If we have built-in STARTTLS support, try to upgrade the
240 ;; connection.
241 (when (and starttls-command
242 (setq starttls-available
243 (or (gnutls-available-p)
244 (and (or require-tls
245 (plist-get parameters :use-starttls-if-possible))
246 (starttls-available-p))))
247 (not (eq (plist-get parameters :type) 'plain)))
248 ;; If using external STARTTLS, drop this connection and start
249 ;; anew with `starttls-open-stream'.
250 (unless (gnutls-available-p)
251 (delete-process stream)
252 (setq start (with-current-buffer buffer (point-max)))
253 (let* ((starttls-extra-arguments
254 (if (or require-tls
255 (member "--insecure" starttls-extra-arguments))
256 starttls-extra-arguments
257 ;; For opportunistic TLS upgrades, we don't really
258 ;; care about the identity of the peer.
259 (cons "--insecure" starttls-extra-arguments)))
260 (starttls-extra-args starttls-extra-args)
261 (cert (network-stream-certificate host service parameters)))
262 ;; There are client certificates requested, so add them to
263 ;; the command line.
264 (when cert
265 (setq starttls-extra-arguments
266 (nconc (list "--x509keyfile" (expand-file-name (nth 0 cert))
267 "--x509certfile" (expand-file-name (nth 1 cert)))
268 starttls-extra-arguments)
269 starttls-extra-args
270 (nconc (list "--key-file" (expand-file-name (nth 0 cert))
271 "--cert-file" (expand-file-name (nth 1 cert)))
272 starttls-extra-args)))
273 (setq stream (starttls-open-stream name buffer host service)))
274 (network-stream-get-response stream start eoc)
275 ;; Requery capabilities for protocols that require it; i.e.,
276 ;; EHLO for SMTP.
277 (when (plist-get parameters :always-query-capabilities)
278 (network-stream-command stream capability-command eo-capa)))
279 (when (let ((response
280 (network-stream-command stream starttls-command eoc)))
281 (and response (string-match success-string response)))
282 ;; The server said it was OK to begin STARTTLS negotiations.
283 (if (gnutls-available-p)
284 (let ((cert (network-stream-certificate host service parameters)))
285 (condition-case nil
286 (gnutls-negotiate :process stream :hostname host
287 :keylist (and cert (list cert)))
288 ;; If we get a gnutls-specific error (for instance if
289 ;; the certificate the server gives us is completely
290 ;; syntactically invalid), then close the connection
291 ;; and possibly (further down) try to create a
292 ;; non-encrypted connection.
293 (gnutls-error
294 (delete-process stream))))
295 (unless (starttls-negotiate stream)
296 (delete-process stream)))
297 (if (memq (process-status stream) '(open run))
298 (setq resulting-type 'tls)
299 ;; We didn't successfully negotiate STARTTLS; if TLS
300 ;; isn't demanded, reopen an unencrypted connection.
301 (unless require-tls
302 (setq stream
303 (make-network-process :name name :buffer buffer
304 :host (puny-encode-domain host)
305 :service service))
306 (network-stream-get-response stream start eoc)))
307 ;; Re-get the capabilities, which may have now changed.
308 (setq capabilities
309 (network-stream-command stream capability-command eo-capa))))
310
311 ;; If TLS is mandatory, close the connection if it's unencrypted.
312 (when (and require-tls
313 ;; ... but Emacs wasn't able to -- either no built-in
314 ;; support, or no gnutls-cli installed.
315 (eq resulting-type 'plain))
316 (setq error
317 (if (or (null starttls-command)
318 starttls-available)
319 "Server does not support TLS"
320 ;; See `starttls-available-p'. If this predicate
321 ;; changes to allow running under Windows, the error
322 ;; message below should be amended.
323 (if (memq system-type '(windows-nt ms-dos))
324 (concat "Emacs does not support TLS")
325 (concat "Emacs does not support TLS, and no external `"
326 (if starttls-use-gnutls
327 starttls-gnutls-program
328 starttls-program)
329 "' program was found"))))
330 (delete-process stream)
331 (setq stream nil))
332 ;; Check certificate validity etc.
333 (when (gnutls-available-p)
334 (setq stream (nsm-verify-connection
335 stream host service
336 (eq resulting-type 'tls)
337 (plist-get parameters :warn-unless-encrypted))))
338 ;; Return value:
339 (list stream greeting capabilities resulting-type error)))
340
341 (defun network-stream-command (stream command eoc)
342 (when command
343 (let ((start (with-current-buffer (process-buffer stream) (point-max))))
344 (process-send-string stream command)
345 (network-stream-get-response stream start eoc))))
346
347 (defun network-stream-get-response (stream start end-of-command)
348 (when end-of-command
349 (with-current-buffer (process-buffer stream)
350 (save-excursion
351 (goto-char start)
352 (while (and (memq (process-status stream) '(open run))
353 (not (re-search-forward end-of-command nil t)))
354 (accept-process-output stream 0 50)
355 (goto-char start))
356 ;; Return the data we got back, or nil if the process died.
357 (unless (= start (point))
358 (buffer-substring start (point)))))))
359
360 (defun network-stream-open-tls (name buffer host service parameters)
361 (with-current-buffer buffer
362 (let* ((start (point-max))
363 (stream
364 (funcall (if (gnutls-available-p)
365 'open-gnutls-stream
366 'open-tls-stream)
367 name buffer host service))
368 (eoc (plist-get parameters :end-of-command)))
369 ;; Check certificate validity etc.
370 (when (and (gnutls-available-p) stream)
371 (setq stream (nsm-verify-connection stream host service)))
372 (if (null stream)
373 (list nil nil nil 'plain)
374 ;; If we're using tls.el, we have to delete the output from
375 ;; openssl/gnutls-cli.
376 (when (and (not (gnutls-available-p))
377 eoc)
378 (network-stream-get-response stream start eoc)
379 (goto-char (point-min))
380 (when (re-search-forward eoc nil t)
381 (goto-char (match-beginning 0))
382 (delete-region (point-min) (line-beginning-position))))
383 (let ((capability-command (plist-get parameters :capability-command))
384 (eo-capa (or (plist-get parameters :end-of-capability)
385 eoc)))
386 (list stream
387 (network-stream-get-response stream start eoc)
388 (network-stream-command stream capability-command eo-capa)
389 'tls))))))
390
391 (defun network-stream-open-shell (name buffer host service parameters)
392 (require 'format-spec)
393 (let* ((capability-command (plist-get parameters :capability-command))
394 (eoc (plist-get parameters :end-of-command))
395 (start (with-current-buffer buffer (point)))
396 (stream (let ((process-connection-type nil))
397 (start-process name buffer shell-file-name
398 shell-command-switch
399 (format-spec
400 (plist-get parameters :shell-command)
401 (format-spec-make
402 ?s host
403 ?p service))))))
404 (list stream
405 (network-stream-get-response stream start eoc)
406 (network-stream-command stream capability-command
407 (or (plist-get parameters :end-of-capability)
408 eoc))
409 'plain)))
410
411 (provide 'network-stream)
412
413 ;;; network-stream.el ends here