2 * Secure Shell (ssh) backend for QEMU.
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"
28 #include <libssh2_sftp.h>
30 #include "block/block_int.h"
31 #include "block/qdict.h"
32 #include "qapi/error.h"
33 #include "qemu/error-report.h"
34 #include "qemu/option.h"
35 #include "qemu/cutils.h"
36 #include "qemu/sockets.h"
38 #include "qapi/qapi-visit-sockets.h"
39 #include "qapi/qapi-visit-block-core.h"
40 #include "qapi/qmp/qdict.h"
41 #include "qapi/qmp/qstring.h"
42 #include "qapi/qobject-input-visitor.h"
43 #include "qapi/qobject-output-visitor.h"
47 * TRACE_LIBSSH2=<bitmask> enables tracing in libssh2 itself. Note
48 * that this requires that libssh2 was specially compiled with the
49 * `./configure --enable-debug' option, so most likely you will have
50 * to compile it yourself. The meaning of <bitmask> is described
51 * here: http://www.libssh2.org/libssh2_trace.html
53 #define TRACE_LIBSSH2 0 /* or try: LIBSSH2_TRACE_SFTP */
55 typedef struct BDRVSSHState {
60 int sock; /* socket */
61 LIBSSH2_SESSION *session; /* ssh session */
62 LIBSSH2_SFTP *sftp; /* sftp session */
63 LIBSSH2_SFTP_HANDLE *sftp_handle; /* sftp remote file handle */
65 /* See ssh_seek() function below. */
69 /* File attributes at open. We try to keep the .filesize field
70 * updated if it changes (eg by writing at the end of the file).
72 LIBSSH2_SFTP_ATTRIBUTES attrs;
74 InetSocketAddress *inet;
76 /* Used to warn if 'flush' is not supported. */
77 bool unsafe_flush_warning;
80 * Store the user name for ssh_refresh_filename() because the
81 * default depends on the system you are on -- therefore, when we
82 * generate a filename, it should always contain the user name we
88 static void ssh_state_init(BDRVSSHState *s)
90 memset(s, 0, sizeof *s);
93 qemu_co_mutex_init(&s->lock);
96 static void ssh_state_free(BDRVSSHState *s)
100 if (s->sftp_handle) {
101 libssh2_sftp_close(s->sftp_handle);
104 libssh2_sftp_shutdown(s->sftp);
107 libssh2_session_disconnect(s->session,
108 "from qemu ssh client: "
109 "user closed the connection");
110 libssh2_session_free(s->session);
117 static void GCC_FMT_ATTR(3, 4)
118 session_error_setg(Error **errp, BDRVSSHState *s, const char *fs, ...)
124 msg = g_strdup_vprintf(fs, args);
131 /* This is not an errno. See <libssh2.h>. */
132 ssh_err_code = libssh2_session_last_error(s->session,
134 error_setg(errp, "%s: %s (libssh2 error code: %d)",
135 msg, ssh_err, ssh_err_code);
137 error_setg(errp, "%s", msg);
142 static void GCC_FMT_ATTR(3, 4)
143 sftp_error_setg(Error **errp, BDRVSSHState *s, const char *fs, ...)
149 msg = g_strdup_vprintf(fs, args);
155 unsigned long sftp_err_code;
157 /* This is not an errno. See <libssh2.h>. */
158 ssh_err_code = libssh2_session_last_error(s->session,
160 /* See <libssh2_sftp.h>. */
161 sftp_err_code = libssh2_sftp_last_error((s)->sftp);
164 "%s: %s (libssh2 error code: %d, sftp error code: %lu)",
165 msg, ssh_err, ssh_err_code, sftp_err_code);
167 error_setg(errp, "%s", msg);
172 static void sftp_error_trace(BDRVSSHState *s, const char *op)
176 unsigned long sftp_err_code;
178 /* This is not an errno. See <libssh2.h>. */
179 ssh_err_code = libssh2_session_last_error(s->session,
181 /* See <libssh2_sftp.h>. */
182 sftp_err_code = libssh2_sftp_last_error((s)->sftp);
184 trace_sftp_error(op, ssh_err, ssh_err_code, sftp_err_code);
187 static int parse_uri(const char *filename, QDict *options, Error **errp)
194 uri = uri_parse(filename);
199 if (g_strcmp0(uri->scheme, "ssh") != 0) {
200 error_setg(errp, "URI scheme must be 'ssh'");
204 if (!uri->server || strcmp(uri->server, "") == 0) {
205 error_setg(errp, "missing hostname in URI");
209 if (!uri->path || strcmp(uri->path, "") == 0) {
210 error_setg(errp, "missing remote path in URI");
214 qp = query_params_parse(uri->query);
216 error_setg(errp, "could not parse query parameters");
220 if(uri->user && strcmp(uri->user, "") != 0) {
221 qdict_put_str(options, "user", uri->user);
224 qdict_put_str(options, "server.host", uri->server);
226 port_str = g_strdup_printf("%d", uri->port ?: 22);
227 qdict_put_str(options, "server.port", port_str);
230 qdict_put_str(options, "path", uri->path);
232 /* Pick out any query parameters that we understand, and ignore
235 for (i = 0; i < qp->n; ++i) {
236 if (strcmp(qp->p[i].name, "host_key_check") == 0) {
237 qdict_put_str(options, "host_key_check", qp->p[i].value);
241 query_params_free(qp);
252 static bool ssh_has_filename_options_conflict(QDict *options, Error **errp)
254 const QDictEntry *qe;
256 for (qe = qdict_first(options); qe; qe = qdict_next(options, qe)) {
257 if (!strcmp(qe->key, "host") ||
258 !strcmp(qe->key, "port") ||
259 !strcmp(qe->key, "path") ||
260 !strcmp(qe->key, "user") ||
261 !strcmp(qe->key, "host_key_check") ||
262 strstart(qe->key, "server.", NULL))
264 error_setg(errp, "Option '%s' cannot be used with a file name",
273 static void ssh_parse_filename(const char *filename, QDict *options,
276 if (ssh_has_filename_options_conflict(options, errp)) {
280 parse_uri(filename, options, errp);
283 static int check_host_key_knownhosts(BDRVSSHState *s,
284 const char *host, int port, Error **errp)
287 char *knh_file = NULL;
288 LIBSSH2_KNOWNHOSTS *knh = NULL;
289 struct libssh2_knownhost *found;
295 hostkey = libssh2_session_hostkey(s->session, &len, &type);
298 session_error_setg(errp, s, "failed to read remote host key");
302 knh = libssh2_knownhost_init(s->session);
305 session_error_setg(errp, s,
306 "failed to initialize known hosts support");
310 home = getenv("HOME");
312 knh_file = g_strdup_printf("%s/.ssh/known_hosts", home);
314 knh_file = g_strdup_printf("/root/.ssh/known_hosts");
317 /* Read all known hosts from OpenSSH-style known_hosts file. */
318 libssh2_knownhost_readfile(knh, knh_file, LIBSSH2_KNOWNHOST_FILE_OPENSSH);
320 r = libssh2_knownhost_checkp(knh, host, port, hostkey, len,
321 LIBSSH2_KNOWNHOST_TYPE_PLAIN|
322 LIBSSH2_KNOWNHOST_KEYENC_RAW,
325 case LIBSSH2_KNOWNHOST_CHECK_MATCH:
327 trace_ssh_check_host_key_knownhosts(found->key);
329 case LIBSSH2_KNOWNHOST_CHECK_MISMATCH:
331 session_error_setg(errp, s,
332 "host key does not match the one in known_hosts"
333 " (found key %s)", found->key);
335 case LIBSSH2_KNOWNHOST_CHECK_NOTFOUND:
337 session_error_setg(errp, s, "no host key was found in known_hosts");
339 case LIBSSH2_KNOWNHOST_CHECK_FAILURE:
341 session_error_setg(errp, s,
342 "failure matching the host key with known_hosts");
346 session_error_setg(errp, s, "unknown error matching the host key"
347 " with known_hosts (%d)", r);
351 /* known_hosts checking successful. */
356 libssh2_knownhost_free(knh);
362 static unsigned hex2decimal(char ch)
364 if (ch >= '0' && ch <= '9') {
366 } else if (ch >= 'a' && ch <= 'f') {
367 return 10 + (ch - 'a');
368 } else if (ch >= 'A' && ch <= 'F') {
369 return 10 + (ch - 'A');
375 /* Compare the binary fingerprint (hash of host key) with the
376 * host_key_check parameter.
378 static int compare_fingerprint(const unsigned char *fingerprint, size_t len,
379 const char *host_key_check)
384 while (*host_key_check == ':')
386 if (!qemu_isxdigit(host_key_check[0]) ||
387 !qemu_isxdigit(host_key_check[1]))
389 c = hex2decimal(host_key_check[0]) * 16 +
390 hex2decimal(host_key_check[1]);
391 if (c - *fingerprint != 0)
392 return c - *fingerprint;
397 return *host_key_check - '\0';
401 check_host_key_hash(BDRVSSHState *s, const char *hash,
402 int hash_type, size_t fingerprint_len, Error **errp)
404 const char *fingerprint;
406 fingerprint = libssh2_hostkey_hash(s->session, hash_type);
408 session_error_setg(errp, s, "failed to read remote host key");
412 if(compare_fingerprint((unsigned char *) fingerprint, fingerprint_len,
414 error_setg(errp, "remote host key does not match host_key_check '%s'",
422 static int check_host_key(BDRVSSHState *s, const char *host, int port,
423 SshHostKeyCheck *hkc, Error **errp)
425 SshHostKeyCheckMode mode;
430 mode = SSH_HOST_KEY_CHECK_MODE_KNOWN_HOSTS;
434 case SSH_HOST_KEY_CHECK_MODE_NONE:
436 case SSH_HOST_KEY_CHECK_MODE_HASH:
437 if (hkc->u.hash.type == SSH_HOST_KEY_CHECK_HASH_TYPE_MD5) {
438 return check_host_key_hash(s, hkc->u.hash.hash,
439 LIBSSH2_HOSTKEY_HASH_MD5, 16, errp);
440 } else if (hkc->u.hash.type == SSH_HOST_KEY_CHECK_HASH_TYPE_SHA1) {
441 return check_host_key_hash(s, hkc->u.hash.hash,
442 LIBSSH2_HOSTKEY_HASH_SHA1, 20, errp);
444 g_assert_not_reached();
446 case SSH_HOST_KEY_CHECK_MODE_KNOWN_HOSTS:
447 return check_host_key_knownhosts(s, host, port, errp);
449 g_assert_not_reached();
455 static int authenticate(BDRVSSHState *s, const char *user, Error **errp)
458 const char *userauthlist;
459 LIBSSH2_AGENT *agent = NULL;
460 struct libssh2_agent_publickey *identity;
461 struct libssh2_agent_publickey *prev_identity = NULL;
463 userauthlist = libssh2_userauth_list(s->session, user, strlen(user));
464 if (strstr(userauthlist, "publickey") == NULL) {
467 "remote server does not support \"publickey\" authentication");
471 /* Connect to ssh-agent and try each identity in turn. */
472 agent = libssh2_agent_init(s->session);
475 session_error_setg(errp, s, "failed to initialize ssh-agent support");
478 if (libssh2_agent_connect(agent)) {
480 session_error_setg(errp, s, "failed to connect to ssh-agent");
483 if (libssh2_agent_list_identities(agent)) {
485 session_error_setg(errp, s,
486 "failed requesting identities from ssh-agent");
491 r = libssh2_agent_get_identity(agent, &identity, prev_identity);
492 if (r == 1) { /* end of list */
497 session_error_setg(errp, s,
498 "failed to obtain identity from ssh-agent");
501 r = libssh2_agent_userauth(agent, user, identity);
507 /* Failed to authenticate with this identity, try the next one. */
508 prev_identity = identity;
512 error_setg(errp, "failed to authenticate using publickey authentication "
513 "and the identities held by your ssh-agent");
517 /* Note: libssh2 implementation implicitly calls
518 * libssh2_agent_disconnect if necessary.
520 libssh2_agent_free(agent);
526 static QemuOptsList ssh_runtime_opts = {
528 .head = QTAILQ_HEAD_INITIALIZER(ssh_runtime_opts.head),
532 .type = QEMU_OPT_STRING,
533 .help = "Host to connect to",
537 .type = QEMU_OPT_NUMBER,
538 .help = "Port to connect to",
541 .name = "host_key_check",
542 .type = QEMU_OPT_STRING,
543 .help = "Defines how and what to check the host key against",
545 { /* end of list */ }
549 static bool ssh_process_legacy_options(QDict *output_opts,
550 QemuOpts *legacy_opts,
553 const char *host = qemu_opt_get(legacy_opts, "host");
554 const char *port = qemu_opt_get(legacy_opts, "port");
555 const char *host_key_check = qemu_opt_get(legacy_opts, "host_key_check");
558 error_setg(errp, "port may not be used without host");
563 qdict_put_str(output_opts, "server.host", host);
564 qdict_put_str(output_opts, "server.port", port ?: stringify(22));
567 if (host_key_check) {
568 if (strcmp(host_key_check, "no") == 0) {
569 qdict_put_str(output_opts, "host-key-check.mode", "none");
570 } else if (strncmp(host_key_check, "md5:", 4) == 0) {
571 qdict_put_str(output_opts, "host-key-check.mode", "hash");
572 qdict_put_str(output_opts, "host-key-check.type", "md5");
573 qdict_put_str(output_opts, "host-key-check.hash",
575 } else if (strncmp(host_key_check, "sha1:", 5) == 0) {
576 qdict_put_str(output_opts, "host-key-check.mode", "hash");
577 qdict_put_str(output_opts, "host-key-check.type", "sha1");
578 qdict_put_str(output_opts, "host-key-check.hash",
580 } else if (strcmp(host_key_check, "yes") == 0) {
581 qdict_put_str(output_opts, "host-key-check.mode", "known_hosts");
583 error_setg(errp, "unknown host_key_check setting (%s)",
592 static BlockdevOptionsSsh *ssh_parse_options(QDict *options, Error **errp)
594 BlockdevOptionsSsh *result = NULL;
595 QemuOpts *opts = NULL;
596 Error *local_err = NULL;
600 /* Translate legacy options */
601 opts = qemu_opts_create(&ssh_runtime_opts, NULL, 0, &error_abort);
602 qemu_opts_absorb_qdict(opts, options, &local_err);
604 error_propagate(errp, local_err);
608 if (!ssh_process_legacy_options(options, opts, errp)) {
612 /* Create the QAPI object */
613 v = qobject_input_visitor_new_flat_confused(options, errp);
618 visit_type_BlockdevOptionsSsh(v, NULL, &result, &local_err);
622 error_propagate(errp, local_err);
626 /* Remove the processed options from the QDict (the visitor processes
627 * _all_ options in the QDict) */
628 while ((e = qdict_first(options))) {
629 qdict_del(options, e->key);
637 static int connect_to_ssh(BDRVSSHState *s, BlockdevOptionsSsh *opts,
638 int ssh_flags, int creat_mode, Error **errp)
643 if (opts->has_user) {
644 s->user = g_strdup(opts->user);
646 s->user = g_strdup(g_get_user_name());
648 error_setg_errno(errp, errno, "Can't get user name");
654 /* Pop the config into our state object, Exit if invalid */
655 s->inet = opts->server;
658 if (qemu_strtol(s->inet->port, NULL, 10, &port) < 0) {
659 error_setg(errp, "Use only numeric port value");
664 /* Open the socket and connect. */
665 s->sock = inet_connect_saddr(s->inet, errp);
671 /* Create SSH session. */
672 s->session = libssh2_session_init();
675 session_error_setg(errp, s, "failed to initialize libssh2 session");
679 #if TRACE_LIBSSH2 != 0
680 libssh2_trace(s->session, TRACE_LIBSSH2);
683 r = libssh2_session_handshake(s->session, s->sock);
686 session_error_setg(errp, s, "failed to establish SSH session");
690 /* Check the remote host's key against known_hosts. */
691 ret = check_host_key(s, s->inet->host, port, opts->host_key_check, errp);
697 ret = authenticate(s, s->user, errp);
703 s->sftp = libssh2_sftp_init(s->session);
705 session_error_setg(errp, s, "failed to initialize sftp handle");
710 /* Open the remote file. */
711 trace_ssh_connect_to_ssh(opts->path, ssh_flags, creat_mode);
712 s->sftp_handle = libssh2_sftp_open(s->sftp, opts->path, ssh_flags,
714 if (!s->sftp_handle) {
715 session_error_setg(errp, s, "failed to open remote file '%s'",
721 r = libssh2_sftp_fstat(s->sftp_handle, &s->attrs);
723 sftp_error_setg(errp, s, "failed to read file attributes");
730 if (s->sftp_handle) {
731 libssh2_sftp_close(s->sftp_handle);
733 s->sftp_handle = NULL;
735 libssh2_sftp_shutdown(s->sftp);
739 libssh2_session_disconnect(s->session,
740 "from qemu ssh client: "
741 "error opening connection");
742 libssh2_session_free(s->session);
749 static int ssh_file_open(BlockDriverState *bs, QDict *options, int bdrv_flags,
752 BDRVSSHState *s = bs->opaque;
753 BlockdevOptionsSsh *opts;
759 ssh_flags = LIBSSH2_FXF_READ;
760 if (bdrv_flags & BDRV_O_RDWR) {
761 ssh_flags |= LIBSSH2_FXF_WRITE;
764 opts = ssh_parse_options(options, errp);
770 ret = connect_to_ssh(s, opts, ssh_flags, 0, errp);
775 /* Go non-blocking. */
776 libssh2_session_set_blocking(s->session, 0);
778 qapi_free_BlockdevOptionsSsh(opts);
788 qapi_free_BlockdevOptionsSsh(opts);
793 /* Note: This is a blocking operation */
794 static int ssh_grow_file(BDRVSSHState *s, int64_t offset, Error **errp)
797 char c[1] = { '\0' };
798 int was_blocking = libssh2_session_get_blocking(s->session);
800 /* offset must be strictly greater than the current size so we do
801 * not overwrite anything */
802 assert(offset > 0 && offset > s->attrs.filesize);
804 libssh2_session_set_blocking(s->session, 1);
806 libssh2_sftp_seek64(s->sftp_handle, offset - 1);
807 ret = libssh2_sftp_write(s->sftp_handle, c, 1);
809 libssh2_session_set_blocking(s->session, was_blocking);
812 sftp_error_setg(errp, s, "Failed to grow file");
816 s->attrs.filesize = offset;
820 static QemuOptsList ssh_create_opts = {
821 .name = "ssh-create-opts",
822 .head = QTAILQ_HEAD_INITIALIZER(ssh_create_opts.head),
825 .name = BLOCK_OPT_SIZE,
826 .type = QEMU_OPT_SIZE,
827 .help = "Virtual disk size"
829 { /* end of list */ }
833 static int ssh_co_create(BlockdevCreateOptions *options, Error **errp)
835 BlockdevCreateOptionsSsh *opts = &options->u.ssh;
839 assert(options->driver == BLOCKDEV_DRIVER_SSH);
843 ret = connect_to_ssh(&s, opts->location,
844 LIBSSH2_FXF_READ|LIBSSH2_FXF_WRITE|
845 LIBSSH2_FXF_CREAT|LIBSSH2_FXF_TRUNC,
851 if (opts->size > 0) {
852 ret = ssh_grow_file(&s, opts->size, errp);
864 static int coroutine_fn ssh_co_create_opts(const char *filename, QemuOpts *opts,
867 BlockdevCreateOptions *create_options;
868 BlockdevCreateOptionsSsh *ssh_opts;
870 QDict *uri_options = NULL;
872 create_options = g_new0(BlockdevCreateOptions, 1);
873 create_options->driver = BLOCKDEV_DRIVER_SSH;
874 ssh_opts = &create_options->u.ssh;
876 /* Get desired file size. */
877 ssh_opts->size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
879 trace_ssh_co_create_opts(ssh_opts->size);
881 uri_options = qdict_new();
882 ret = parse_uri(filename, uri_options, errp);
887 ssh_opts->location = ssh_parse_options(uri_options, errp);
888 if (ssh_opts->location == NULL) {
893 ret = ssh_co_create(create_options, errp);
896 qobject_unref(uri_options);
897 qapi_free_BlockdevCreateOptions(create_options);
901 static void ssh_close(BlockDriverState *bs)
903 BDRVSSHState *s = bs->opaque;
908 static int ssh_has_zero_init(BlockDriverState *bs)
910 BDRVSSHState *s = bs->opaque;
911 /* Assume false, unless we can positively prove it's true. */
912 int has_zero_init = 0;
914 if (s->attrs.flags & LIBSSH2_SFTP_ATTR_PERMISSIONS) {
915 if (s->attrs.permissions & LIBSSH2_SFTP_S_IFREG) {
920 return has_zero_init;
923 typedef struct BDRVSSHRestart {
924 BlockDriverState *bs;
928 static void restart_coroutine(void *opaque)
930 BDRVSSHRestart *restart = opaque;
931 BlockDriverState *bs = restart->bs;
932 BDRVSSHState *s = bs->opaque;
933 AioContext *ctx = bdrv_get_aio_context(bs);
935 trace_ssh_restart_coroutine(restart->co);
936 aio_set_fd_handler(ctx, s->sock, false, NULL, NULL, NULL, NULL);
938 aio_co_wake(restart->co);
941 /* A non-blocking call returned EAGAIN, so yield, ensuring the
942 * handlers are set up so that we'll be rescheduled when there is an
943 * interesting event on the socket.
945 static coroutine_fn void co_yield(BDRVSSHState *s, BlockDriverState *bs)
948 IOHandler *rd_handler = NULL, *wr_handler = NULL;
949 BDRVSSHRestart restart = {
951 .co = qemu_coroutine_self()
954 r = libssh2_session_block_directions(s->session);
956 if (r & LIBSSH2_SESSION_BLOCK_INBOUND) {
957 rd_handler = restart_coroutine;
959 if (r & LIBSSH2_SESSION_BLOCK_OUTBOUND) {
960 wr_handler = restart_coroutine;
963 trace_ssh_co_yield(s->sock, rd_handler, wr_handler);
965 aio_set_fd_handler(bdrv_get_aio_context(bs), s->sock,
966 false, rd_handler, wr_handler, NULL, &restart);
967 qemu_coroutine_yield();
968 trace_ssh_co_yield_back(s->sock);
971 /* SFTP has a function `libssh2_sftp_seek64' which seeks to a position
972 * in the remote file. Notice that it just updates a field in the
973 * sftp_handle structure, so there is no network traffic and it cannot
976 * However, `libssh2_sftp_seek64' does have a catastrophic effect on
977 * performance since it causes the handle to throw away all in-flight
978 * reads and buffered readahead data. Therefore this function tries
979 * to be intelligent about when to call the underlying libssh2 function.
981 #define SSH_SEEK_WRITE 0
982 #define SSH_SEEK_READ 1
983 #define SSH_SEEK_FORCE 2
985 static void ssh_seek(BDRVSSHState *s, int64_t offset, int flags)
987 bool op_read = (flags & SSH_SEEK_READ) != 0;
988 bool force = (flags & SSH_SEEK_FORCE) != 0;
990 if (force || op_read != s->offset_op_read || offset != s->offset) {
991 trace_ssh_seek(offset);
992 libssh2_sftp_seek64(s->sftp_handle, offset);
994 s->offset_op_read = op_read;
998 static coroutine_fn int ssh_read(BDRVSSHState *s, BlockDriverState *bs,
999 int64_t offset, size_t size,
1004 char *buf, *end_of_vec;
1007 trace_ssh_read(offset, size);
1009 ssh_seek(s, offset, SSH_SEEK_READ);
1011 /* This keeps track of the current iovec element ('i'), where we
1012 * will write to next ('buf'), and the end of the current iovec
1017 end_of_vec = i->iov_base + i->iov_len;
1019 /* libssh2 has a hard-coded limit of 2000 bytes per request,
1020 * although it will also do readahead behind our backs. Therefore
1021 * we may have to do repeated reads here until we have read 'size'
1024 for (got = 0; got < size; ) {
1026 trace_ssh_read_buf(buf, end_of_vec - buf);
1027 r = libssh2_sftp_read(s->sftp_handle, buf, end_of_vec - buf);
1028 trace_ssh_read_return(r);
1030 if (r == LIBSSH2_ERROR_EAGAIN || r == LIBSSH2_ERROR_TIMEOUT) {
1035 sftp_error_trace(s, "read");
1040 /* EOF: Short read so pad the buffer with zeroes and return it. */
1041 qemu_iovec_memset(qiov, got, 0, size - got);
1048 if (buf >= end_of_vec && got < size) {
1051 end_of_vec = i->iov_base + i->iov_len;
1058 static coroutine_fn int ssh_co_readv(BlockDriverState *bs,
1060 int nb_sectors, QEMUIOVector *qiov)
1062 BDRVSSHState *s = bs->opaque;
1065 qemu_co_mutex_lock(&s->lock);
1066 ret = ssh_read(s, bs, sector_num * BDRV_SECTOR_SIZE,
1067 nb_sectors * BDRV_SECTOR_SIZE, qiov);
1068 qemu_co_mutex_unlock(&s->lock);
1073 static int ssh_write(BDRVSSHState *s, BlockDriverState *bs,
1074 int64_t offset, size_t size,
1079 char *buf, *end_of_vec;
1082 trace_ssh_write(offset, size);
1084 ssh_seek(s, offset, SSH_SEEK_WRITE);
1086 /* This keeps track of the current iovec element ('i'), where we
1087 * will read from next ('buf'), and the end of the current iovec
1092 end_of_vec = i->iov_base + i->iov_len;
1094 for (written = 0; written < size; ) {
1096 trace_ssh_write_buf(buf, end_of_vec - buf);
1097 r = libssh2_sftp_write(s->sftp_handle, buf, end_of_vec - buf);
1098 trace_ssh_write_return(r);
1100 if (r == LIBSSH2_ERROR_EAGAIN || r == LIBSSH2_ERROR_TIMEOUT) {
1105 sftp_error_trace(s, "write");
1109 /* The libssh2 API is very unclear about this. A comment in
1110 * the code says "nothing was acked, and no EAGAIN was
1111 * received!" which apparently means that no data got sent
1112 * out, and the underlying channel didn't return any EAGAIN
1113 * indication. I think this is a bug in either libssh2 or
1114 * OpenSSH (server-side). In any case, forcing a seek (to
1115 * discard libssh2 internal buffers), and then trying again
1119 ssh_seek(s, offset + written, SSH_SEEK_WRITE|SSH_SEEK_FORCE);
1127 if (buf >= end_of_vec && written < size) {
1130 end_of_vec = i->iov_base + i->iov_len;
1133 if (offset + written > s->attrs.filesize)
1134 s->attrs.filesize = offset + written;
1140 static coroutine_fn int ssh_co_writev(BlockDriverState *bs,
1142 int nb_sectors, QEMUIOVector *qiov,
1145 BDRVSSHState *s = bs->opaque;
1149 qemu_co_mutex_lock(&s->lock);
1150 ret = ssh_write(s, bs, sector_num * BDRV_SECTOR_SIZE,
1151 nb_sectors * BDRV_SECTOR_SIZE, qiov);
1152 qemu_co_mutex_unlock(&s->lock);
1157 static void unsafe_flush_warning(BDRVSSHState *s, const char *what)
1159 if (!s->unsafe_flush_warning) {
1160 warn_report("ssh server %s does not support fsync",
1163 error_report("to support fsync, you need %s", what);
1165 s->unsafe_flush_warning = true;
1169 #ifdef HAS_LIBSSH2_SFTP_FSYNC
1171 static coroutine_fn int ssh_flush(BDRVSSHState *s, BlockDriverState *bs)
1177 r = libssh2_sftp_fsync(s->sftp_handle);
1178 if (r == LIBSSH2_ERROR_EAGAIN || r == LIBSSH2_ERROR_TIMEOUT) {
1182 if (r == LIBSSH2_ERROR_SFTP_PROTOCOL &&
1183 libssh2_sftp_last_error(s->sftp) == LIBSSH2_FX_OP_UNSUPPORTED) {
1184 unsafe_flush_warning(s, "OpenSSH >= 6.3");
1188 sftp_error_trace(s, "fsync");
1195 static coroutine_fn int ssh_co_flush(BlockDriverState *bs)
1197 BDRVSSHState *s = bs->opaque;
1200 qemu_co_mutex_lock(&s->lock);
1201 ret = ssh_flush(s, bs);
1202 qemu_co_mutex_unlock(&s->lock);
1207 #else /* !HAS_LIBSSH2_SFTP_FSYNC */
1209 static coroutine_fn int ssh_co_flush(BlockDriverState *bs)
1211 BDRVSSHState *s = bs->opaque;
1213 unsafe_flush_warning(s, "libssh2 >= 1.4.4");
1217 #endif /* !HAS_LIBSSH2_SFTP_FSYNC */
1219 static int64_t ssh_getlength(BlockDriverState *bs)
1221 BDRVSSHState *s = bs->opaque;
1224 /* Note we cannot make a libssh2 call here. */
1225 length = (int64_t) s->attrs.filesize;
1226 trace_ssh_getlength(length);
1231 static int coroutine_fn ssh_co_truncate(BlockDriverState *bs, int64_t offset,
1232 PreallocMode prealloc, Error **errp)
1234 BDRVSSHState *s = bs->opaque;
1236 if (prealloc != PREALLOC_MODE_OFF) {
1237 error_setg(errp, "Unsupported preallocation mode '%s'",
1238 PreallocMode_str(prealloc));
1242 if (offset < s->attrs.filesize) {
1243 error_setg(errp, "ssh driver does not support shrinking files");
1247 if (offset == s->attrs.filesize) {
1251 return ssh_grow_file(s, offset, errp);
1254 static void ssh_refresh_filename(BlockDriverState *bs)
1256 BDRVSSHState *s = bs->opaque;
1257 const char *path, *host_key_check;
1261 * None of these options can be represented in a plain "host:port"
1262 * format, so if any was given, we have to abort.
1264 if (s->inet->has_ipv4 || s->inet->has_ipv6 || s->inet->has_to ||
1265 s->inet->has_numeric)
1270 path = qdict_get_try_str(bs->full_open_options, "path");
1271 assert(path); /* mandatory option */
1273 host_key_check = qdict_get_try_str(bs->full_open_options, "host_key_check");
1275 ret = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
1276 "ssh://%s@%s:%s%s%s%s",
1277 s->user, s->inet->host, s->inet->port, path,
1278 host_key_check ? "?host_key_check=" : "",
1279 host_key_check ?: "");
1280 if (ret >= sizeof(bs->exact_filename)) {
1281 /* An overflow makes the filename unusable, so do not report any */
1282 bs->exact_filename[0] = '\0';
1286 static char *ssh_bdrv_dirname(BlockDriverState *bs, Error **errp)
1288 if (qdict_haskey(bs->full_open_options, "host_key_check")) {
1290 * We cannot generate a simple prefix if we would have to
1291 * append a query string.
1294 "Cannot generate a base directory with host_key_check set");
1298 if (bs->exact_filename[0] == '\0') {
1299 error_setg(errp, "Cannot generate a base directory for this ssh node");
1303 return path_combine(bs->exact_filename, "");
1306 static const char *const ssh_strong_runtime_opts[] = {
1317 static BlockDriver bdrv_ssh = {
1318 .format_name = "ssh",
1319 .protocol_name = "ssh",
1320 .instance_size = sizeof(BDRVSSHState),
1321 .bdrv_parse_filename = ssh_parse_filename,
1322 .bdrv_file_open = ssh_file_open,
1323 .bdrv_co_create = ssh_co_create,
1324 .bdrv_co_create_opts = ssh_co_create_opts,
1325 .bdrv_close = ssh_close,
1326 .bdrv_has_zero_init = ssh_has_zero_init,
1327 .bdrv_co_readv = ssh_co_readv,
1328 .bdrv_co_writev = ssh_co_writev,
1329 .bdrv_getlength = ssh_getlength,
1330 .bdrv_co_truncate = ssh_co_truncate,
1331 .bdrv_co_flush_to_disk = ssh_co_flush,
1332 .bdrv_refresh_filename = ssh_refresh_filename,
1333 .bdrv_dirname = ssh_bdrv_dirname,
1334 .create_opts = &ssh_create_opts,
1335 .strong_runtime_opts = ssh_strong_runtime_opts,
1338 static void bdrv_ssh_init(void)
1342 r = libssh2_init(0);
1344 fprintf(stderr, "libssh2 initialization failed, %d\n", r);
1348 bdrv_register(&bdrv_ssh);
1351 block_init(bdrv_ssh_init);