migration/multifd: Cleanup multifd_load_cleanup()
[qemu/armbru.git] / block / ssh.c
blob2748253d4a3644261d866761fa1d436b7416b6a8
1 /*
2 * Secure Shell (ssh) backend for QEMU.
4 * Copyright (C) 2013 Red Hat Inc., Richard W.M. Jones <rjones@redhat.com>
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
25 #include "qemu/osdep.h"
27 #include <libssh/libssh.h>
28 #include <libssh/sftp.h>
30 #include "block/block-io.h"
31 #include "block/block_int.h"
32 #include "block/qdict.h"
33 #include "qapi/error.h"
34 #include "qemu/error-report.h"
35 #include "qemu/module.h"
36 #include "qemu/option.h"
37 #include "qemu/ctype.h"
38 #include "qemu/cutils.h"
39 #include "qemu/sockets.h"
40 #include "qemu/uri.h"
41 #include "qapi/qapi-visit-sockets.h"
42 #include "qapi/qapi-visit-block-core.h"
43 #include "qapi/qmp/qdict.h"
44 #include "qapi/qmp/qstring.h"
45 #include "qapi/qobject-input-visitor.h"
46 #include "qapi/qobject-output-visitor.h"
47 #include "trace.h"
50 * TRACE_LIBSSH=<level> enables tracing in libssh itself.
51 * The meaning of <level> is described here:
52 * http://api.libssh.org/master/group__libssh__log.html
54 #define TRACE_LIBSSH 0 /* see: SSH_LOG_* */
56 typedef struct BDRVSSHState {
57 /* Coroutine. */
58 CoMutex lock;
60 /* SSH connection. */
61 int sock; /* socket */
62 ssh_session session; /* ssh session */
63 sftp_session sftp; /* sftp session */
64 sftp_file sftp_handle; /* sftp remote file handle */
67 * File attributes at open. We try to keep the .size field
68 * updated if it changes (eg by writing at the end of the file).
70 sftp_attributes attrs;
72 InetSocketAddress *inet;
74 /* Used to warn if 'flush' is not supported. */
75 bool unsafe_flush_warning;
78 * Store the user name for ssh_refresh_filename() because the
79 * default depends on the system you are on -- therefore, when we
80 * generate a filename, it should always contain the user name we
81 * are actually using.
83 char *user;
84 } BDRVSSHState;
86 static void ssh_state_init(BDRVSSHState *s)
88 memset(s, 0, sizeof *s);
89 s->sock = -1;
90 qemu_co_mutex_init(&s->lock);
93 static void ssh_state_free(BDRVSSHState *s)
95 g_free(s->user);
97 if (s->attrs) {
98 sftp_attributes_free(s->attrs);
100 if (s->sftp_handle) {
101 sftp_close(s->sftp_handle);
103 if (s->sftp) {
104 sftp_free(s->sftp);
106 if (s->session) {
107 ssh_disconnect(s->session);
108 ssh_free(s->session); /* This frees s->sock */
112 static void G_GNUC_PRINTF(3, 4)
113 session_error_setg(Error **errp, BDRVSSHState *s, const char *fs, ...)
115 va_list args;
116 char *msg;
118 va_start(args, fs);
119 msg = g_strdup_vprintf(fs, args);
120 va_end(args);
122 if (s->session) {
123 const char *ssh_err;
124 int ssh_err_code;
126 /* This is not an errno. See <libssh/libssh.h>. */
127 ssh_err = ssh_get_error(s->session);
128 ssh_err_code = ssh_get_error_code(s->session);
129 error_setg(errp, "%s: %s (libssh error code: %d)",
130 msg, ssh_err, ssh_err_code);
131 } else {
132 error_setg(errp, "%s", msg);
134 g_free(msg);
137 static void G_GNUC_PRINTF(3, 4)
138 sftp_error_setg(Error **errp, BDRVSSHState *s, const char *fs, ...)
140 va_list args;
141 char *msg;
143 va_start(args, fs);
144 msg = g_strdup_vprintf(fs, args);
145 va_end(args);
147 if (s->sftp) {
148 const char *ssh_err;
149 int ssh_err_code;
150 int sftp_err_code;
152 /* This is not an errno. See <libssh/libssh.h>. */
153 ssh_err = ssh_get_error(s->session);
154 ssh_err_code = ssh_get_error_code(s->session);
155 /* See <libssh/sftp.h>. */
156 sftp_err_code = sftp_get_error(s->sftp);
158 error_setg(errp,
159 "%s: %s (libssh error code: %d, sftp error code: %d)",
160 msg, ssh_err, ssh_err_code, sftp_err_code);
161 } else {
162 error_setg(errp, "%s", msg);
164 g_free(msg);
167 static void sftp_error_trace(BDRVSSHState *s, const char *op)
169 const char *ssh_err;
170 int ssh_err_code;
171 int sftp_err_code;
173 /* This is not an errno. See <libssh/libssh.h>. */
174 ssh_err = ssh_get_error(s->session);
175 ssh_err_code = ssh_get_error_code(s->session);
176 /* See <libssh/sftp.h>. */
177 sftp_err_code = sftp_get_error(s->sftp);
179 trace_sftp_error(op, ssh_err, ssh_err_code, sftp_err_code);
182 static int parse_uri(const char *filename, QDict *options, Error **errp)
184 URI *uri = NULL;
185 QueryParams *qp;
186 char *port_str;
187 int i;
189 uri = uri_parse(filename);
190 if (!uri) {
191 return -EINVAL;
194 if (g_strcmp0(uri->scheme, "ssh") != 0) {
195 error_setg(errp, "URI scheme must be 'ssh'");
196 goto err;
199 if (!uri->server || strcmp(uri->server, "") == 0) {
200 error_setg(errp, "missing hostname in URI");
201 goto err;
204 if (!uri->path || strcmp(uri->path, "") == 0) {
205 error_setg(errp, "missing remote path in URI");
206 goto err;
209 qp = query_params_parse(uri->query);
210 if (!qp) {
211 error_setg(errp, "could not parse query parameters");
212 goto err;
215 if(uri->user && strcmp(uri->user, "") != 0) {
216 qdict_put_str(options, "user", uri->user);
219 qdict_put_str(options, "server.host", uri->server);
221 port_str = g_strdup_printf("%d", uri->port ?: 22);
222 qdict_put_str(options, "server.port", port_str);
223 g_free(port_str);
225 qdict_put_str(options, "path", uri->path);
227 /* Pick out any query parameters that we understand, and ignore
228 * the rest.
230 for (i = 0; i < qp->n; ++i) {
231 if (strcmp(qp->p[i].name, "host_key_check") == 0) {
232 qdict_put_str(options, "host_key_check", qp->p[i].value);
236 query_params_free(qp);
237 uri_free(uri);
238 return 0;
240 err:
241 uri_free(uri);
242 return -EINVAL;
245 static bool ssh_has_filename_options_conflict(QDict *options, Error **errp)
247 const QDictEntry *qe;
249 for (qe = qdict_first(options); qe; qe = qdict_next(options, qe)) {
250 if (!strcmp(qe->key, "host") ||
251 !strcmp(qe->key, "port") ||
252 !strcmp(qe->key, "path") ||
253 !strcmp(qe->key, "user") ||
254 !strcmp(qe->key, "host_key_check") ||
255 strstart(qe->key, "server.", NULL))
257 error_setg(errp, "Option '%s' cannot be used with a file name",
258 qe->key);
259 return true;
263 return false;
266 static void ssh_parse_filename(const char *filename, QDict *options,
267 Error **errp)
269 if (ssh_has_filename_options_conflict(options, errp)) {
270 return;
273 parse_uri(filename, options, errp);
276 static int check_host_key_knownhosts(BDRVSSHState *s, Error **errp)
278 int ret;
279 enum ssh_known_hosts_e state;
280 int r;
281 ssh_key pubkey;
282 enum ssh_keytypes_e pubkey_type;
283 unsigned char *server_hash = NULL;
284 size_t server_hash_len;
285 char *fingerprint = NULL;
287 state = ssh_session_is_known_server(s->session);
288 trace_ssh_server_status(state);
290 switch (state) {
291 case SSH_KNOWN_HOSTS_OK:
292 /* OK */
293 trace_ssh_check_host_key_knownhosts();
294 break;
295 case SSH_KNOWN_HOSTS_CHANGED:
296 ret = -EINVAL;
297 r = ssh_get_server_publickey(s->session, &pubkey);
298 if (r == 0) {
299 r = ssh_get_publickey_hash(pubkey, SSH_PUBLICKEY_HASH_SHA256,
300 &server_hash, &server_hash_len);
301 pubkey_type = ssh_key_type(pubkey);
302 ssh_key_free(pubkey);
304 if (r == 0) {
305 fingerprint = ssh_get_fingerprint_hash(SSH_PUBLICKEY_HASH_SHA256,
306 server_hash,
307 server_hash_len);
308 ssh_clean_pubkey_hash(&server_hash);
310 if (fingerprint) {
311 error_setg(errp,
312 "host key (%s key with fingerprint %s) does not match "
313 "the one in known_hosts; this may be a possible attack",
314 ssh_key_type_to_char(pubkey_type), fingerprint);
315 ssh_string_free_char(fingerprint);
316 } else {
317 error_setg(errp,
318 "host key does not match the one in known_hosts; this "
319 "may be a possible attack");
321 goto out;
322 case SSH_KNOWN_HOSTS_OTHER:
323 ret = -EINVAL;
324 error_setg(errp,
325 "host key for this server not found, another type exists");
326 goto out;
327 case SSH_KNOWN_HOSTS_UNKNOWN:
328 ret = -EINVAL;
329 error_setg(errp, "no host key was found in known_hosts");
330 goto out;
331 case SSH_KNOWN_HOSTS_NOT_FOUND:
332 ret = -ENOENT;
333 error_setg(errp, "known_hosts file not found");
334 goto out;
335 case SSH_KNOWN_HOSTS_ERROR:
336 ret = -EINVAL;
337 error_setg(errp, "error while checking the host");
338 goto out;
339 default:
340 ret = -EINVAL;
341 error_setg(errp, "error while checking for known server (%d)", state);
342 goto out;
345 /* known_hosts checking successful. */
346 ret = 0;
348 out:
349 return ret;
352 static unsigned hex2decimal(char ch)
354 if (ch >= '0' && ch <= '9') {
355 return (ch - '0');
356 } else if (ch >= 'a' && ch <= 'f') {
357 return 10 + (ch - 'a');
358 } else if (ch >= 'A' && ch <= 'F') {
359 return 10 + (ch - 'A');
362 return -1;
365 /* Compare the binary fingerprint (hash of host key) with the
366 * host_key_check parameter.
368 static int compare_fingerprint(const unsigned char *fingerprint, size_t len,
369 const char *host_key_check)
371 unsigned c;
373 while (len > 0) {
374 while (*host_key_check == ':')
375 host_key_check++;
376 if (!qemu_isxdigit(host_key_check[0]) ||
377 !qemu_isxdigit(host_key_check[1]))
378 return 1;
379 c = hex2decimal(host_key_check[0]) * 16 +
380 hex2decimal(host_key_check[1]);
381 if (c - *fingerprint != 0)
382 return c - *fingerprint;
383 fingerprint++;
384 len--;
385 host_key_check += 2;
387 return *host_key_check - '\0';
390 static char *format_fingerprint(const unsigned char *fingerprint, size_t len)
392 static const char *hex = "0123456789abcdef";
393 char *ret = g_new0(char, (len * 2) + 1);
394 for (size_t i = 0; i < len; i++) {
395 ret[i * 2] = hex[((fingerprint[i] >> 4) & 0xf)];
396 ret[(i * 2) + 1] = hex[(fingerprint[i] & 0xf)];
398 ret[len * 2] = '\0';
399 return ret;
402 static int
403 check_host_key_hash(BDRVSSHState *s, const char *hash,
404 enum ssh_publickey_hash_type type, const char *typestr,
405 Error **errp)
407 int r;
408 ssh_key pubkey;
409 unsigned char *server_hash;
410 size_t server_hash_len;
411 const char *keytype;
413 r = ssh_get_server_publickey(s->session, &pubkey);
414 if (r != SSH_OK) {
415 session_error_setg(errp, s, "failed to read remote host key");
416 return -EINVAL;
419 keytype = ssh_key_type_to_char(ssh_key_type(pubkey));
421 r = ssh_get_publickey_hash(pubkey, type, &server_hash, &server_hash_len);
422 ssh_key_free(pubkey);
423 if (r != 0) {
424 session_error_setg(errp, s,
425 "failed reading the hash of the server SSH key");
426 return -EINVAL;
429 r = compare_fingerprint(server_hash, server_hash_len, hash);
430 if (r != 0) {
431 g_autofree char *server_fp = format_fingerprint(server_hash,
432 server_hash_len);
433 error_setg(errp, "remote host %s key fingerprint '%s:%s' "
434 "does not match host_key_check '%s:%s'",
435 keytype, typestr, server_fp, typestr, hash);
436 ssh_clean_pubkey_hash(&server_hash);
437 return -EPERM;
439 ssh_clean_pubkey_hash(&server_hash);
441 return 0;
444 static int check_host_key(BDRVSSHState *s, SshHostKeyCheck *hkc, Error **errp)
446 SshHostKeyCheckMode mode;
448 if (hkc) {
449 mode = hkc->mode;
450 } else {
451 mode = SSH_HOST_KEY_CHECK_MODE_KNOWN_HOSTS;
454 switch (mode) {
455 case SSH_HOST_KEY_CHECK_MODE_NONE:
456 return 0;
457 case SSH_HOST_KEY_CHECK_MODE_HASH:
458 if (hkc->u.hash.type == SSH_HOST_KEY_CHECK_HASH_TYPE_MD5) {
459 return check_host_key_hash(s, hkc->u.hash.hash,
460 SSH_PUBLICKEY_HASH_MD5, "md5",
461 errp);
462 } else if (hkc->u.hash.type == SSH_HOST_KEY_CHECK_HASH_TYPE_SHA1) {
463 return check_host_key_hash(s, hkc->u.hash.hash,
464 SSH_PUBLICKEY_HASH_SHA1, "sha1",
465 errp);
466 } else if (hkc->u.hash.type == SSH_HOST_KEY_CHECK_HASH_TYPE_SHA256) {
467 return check_host_key_hash(s, hkc->u.hash.hash,
468 SSH_PUBLICKEY_HASH_SHA256, "sha256",
469 errp);
471 g_assert_not_reached();
472 break;
473 case SSH_HOST_KEY_CHECK_MODE_KNOWN_HOSTS:
474 return check_host_key_knownhosts(s, errp);
475 default:
476 g_assert_not_reached();
479 return -EINVAL;
482 static int authenticate(BDRVSSHState *s, Error **errp)
484 int r, ret;
485 int method;
487 /* Try to authenticate with the "none" method. */
488 r = ssh_userauth_none(s->session, NULL);
489 if (r == SSH_AUTH_ERROR) {
490 ret = -EPERM;
491 session_error_setg(errp, s, "failed to authenticate using none "
492 "authentication");
493 goto out;
494 } else if (r == SSH_AUTH_SUCCESS) {
495 /* Authenticated! */
496 ret = 0;
497 goto out;
500 method = ssh_userauth_list(s->session, NULL);
501 trace_ssh_auth_methods(method);
504 * Try to authenticate with publickey, using the ssh-agent
505 * if available.
507 if (method & SSH_AUTH_METHOD_PUBLICKEY) {
508 r = ssh_userauth_publickey_auto(s->session, NULL, NULL);
509 if (r == SSH_AUTH_ERROR) {
510 ret = -EINVAL;
511 session_error_setg(errp, s, "failed to authenticate using "
512 "publickey authentication");
513 goto out;
514 } else if (r == SSH_AUTH_SUCCESS) {
515 /* Authenticated! */
516 ret = 0;
517 goto out;
521 ret = -EPERM;
522 error_setg(errp, "failed to authenticate using publickey authentication "
523 "and the identities held by your ssh-agent");
525 out:
526 return ret;
529 static QemuOptsList ssh_runtime_opts = {
530 .name = "ssh",
531 .head = QTAILQ_HEAD_INITIALIZER(ssh_runtime_opts.head),
532 .desc = {
534 .name = "host",
535 .type = QEMU_OPT_STRING,
536 .help = "Host to connect to",
539 .name = "port",
540 .type = QEMU_OPT_NUMBER,
541 .help = "Port to connect to",
544 .name = "host_key_check",
545 .type = QEMU_OPT_STRING,
546 .help = "Defines how and what to check the host key against",
548 { /* end of list */ }
552 static bool ssh_process_legacy_options(QDict *output_opts,
553 QemuOpts *legacy_opts,
554 Error **errp)
556 const char *host = qemu_opt_get(legacy_opts, "host");
557 const char *port = qemu_opt_get(legacy_opts, "port");
558 const char *host_key_check = qemu_opt_get(legacy_opts, "host_key_check");
560 if (!host && port) {
561 error_setg(errp, "port may not be used without host");
562 return false;
565 if (host) {
566 qdict_put_str(output_opts, "server.host", host);
567 qdict_put_str(output_opts, "server.port", port ?: stringify(22));
570 if (host_key_check) {
571 if (strcmp(host_key_check, "no") == 0) {
572 qdict_put_str(output_opts, "host-key-check.mode", "none");
573 } else if (strncmp(host_key_check, "md5:", 4) == 0) {
574 qdict_put_str(output_opts, "host-key-check.mode", "hash");
575 qdict_put_str(output_opts, "host-key-check.type", "md5");
576 qdict_put_str(output_opts, "host-key-check.hash",
577 &host_key_check[4]);
578 } else if (strncmp(host_key_check, "sha1:", 5) == 0) {
579 qdict_put_str(output_opts, "host-key-check.mode", "hash");
580 qdict_put_str(output_opts, "host-key-check.type", "sha1");
581 qdict_put_str(output_opts, "host-key-check.hash",
582 &host_key_check[5]);
583 } else if (strncmp(host_key_check, "sha256:", 7) == 0) {
584 qdict_put_str(output_opts, "host-key-check.mode", "hash");
585 qdict_put_str(output_opts, "host-key-check.type", "sha256");
586 qdict_put_str(output_opts, "host-key-check.hash",
587 &host_key_check[7]);
588 } else if (strcmp(host_key_check, "yes") == 0) {
589 qdict_put_str(output_opts, "host-key-check.mode", "known_hosts");
590 } else {
591 error_setg(errp, "unknown host_key_check setting (%s)",
592 host_key_check);
593 return false;
597 return true;
600 static BlockdevOptionsSsh *ssh_parse_options(QDict *options, Error **errp)
602 BlockdevOptionsSsh *result = NULL;
603 QemuOpts *opts = NULL;
604 const QDictEntry *e;
605 Visitor *v;
607 /* Translate legacy options */
608 opts = qemu_opts_create(&ssh_runtime_opts, NULL, 0, &error_abort);
609 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
610 goto fail;
613 if (!ssh_process_legacy_options(options, opts, errp)) {
614 goto fail;
617 /* Create the QAPI object */
618 v = qobject_input_visitor_new_flat_confused(options, errp);
619 if (!v) {
620 goto fail;
623 visit_type_BlockdevOptionsSsh(v, NULL, &result, errp);
624 visit_free(v);
625 if (!result) {
626 goto fail;
629 /* Remove the processed options from the QDict (the visitor processes
630 * _all_ options in the QDict) */
631 while ((e = qdict_first(options))) {
632 qdict_del(options, e->key);
635 fail:
636 qemu_opts_del(opts);
637 return result;
640 static int connect_to_ssh(BDRVSSHState *s, BlockdevOptionsSsh *opts,
641 int ssh_flags, int creat_mode, Error **errp)
643 int r, ret;
644 unsigned int port = 0;
645 int new_sock = -1;
647 if (opts->user) {
648 s->user = g_strdup(opts->user);
649 } else {
650 s->user = g_strdup(g_get_user_name());
651 if (!s->user) {
652 error_setg_errno(errp, errno, "Can't get user name");
653 ret = -errno;
654 goto err;
658 /* Pop the config into our state object, Exit if invalid */
659 s->inet = opts->server;
660 opts->server = NULL;
662 if (qemu_strtoui(s->inet->port, NULL, 10, &port) < 0) {
663 error_setg(errp, "Use only numeric port value");
664 ret = -EINVAL;
665 goto err;
668 /* Open the socket and connect. */
669 new_sock = inet_connect_saddr(s->inet, errp);
670 if (new_sock < 0) {
671 ret = -EIO;
672 goto err;
676 * Try to disable the Nagle algorithm on TCP sockets to reduce latency,
677 * but do not fail if it cannot be disabled.
679 r = socket_set_nodelay(new_sock);
680 if (r < 0) {
681 warn_report("can't set TCP_NODELAY for the ssh server %s: %s",
682 s->inet->host, strerror(errno));
685 /* Create SSH session. */
686 s->session = ssh_new();
687 if (!s->session) {
688 ret = -EINVAL;
689 session_error_setg(errp, s, "failed to initialize libssh session");
690 goto err;
694 * Make sure we are in blocking mode during the connection and
695 * authentication phases.
697 ssh_set_blocking(s->session, 1);
699 r = ssh_options_set(s->session, SSH_OPTIONS_USER, s->user);
700 if (r < 0) {
701 ret = -EINVAL;
702 session_error_setg(errp, s,
703 "failed to set the user in the libssh session");
704 goto err;
707 r = ssh_options_set(s->session, SSH_OPTIONS_HOST, s->inet->host);
708 if (r < 0) {
709 ret = -EINVAL;
710 session_error_setg(errp, s,
711 "failed to set the host in the libssh session");
712 goto err;
715 if (port > 0) {
716 r = ssh_options_set(s->session, SSH_OPTIONS_PORT, &port);
717 if (r < 0) {
718 ret = -EINVAL;
719 session_error_setg(errp, s,
720 "failed to set the port in the libssh session");
721 goto err;
725 r = ssh_options_set(s->session, SSH_OPTIONS_COMPRESSION, "none");
726 if (r < 0) {
727 ret = -EINVAL;
728 session_error_setg(errp, s,
729 "failed to disable the compression in the libssh "
730 "session");
731 goto err;
734 /* Read ~/.ssh/config. */
735 r = ssh_options_parse_config(s->session, NULL);
736 if (r < 0) {
737 ret = -EINVAL;
738 session_error_setg(errp, s, "failed to parse ~/.ssh/config");
739 goto err;
742 r = ssh_options_set(s->session, SSH_OPTIONS_FD, &new_sock);
743 if (r < 0) {
744 ret = -EINVAL;
745 session_error_setg(errp, s,
746 "failed to set the socket in the libssh session");
747 goto err;
749 /* libssh took ownership of the socket. */
750 s->sock = new_sock;
751 new_sock = -1;
753 /* Connect. */
754 r = ssh_connect(s->session);
755 if (r != SSH_OK) {
756 ret = -EINVAL;
757 session_error_setg(errp, s, "failed to establish SSH session");
758 goto err;
761 /* Check the remote host's key against known_hosts. */
762 ret = check_host_key(s, opts->host_key_check, errp);
763 if (ret < 0) {
764 goto err;
767 /* Authenticate. */
768 ret = authenticate(s, errp);
769 if (ret < 0) {
770 goto err;
773 /* Start SFTP. */
774 s->sftp = sftp_new(s->session);
775 if (!s->sftp) {
776 session_error_setg(errp, s, "failed to create sftp handle");
777 ret = -EINVAL;
778 goto err;
781 r = sftp_init(s->sftp);
782 if (r < 0) {
783 sftp_error_setg(errp, s, "failed to initialize sftp handle");
784 ret = -EINVAL;
785 goto err;
788 /* Open the remote file. */
789 trace_ssh_connect_to_ssh(opts->path, ssh_flags, creat_mode);
790 s->sftp_handle = sftp_open(s->sftp, opts->path, ssh_flags, creat_mode);
791 if (!s->sftp_handle) {
792 sftp_error_setg(errp, s, "failed to open remote file '%s'",
793 opts->path);
794 ret = -EINVAL;
795 goto err;
798 /* Make sure the SFTP file is handled in blocking mode. */
799 sftp_file_set_blocking(s->sftp_handle);
801 s->attrs = sftp_fstat(s->sftp_handle);
802 if (!s->attrs) {
803 sftp_error_setg(errp, s, "failed to read file attributes");
804 return -EINVAL;
807 return 0;
809 err:
810 if (s->attrs) {
811 sftp_attributes_free(s->attrs);
813 s->attrs = NULL;
814 if (s->sftp_handle) {
815 sftp_close(s->sftp_handle);
817 s->sftp_handle = NULL;
818 if (s->sftp) {
819 sftp_free(s->sftp);
821 s->sftp = NULL;
822 if (s->session) {
823 ssh_disconnect(s->session);
824 ssh_free(s->session);
826 s->session = NULL;
827 s->sock = -1;
828 if (new_sock >= 0) {
829 close(new_sock);
832 return ret;
835 static int ssh_file_open(BlockDriverState *bs, QDict *options, int bdrv_flags,
836 Error **errp)
838 BDRVSSHState *s = bs->opaque;
839 BlockdevOptionsSsh *opts;
840 int ret;
841 int ssh_flags;
843 ssh_state_init(s);
845 ssh_flags = 0;
846 if (bdrv_flags & BDRV_O_RDWR) {
847 ssh_flags |= O_RDWR;
848 } else {
849 ssh_flags |= O_RDONLY;
852 opts = ssh_parse_options(options, errp);
853 if (opts == NULL) {
854 return -EINVAL;
857 /* Start up SSH. */
858 ret = connect_to_ssh(s, opts, ssh_flags, 0, errp);
859 if (ret < 0) {
860 goto err;
863 /* Go non-blocking. */
864 ssh_set_blocking(s->session, 0);
866 if (s->attrs->type == SSH_FILEXFER_TYPE_REGULAR) {
867 bs->supported_truncate_flags = BDRV_REQ_ZERO_WRITE;
870 qapi_free_BlockdevOptionsSsh(opts);
872 return 0;
874 err:
875 qapi_free_BlockdevOptionsSsh(opts);
877 return ret;
880 /* Note: This is a blocking operation */
881 static int ssh_grow_file(BDRVSSHState *s, int64_t offset, Error **errp)
883 ssize_t ret;
884 char c[1] = { '\0' };
885 int was_blocking = ssh_is_blocking(s->session);
887 /* offset must be strictly greater than the current size so we do
888 * not overwrite anything */
889 assert(offset > 0 && offset > s->attrs->size);
891 ssh_set_blocking(s->session, 1);
893 sftp_seek64(s->sftp_handle, offset - 1);
894 ret = sftp_write(s->sftp_handle, c, 1);
896 ssh_set_blocking(s->session, was_blocking);
898 if (ret < 0) {
899 sftp_error_setg(errp, s, "Failed to grow file");
900 return -EIO;
903 s->attrs->size = offset;
904 return 0;
907 static QemuOptsList ssh_create_opts = {
908 .name = "ssh-create-opts",
909 .head = QTAILQ_HEAD_INITIALIZER(ssh_create_opts.head),
910 .desc = {
912 .name = BLOCK_OPT_SIZE,
913 .type = QEMU_OPT_SIZE,
914 .help = "Virtual disk size"
916 { /* end of list */ }
920 static int ssh_co_create(BlockdevCreateOptions *options, Error **errp)
922 BlockdevCreateOptionsSsh *opts = &options->u.ssh;
923 BDRVSSHState s;
924 int ret;
926 assert(options->driver == BLOCKDEV_DRIVER_SSH);
928 ssh_state_init(&s);
930 ret = connect_to_ssh(&s, opts->location,
931 O_RDWR | O_CREAT | O_TRUNC,
932 0644, errp);
933 if (ret < 0) {
934 goto fail;
937 if (opts->size > 0) {
938 ret = ssh_grow_file(&s, opts->size, errp);
939 if (ret < 0) {
940 goto fail;
944 ret = 0;
945 fail:
946 ssh_state_free(&s);
947 return ret;
950 static int coroutine_fn ssh_co_create_opts(BlockDriver *drv,
951 const char *filename,
952 QemuOpts *opts,
953 Error **errp)
955 BlockdevCreateOptions *create_options;
956 BlockdevCreateOptionsSsh *ssh_opts;
957 int ret;
958 QDict *uri_options = NULL;
960 create_options = g_new0(BlockdevCreateOptions, 1);
961 create_options->driver = BLOCKDEV_DRIVER_SSH;
962 ssh_opts = &create_options->u.ssh;
964 /* Get desired file size. */
965 ssh_opts->size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
966 BDRV_SECTOR_SIZE);
967 trace_ssh_co_create_opts(ssh_opts->size);
969 uri_options = qdict_new();
970 ret = parse_uri(filename, uri_options, errp);
971 if (ret < 0) {
972 goto out;
975 ssh_opts->location = ssh_parse_options(uri_options, errp);
976 if (ssh_opts->location == NULL) {
977 ret = -EINVAL;
978 goto out;
981 ret = ssh_co_create(create_options, errp);
983 out:
984 qobject_unref(uri_options);
985 qapi_free_BlockdevCreateOptions(create_options);
986 return ret;
989 static void ssh_close(BlockDriverState *bs)
991 BDRVSSHState *s = bs->opaque;
993 ssh_state_free(s);
996 static int ssh_has_zero_init(BlockDriverState *bs)
998 BDRVSSHState *s = bs->opaque;
999 /* Assume false, unless we can positively prove it's true. */
1000 int has_zero_init = 0;
1002 if (s->attrs->type == SSH_FILEXFER_TYPE_REGULAR) {
1003 has_zero_init = 1;
1006 return has_zero_init;
1009 typedef struct BDRVSSHRestart {
1010 BlockDriverState *bs;
1011 Coroutine *co;
1012 } BDRVSSHRestart;
1014 static void restart_coroutine(void *opaque)
1016 BDRVSSHRestart *restart = opaque;
1017 BlockDriverState *bs = restart->bs;
1018 BDRVSSHState *s = bs->opaque;
1019 AioContext *ctx = bdrv_get_aio_context(bs);
1021 trace_ssh_restart_coroutine(restart->co);
1022 aio_set_fd_handler(ctx, s->sock, NULL, NULL, NULL, NULL, NULL);
1024 aio_co_wake(restart->co);
1027 /* A non-blocking call returned EAGAIN, so yield, ensuring the
1028 * handlers are set up so that we'll be rescheduled when there is an
1029 * interesting event on the socket.
1031 static coroutine_fn void co_yield(BDRVSSHState *s, BlockDriverState *bs)
1033 int r;
1034 IOHandler *rd_handler = NULL, *wr_handler = NULL;
1035 BDRVSSHRestart restart = {
1036 .bs = bs,
1037 .co = qemu_coroutine_self()
1040 r = ssh_get_poll_flags(s->session);
1042 if (r & SSH_READ_PENDING) {
1043 rd_handler = restart_coroutine;
1045 if (r & SSH_WRITE_PENDING) {
1046 wr_handler = restart_coroutine;
1049 trace_ssh_co_yield(s->sock, rd_handler, wr_handler);
1051 aio_set_fd_handler(bdrv_get_aio_context(bs), s->sock,
1052 rd_handler, wr_handler, NULL, NULL, &restart);
1053 qemu_coroutine_yield();
1054 trace_ssh_co_yield_back(s->sock);
1057 static coroutine_fn int ssh_read(BDRVSSHState *s, BlockDriverState *bs,
1058 int64_t offset, size_t size,
1059 QEMUIOVector *qiov)
1061 ssize_t r;
1062 size_t got;
1063 char *buf, *end_of_vec;
1064 struct iovec *i;
1066 trace_ssh_read(offset, size);
1068 trace_ssh_seek(offset);
1069 sftp_seek64(s->sftp_handle, offset);
1071 /* This keeps track of the current iovec element ('i'), where we
1072 * will write to next ('buf'), and the end of the current iovec
1073 * ('end_of_vec').
1075 i = &qiov->iov[0];
1076 buf = i->iov_base;
1077 end_of_vec = i->iov_base + i->iov_len;
1079 for (got = 0; got < size; ) {
1080 size_t request_read_size;
1081 again:
1083 * The size of SFTP packets is limited to 32K bytes, so limit
1084 * the amount of data requested to 16K, as libssh currently
1085 * does not handle multiple requests on its own.
1087 request_read_size = MIN(end_of_vec - buf, 16384);
1088 trace_ssh_read_buf(buf, end_of_vec - buf, request_read_size);
1089 r = sftp_read(s->sftp_handle, buf, request_read_size);
1090 trace_ssh_read_return(r, sftp_get_error(s->sftp));
1092 if (r == SSH_AGAIN) {
1093 co_yield(s, bs);
1094 goto again;
1096 if (r == SSH_EOF || (r == 0 && sftp_get_error(s->sftp) == SSH_FX_EOF)) {
1097 /* EOF: Short read so pad the buffer with zeroes and return it. */
1098 qemu_iovec_memset(qiov, got, 0, size - got);
1099 return 0;
1101 if (r <= 0) {
1102 sftp_error_trace(s, "read");
1103 return -EIO;
1106 got += r;
1107 buf += r;
1108 if (buf >= end_of_vec && got < size) {
1109 i++;
1110 buf = i->iov_base;
1111 end_of_vec = i->iov_base + i->iov_len;
1115 return 0;
1118 static coroutine_fn int ssh_co_readv(BlockDriverState *bs,
1119 int64_t sector_num,
1120 int nb_sectors, QEMUIOVector *qiov)
1122 BDRVSSHState *s = bs->opaque;
1123 int ret;
1125 qemu_co_mutex_lock(&s->lock);
1126 ret = ssh_read(s, bs, sector_num * BDRV_SECTOR_SIZE,
1127 nb_sectors * BDRV_SECTOR_SIZE, qiov);
1128 qemu_co_mutex_unlock(&s->lock);
1130 return ret;
1133 static coroutine_fn int ssh_write(BDRVSSHState *s, BlockDriverState *bs,
1134 int64_t offset, size_t size,
1135 QEMUIOVector *qiov)
1137 ssize_t r;
1138 size_t written;
1139 char *buf, *end_of_vec;
1140 struct iovec *i;
1142 trace_ssh_write(offset, size);
1144 trace_ssh_seek(offset);
1145 sftp_seek64(s->sftp_handle, offset);
1147 /* This keeps track of the current iovec element ('i'), where we
1148 * will read from next ('buf'), and the end of the current iovec
1149 * ('end_of_vec').
1151 i = &qiov->iov[0];
1152 buf = i->iov_base;
1153 end_of_vec = i->iov_base + i->iov_len;
1155 for (written = 0; written < size; ) {
1156 size_t request_write_size;
1157 again:
1159 * Avoid too large data packets, as libssh currently does not
1160 * handle multiple requests on its own.
1162 request_write_size = MIN(end_of_vec - buf, 131072);
1163 trace_ssh_write_buf(buf, end_of_vec - buf, request_write_size);
1164 r = sftp_write(s->sftp_handle, buf, request_write_size);
1165 trace_ssh_write_return(r, sftp_get_error(s->sftp));
1167 if (r == SSH_AGAIN) {
1168 co_yield(s, bs);
1169 goto again;
1171 if (r < 0) {
1172 sftp_error_trace(s, "write");
1173 return -EIO;
1176 written += r;
1177 buf += r;
1178 if (buf >= end_of_vec && written < size) {
1179 i++;
1180 buf = i->iov_base;
1181 end_of_vec = i->iov_base + i->iov_len;
1184 if (offset + written > s->attrs->size) {
1185 s->attrs->size = offset + written;
1189 return 0;
1192 static coroutine_fn int ssh_co_writev(BlockDriverState *bs,
1193 int64_t sector_num,
1194 int nb_sectors, QEMUIOVector *qiov,
1195 int flags)
1197 BDRVSSHState *s = bs->opaque;
1198 int ret;
1200 qemu_co_mutex_lock(&s->lock);
1201 ret = ssh_write(s, bs, sector_num * BDRV_SECTOR_SIZE,
1202 nb_sectors * BDRV_SECTOR_SIZE, qiov);
1203 qemu_co_mutex_unlock(&s->lock);
1205 return ret;
1208 static void unsafe_flush_warning(BDRVSSHState *s, const char *what)
1210 if (!s->unsafe_flush_warning) {
1211 warn_report("ssh server %s does not support fsync",
1212 s->inet->host);
1213 if (what) {
1214 error_report("to support fsync, you need %s", what);
1216 s->unsafe_flush_warning = true;
1220 static coroutine_fn int ssh_flush(BDRVSSHState *s, BlockDriverState *bs)
1222 int r;
1224 trace_ssh_flush();
1226 if (!sftp_extension_supported(s->sftp, "fsync@openssh.com", "1")) {
1227 unsafe_flush_warning(s, "OpenSSH >= 6.3");
1228 return 0;
1230 again:
1231 r = sftp_fsync(s->sftp_handle);
1232 if (r == SSH_AGAIN) {
1233 co_yield(s, bs);
1234 goto again;
1236 if (r < 0) {
1237 sftp_error_trace(s, "fsync");
1238 return -EIO;
1241 return 0;
1244 static coroutine_fn int ssh_co_flush(BlockDriverState *bs)
1246 BDRVSSHState *s = bs->opaque;
1247 int ret;
1249 qemu_co_mutex_lock(&s->lock);
1250 ret = ssh_flush(s, bs);
1251 qemu_co_mutex_unlock(&s->lock);
1253 return ret;
1256 static int64_t coroutine_fn ssh_co_getlength(BlockDriverState *bs)
1258 BDRVSSHState *s = bs->opaque;
1259 int64_t length;
1261 /* Note we cannot make a libssh call here. */
1262 length = (int64_t) s->attrs->size;
1263 trace_ssh_getlength(length);
1265 return length;
1268 static int coroutine_fn ssh_co_truncate(BlockDriverState *bs, int64_t offset,
1269 bool exact, PreallocMode prealloc,
1270 BdrvRequestFlags flags, Error **errp)
1272 BDRVSSHState *s = bs->opaque;
1274 if (prealloc != PREALLOC_MODE_OFF) {
1275 error_setg(errp, "Unsupported preallocation mode '%s'",
1276 PreallocMode_str(prealloc));
1277 return -ENOTSUP;
1280 if (offset < s->attrs->size) {
1281 error_setg(errp, "ssh driver does not support shrinking files");
1282 return -ENOTSUP;
1285 if (offset == s->attrs->size) {
1286 return 0;
1289 return ssh_grow_file(s, offset, errp);
1292 static void ssh_refresh_filename(BlockDriverState *bs)
1294 BDRVSSHState *s = bs->opaque;
1295 const char *path, *host_key_check;
1296 int ret;
1299 * None of these options can be represented in a plain "host:port"
1300 * format, so if any was given, we have to abort.
1302 if (s->inet->has_ipv4 || s->inet->has_ipv6 || s->inet->has_to ||
1303 s->inet->has_numeric)
1305 return;
1308 path = qdict_get_try_str(bs->full_open_options, "path");
1309 assert(path); /* mandatory option */
1311 host_key_check = qdict_get_try_str(bs->full_open_options, "host_key_check");
1313 ret = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
1314 "ssh://%s@%s:%s%s%s%s",
1315 s->user, s->inet->host, s->inet->port, path,
1316 host_key_check ? "?host_key_check=" : "",
1317 host_key_check ?: "");
1318 if (ret >= sizeof(bs->exact_filename)) {
1319 /* An overflow makes the filename unusable, so do not report any */
1320 bs->exact_filename[0] = '\0';
1324 static char *ssh_bdrv_dirname(BlockDriverState *bs, Error **errp)
1326 if (qdict_haskey(bs->full_open_options, "host_key_check")) {
1328 * We cannot generate a simple prefix if we would have to
1329 * append a query string.
1331 error_setg(errp,
1332 "Cannot generate a base directory with host_key_check set");
1333 return NULL;
1336 if (bs->exact_filename[0] == '\0') {
1337 error_setg(errp, "Cannot generate a base directory for this ssh node");
1338 return NULL;
1341 return path_combine(bs->exact_filename, "");
1344 static const char *const ssh_strong_runtime_opts[] = {
1345 "host",
1346 "port",
1347 "path",
1348 "user",
1349 "host_key_check",
1350 "server.",
1352 NULL
1355 static BlockDriver bdrv_ssh = {
1356 .format_name = "ssh",
1357 .protocol_name = "ssh",
1358 .instance_size = sizeof(BDRVSSHState),
1359 .bdrv_parse_filename = ssh_parse_filename,
1360 .bdrv_file_open = ssh_file_open,
1361 .bdrv_co_create = ssh_co_create,
1362 .bdrv_co_create_opts = ssh_co_create_opts,
1363 .bdrv_close = ssh_close,
1364 .bdrv_has_zero_init = ssh_has_zero_init,
1365 .bdrv_co_readv = ssh_co_readv,
1366 .bdrv_co_writev = ssh_co_writev,
1367 .bdrv_co_getlength = ssh_co_getlength,
1368 .bdrv_co_truncate = ssh_co_truncate,
1369 .bdrv_co_flush_to_disk = ssh_co_flush,
1370 .bdrv_refresh_filename = ssh_refresh_filename,
1371 .bdrv_dirname = ssh_bdrv_dirname,
1372 .create_opts = &ssh_create_opts,
1373 .strong_runtime_opts = ssh_strong_runtime_opts,
1376 static void bdrv_ssh_init(void)
1378 int r;
1380 r = ssh_init();
1381 if (r != 0) {
1382 fprintf(stderr, "libssh initialization failed, %d\n", r);
1383 exit(EXIT_FAILURE);
1386 #if TRACE_LIBSSH != 0
1387 ssh_set_log_level(TRACE_LIBSSH);
1388 #endif
1390 bdrv_register(&bdrv_ssh);
1393 block_init(bdrv_ssh_init);