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