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
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"
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"
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 {
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
86 static void ssh_state_init(BDRVSSHState *s)
88 memset(s, 0, sizeof *s);
90 qemu_co_mutex_init(&s->lock);
93 static void ssh_state_free(BDRVSSHState *s)
98 sftp_attributes_free(s->attrs);
100 if (s->sftp_handle) {
101 sftp_close(s->sftp_handle);
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, ...)
119 msg = g_strdup_vprintf(fs, args);
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);
132 error_setg(errp, "%s", msg);
137 static void G_GNUC_PRINTF(3, 4)
138 sftp_error_setg(Error **errp, BDRVSSHState *s, const char *fs, ...)
144 msg = g_strdup_vprintf(fs, args);
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);
159 "%s: %s (libssh error code: %d, sftp error code: %d)",
160 msg, ssh_err, ssh_err_code, sftp_err_code);
162 error_setg(errp, "%s", msg);
167 static void sftp_error_trace(BDRVSSHState *s, const char *op)
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)
189 uri = uri_parse(filename);
194 if (g_strcmp0(uri->scheme, "ssh") != 0) {
195 error_setg(errp, "URI scheme must be 'ssh'");
199 if (!uri->server || strcmp(uri->server, "") == 0) {
200 error_setg(errp, "missing hostname in URI");
204 if (!uri->path || strcmp(uri->path, "") == 0) {
205 error_setg(errp, "missing remote path in URI");
209 qp = query_params_parse(uri->query);
211 error_setg(errp, "could not parse query parameters");
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);
225 qdict_put_str(options, "path", uri->path);
227 /* Pick out any query parameters that we understand, and ignore
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);
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",
266 static void ssh_parse_filename(const char *filename, QDict *options,
269 if (ssh_has_filename_options_conflict(options, errp)) {
273 parse_uri(filename, options, errp);
276 static int check_host_key_knownhosts(BDRVSSHState *s, Error **errp)
279 enum ssh_known_hosts_e state;
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);
291 case SSH_KNOWN_HOSTS_OK:
293 trace_ssh_check_host_key_knownhosts();
295 case SSH_KNOWN_HOSTS_CHANGED:
297 r = ssh_get_server_publickey(s->session, &pubkey);
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);
305 fingerprint = ssh_get_fingerprint_hash(SSH_PUBLICKEY_HASH_SHA256,
308 ssh_clean_pubkey_hash(&server_hash);
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);
318 "host key does not match the one in known_hosts; this "
319 "may be a possible attack");
322 case SSH_KNOWN_HOSTS_OTHER:
325 "host key for this server not found, another type exists");
327 case SSH_KNOWN_HOSTS_UNKNOWN:
329 error_setg(errp, "no host key was found in known_hosts");
331 case SSH_KNOWN_HOSTS_NOT_FOUND:
333 error_setg(errp, "known_hosts file not found");
335 case SSH_KNOWN_HOSTS_ERROR:
337 error_setg(errp, "error while checking the host");
341 error_setg(errp, "error while checking for known server (%d)", state);
345 /* known_hosts checking successful. */
352 static unsigned hex2decimal(char ch)
354 if (ch >= '0' && ch <= '9') {
356 } else if (ch >= 'a' && ch <= 'f') {
357 return 10 + (ch - 'a');
358 } else if (ch >= 'A' && ch <= 'F') {
359 return 10 + (ch - 'A');
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)
374 while (*host_key_check == ':')
376 if (!qemu_isxdigit(host_key_check[0]) ||
377 !qemu_isxdigit(host_key_check[1]))
379 c = hex2decimal(host_key_check[0]) * 16 +
380 hex2decimal(host_key_check[1]);
381 if (c - *fingerprint != 0)
382 return c - *fingerprint;
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)];
403 check_host_key_hash(BDRVSSHState *s, const char *hash,
404 enum ssh_publickey_hash_type type, const char *typestr,
409 unsigned char *server_hash;
410 size_t server_hash_len;
413 r = ssh_get_server_publickey(s->session, &pubkey);
415 session_error_setg(errp, s, "failed to read remote host key");
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);
424 session_error_setg(errp, s,
425 "failed reading the hash of the server SSH key");
429 r = compare_fingerprint(server_hash, server_hash_len, hash);
431 g_autofree char *server_fp = format_fingerprint(server_hash,
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);
439 ssh_clean_pubkey_hash(&server_hash);
444 static int check_host_key(BDRVSSHState *s, SshHostKeyCheck *hkc, Error **errp)
446 SshHostKeyCheckMode mode;
451 mode = SSH_HOST_KEY_CHECK_MODE_KNOWN_HOSTS;
455 case SSH_HOST_KEY_CHECK_MODE_NONE:
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",
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",
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",
471 g_assert_not_reached();
473 case SSH_HOST_KEY_CHECK_MODE_KNOWN_HOSTS:
474 return check_host_key_knownhosts(s, errp);
476 g_assert_not_reached();
482 static int authenticate(BDRVSSHState *s, Error **errp)
487 /* Try to authenticate with the "none" method. */
488 r = ssh_userauth_none(s->session, NULL);
489 if (r == SSH_AUTH_ERROR) {
491 session_error_setg(errp, s, "failed to authenticate using none "
494 } else if (r == SSH_AUTH_SUCCESS) {
500 method = ssh_userauth_list(s->session, NULL);
501 trace_ssh_auth_methods(method);
504 * Try to authenticate with publickey, using the ssh-agent
507 if (method & SSH_AUTH_METHOD_PUBLICKEY) {
508 r = ssh_userauth_publickey_auto(s->session, NULL, NULL);
509 if (r == SSH_AUTH_ERROR) {
511 session_error_setg(errp, s, "failed to authenticate using "
512 "publickey authentication");
514 } else if (r == SSH_AUTH_SUCCESS) {
522 error_setg(errp, "failed to authenticate using publickey authentication "
523 "and the identities held by your ssh-agent");
529 static QemuOptsList ssh_runtime_opts = {
531 .head = QTAILQ_HEAD_INITIALIZER(ssh_runtime_opts.head),
535 .type = QEMU_OPT_STRING,
536 .help = "Host to connect to",
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,
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");
561 error_setg(errp, "port may not be used without 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",
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",
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",
588 } else if (strcmp(host_key_check, "yes") == 0) {
589 qdict_put_str(output_opts, "host-key-check.mode", "known_hosts");
591 error_setg(errp, "unknown host_key_check setting (%s)",
600 static BlockdevOptionsSsh *ssh_parse_options(QDict *options, Error **errp)
602 BlockdevOptionsSsh *result = NULL;
603 QemuOpts *opts = NULL;
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)) {
613 if (!ssh_process_legacy_options(options, opts, errp)) {
617 /* Create the QAPI object */
618 v = qobject_input_visitor_new_flat_confused(options, errp);
623 visit_type_BlockdevOptionsSsh(v, NULL, &result, errp);
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);
640 static int connect_to_ssh(BDRVSSHState *s, BlockdevOptionsSsh *opts,
641 int ssh_flags, int creat_mode, Error **errp)
644 unsigned int port = 0;
648 s->user = g_strdup(opts->user);
650 s->user = g_strdup(g_get_user_name());
652 error_setg_errno(errp, errno, "Can't get user name");
658 /* Pop the config into our state object, Exit if invalid */
659 s->inet = opts->server;
662 if (qemu_strtoui(s->inet->port, NULL, 10, &port) < 0) {
663 error_setg(errp, "Use only numeric port value");
668 /* Open the socket and connect. */
669 new_sock = inet_connect_saddr(s->inet, errp);
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);
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();
689 session_error_setg(errp, s, "failed to initialize libssh session");
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);
702 session_error_setg(errp, s,
703 "failed to set the user in the libssh session");
707 r = ssh_options_set(s->session, SSH_OPTIONS_HOST, s->inet->host);
710 session_error_setg(errp, s,
711 "failed to set the host in the libssh session");
716 r = ssh_options_set(s->session, SSH_OPTIONS_PORT, &port);
719 session_error_setg(errp, s,
720 "failed to set the port in the libssh session");
725 r = ssh_options_set(s->session, SSH_OPTIONS_COMPRESSION, "none");
728 session_error_setg(errp, s,
729 "failed to disable the compression in the libssh "
734 /* Read ~/.ssh/config. */
735 r = ssh_options_parse_config(s->session, NULL);
738 session_error_setg(errp, s, "failed to parse ~/.ssh/config");
742 r = ssh_options_set(s->session, SSH_OPTIONS_FD, &new_sock);
745 session_error_setg(errp, s,
746 "failed to set the socket in the libssh session");
749 /* libssh took ownership of the socket. */
754 r = ssh_connect(s->session);
757 session_error_setg(errp, s, "failed to establish SSH session");
761 /* Check the remote host's key against known_hosts. */
762 ret = check_host_key(s, opts->host_key_check, errp);
768 ret = authenticate(s, errp);
774 s->sftp = sftp_new(s->session);
776 session_error_setg(errp, s, "failed to create sftp handle");
781 r = sftp_init(s->sftp);
783 sftp_error_setg(errp, s, "failed to initialize sftp handle");
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'",
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);
803 sftp_error_setg(errp, s, "failed to read file attributes");
811 sftp_attributes_free(s->attrs);
814 if (s->sftp_handle) {
815 sftp_close(s->sftp_handle);
817 s->sftp_handle = NULL;
823 ssh_disconnect(s->session);
824 ssh_free(s->session);
835 static int ssh_file_open(BlockDriverState *bs, QDict *options, int bdrv_flags,
838 BDRVSSHState *s = bs->opaque;
839 BlockdevOptionsSsh *opts;
846 if (bdrv_flags & BDRV_O_RDWR) {
849 ssh_flags |= O_RDONLY;
852 opts = ssh_parse_options(options, errp);
858 ret = connect_to_ssh(s, opts, ssh_flags, 0, errp);
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);
875 qapi_free_BlockdevOptionsSsh(opts);
880 /* Note: This is a blocking operation */
881 static int ssh_grow_file(BDRVSSHState *s, int64_t offset, Error **errp)
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);
899 sftp_error_setg(errp, s, "Failed to grow file");
903 s->attrs->size = offset;
907 static QemuOptsList ssh_create_opts = {
908 .name = "ssh-create-opts",
909 .head = QTAILQ_HEAD_INITIALIZER(ssh_create_opts.head),
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;
926 assert(options->driver == BLOCKDEV_DRIVER_SSH);
930 ret = connect_to_ssh(&s, opts->location,
931 O_RDWR | O_CREAT | O_TRUNC,
937 if (opts->size > 0) {
938 ret = ssh_grow_file(&s, opts->size, errp);
950 static int coroutine_fn ssh_co_create_opts(BlockDriver *drv,
951 const char *filename,
955 BlockdevCreateOptions *create_options;
956 BlockdevCreateOptionsSsh *ssh_opts;
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),
967 trace_ssh_co_create_opts(ssh_opts->size);
969 uri_options = qdict_new();
970 ret = parse_uri(filename, uri_options, errp);
975 ssh_opts->location = ssh_parse_options(uri_options, errp);
976 if (ssh_opts->location == NULL) {
981 ret = ssh_co_create(create_options, errp);
984 qobject_unref(uri_options);
985 qapi_free_BlockdevCreateOptions(create_options);
989 static void ssh_close(BlockDriverState *bs)
991 BDRVSSHState *s = bs->opaque;
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) {
1006 return has_zero_init;
1009 typedef struct BDRVSSHRestart {
1010 BlockDriverState *bs;
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)
1034 IOHandler *rd_handler = NULL, *wr_handler = NULL;
1035 BDRVSSHRestart restart = {
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,
1063 char *buf, *end_of_vec;
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
1077 end_of_vec = i->iov_base + i->iov_len;
1079 for (got = 0; got < size; ) {
1080 size_t request_read_size;
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) {
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);
1102 sftp_error_trace(s, "read");
1108 if (buf >= end_of_vec && got < size) {
1111 end_of_vec = i->iov_base + i->iov_len;
1118 static coroutine_fn int ssh_co_readv(BlockDriverState *bs,
1120 int nb_sectors, QEMUIOVector *qiov)
1122 BDRVSSHState *s = bs->opaque;
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);
1133 static coroutine_fn int ssh_write(BDRVSSHState *s, BlockDriverState *bs,
1134 int64_t offset, size_t size,
1139 char *buf, *end_of_vec;
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
1153 end_of_vec = i->iov_base + i->iov_len;
1155 for (written = 0; written < size; ) {
1156 size_t request_write_size;
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) {
1172 sftp_error_trace(s, "write");
1178 if (buf >= end_of_vec && written < size) {
1181 end_of_vec = i->iov_base + i->iov_len;
1184 if (offset + written > s->attrs->size) {
1185 s->attrs->size = offset + written;
1192 static coroutine_fn int ssh_co_writev(BlockDriverState *bs,
1194 int nb_sectors, QEMUIOVector *qiov,
1197 BDRVSSHState *s = bs->opaque;
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);
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",
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)
1226 if (!sftp_extension_supported(s->sftp, "fsync@openssh.com", "1")) {
1227 unsafe_flush_warning(s, "OpenSSH >= 6.3");
1231 r = sftp_fsync(s->sftp_handle);
1232 if (r == SSH_AGAIN) {
1237 sftp_error_trace(s, "fsync");
1244 static coroutine_fn int ssh_co_flush(BlockDriverState *bs)
1246 BDRVSSHState *s = bs->opaque;
1249 qemu_co_mutex_lock(&s->lock);
1250 ret = ssh_flush(s, bs);
1251 qemu_co_mutex_unlock(&s->lock);
1256 static int64_t coroutine_fn ssh_co_getlength(BlockDriverState *bs)
1258 BDRVSSHState *s = bs->opaque;
1261 /* Note we cannot make a libssh call here. */
1262 length = (int64_t) s->attrs->size;
1263 trace_ssh_getlength(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));
1280 if (offset < s->attrs->size) {
1281 error_setg(errp, "ssh driver does not support shrinking files");
1285 if (offset == s->attrs->size) {
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;
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)
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.
1332 "Cannot generate a base directory with host_key_check set");
1336 if (bs->exact_filename[0] == '\0') {
1337 error_setg(errp, "Cannot generate a base directory for this ssh node");
1341 return path_combine(bs->exact_filename, "");
1344 static const char *const ssh_strong_runtime_opts[] = {
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)
1382 fprintf(stderr, "libssh initialization failed, %d\n", r);
1386 #if TRACE_LIBSSH != 0
1387 ssh_set_log_level(TRACE_LIBSSH);
1390 bdrv_register(&bdrv_ssh);
1393 block_init(bdrv_ssh_init);