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 static void ssh_state_init(BDRVSSHState *s)
82 memset(s, 0, sizeof *s);
85 qemu_co_mutex_init(&s->lock);
88 static void ssh_state_free(BDRVSSHState *s)
91 libssh2_sftp_close(s->sftp_handle);
94 libssh2_sftp_shutdown(s->sftp);
97 libssh2_session_disconnect(s->session,
98 "from qemu ssh client: "
99 "user closed the connection");
100 libssh2_session_free(s->session);
107 static void GCC_FMT_ATTR(3, 4)
108 session_error_setg(Error **errp, BDRVSSHState *s, const char *fs, ...)
114 msg = g_strdup_vprintf(fs, args);
121 /* This is not an errno. See <libssh2.h>. */
122 ssh_err_code = libssh2_session_last_error(s->session,
124 error_setg(errp, "%s: %s (libssh2 error code: %d)",
125 msg, ssh_err, ssh_err_code);
127 error_setg(errp, "%s", msg);
132 static void GCC_FMT_ATTR(3, 4)
133 sftp_error_setg(Error **errp, BDRVSSHState *s, const char *fs, ...)
139 msg = g_strdup_vprintf(fs, args);
145 unsigned long sftp_err_code;
147 /* This is not an errno. See <libssh2.h>. */
148 ssh_err_code = libssh2_session_last_error(s->session,
150 /* See <libssh2_sftp.h>. */
151 sftp_err_code = libssh2_sftp_last_error((s)->sftp);
154 "%s: %s (libssh2 error code: %d, sftp error code: %lu)",
155 msg, ssh_err, ssh_err_code, sftp_err_code);
157 error_setg(errp, "%s", msg);
162 static void GCC_FMT_ATTR(2, 3)
163 sftp_error_report(BDRVSSHState *s, const char *fs, ...)
168 error_vprintf(fs, args);
173 unsigned long sftp_err_code;
175 /* This is not an errno. See <libssh2.h>. */
176 ssh_err_code = libssh2_session_last_error(s->session,
178 /* See <libssh2_sftp.h>. */
179 sftp_err_code = libssh2_sftp_last_error((s)->sftp);
181 error_printf(": %s (libssh2 error code: %d, sftp error code: %lu)",
182 ssh_err, ssh_err_code, sftp_err_code);
189 static int parse_uri(const char *filename, QDict *options, Error **errp)
196 uri = uri_parse(filename);
201 if (g_strcmp0(uri->scheme, "ssh") != 0) {
202 error_setg(errp, "URI scheme must be 'ssh'");
206 if (!uri->server || strcmp(uri->server, "") == 0) {
207 error_setg(errp, "missing hostname in URI");
211 if (!uri->path || strcmp(uri->path, "") == 0) {
212 error_setg(errp, "missing remote path in URI");
216 qp = query_params_parse(uri->query);
218 error_setg(errp, "could not parse query parameters");
222 if(uri->user && strcmp(uri->user, "") != 0) {
223 qdict_put_str(options, "user", uri->user);
226 qdict_put_str(options, "server.host", uri->server);
228 port_str = g_strdup_printf("%d", uri->port ?: 22);
229 qdict_put_str(options, "server.port", port_str);
232 qdict_put_str(options, "path", uri->path);
234 /* Pick out any query parameters that we understand, and ignore
237 for (i = 0; i < qp->n; ++i) {
238 if (strcmp(qp->p[i].name, "host_key_check") == 0) {
239 qdict_put_str(options, "host_key_check", qp->p[i].value);
243 query_params_free(qp);
254 static bool ssh_has_filename_options_conflict(QDict *options, Error **errp)
256 const QDictEntry *qe;
258 for (qe = qdict_first(options); qe; qe = qdict_next(options, qe)) {
259 if (!strcmp(qe->key, "host") ||
260 !strcmp(qe->key, "port") ||
261 !strcmp(qe->key, "path") ||
262 !strcmp(qe->key, "user") ||
263 !strcmp(qe->key, "host_key_check") ||
264 strstart(qe->key, "server.", NULL))
266 error_setg(errp, "Option '%s' cannot be used with a file name",
275 static void ssh_parse_filename(const char *filename, QDict *options,
278 if (ssh_has_filename_options_conflict(options, errp)) {
282 parse_uri(filename, options, errp);
285 static int check_host_key_knownhosts(BDRVSSHState *s,
286 const char *host, int port, Error **errp)
289 char *knh_file = NULL;
290 LIBSSH2_KNOWNHOSTS *knh = NULL;
291 struct libssh2_knownhost *found;
297 hostkey = libssh2_session_hostkey(s->session, &len, &type);
300 session_error_setg(errp, s, "failed to read remote host key");
304 knh = libssh2_knownhost_init(s->session);
307 session_error_setg(errp, s,
308 "failed to initialize known hosts support");
312 home = getenv("HOME");
314 knh_file = g_strdup_printf("%s/.ssh/known_hosts", home);
316 knh_file = g_strdup_printf("/root/.ssh/known_hosts");
319 /* Read all known hosts from OpenSSH-style known_hosts file. */
320 libssh2_knownhost_readfile(knh, knh_file, LIBSSH2_KNOWNHOST_FILE_OPENSSH);
322 r = libssh2_knownhost_checkp(knh, host, port, hostkey, len,
323 LIBSSH2_KNOWNHOST_TYPE_PLAIN|
324 LIBSSH2_KNOWNHOST_KEYENC_RAW,
327 case LIBSSH2_KNOWNHOST_CHECK_MATCH:
329 trace_ssh_check_host_key_knownhosts(found->key);
331 case LIBSSH2_KNOWNHOST_CHECK_MISMATCH:
333 session_error_setg(errp, s,
334 "host key does not match the one in known_hosts"
335 " (found key %s)", found->key);
337 case LIBSSH2_KNOWNHOST_CHECK_NOTFOUND:
339 session_error_setg(errp, s, "no host key was found in known_hosts");
341 case LIBSSH2_KNOWNHOST_CHECK_FAILURE:
343 session_error_setg(errp, s,
344 "failure matching the host key with known_hosts");
348 session_error_setg(errp, s, "unknown error matching the host key"
349 " with known_hosts (%d)", r);
353 /* known_hosts checking successful. */
358 libssh2_knownhost_free(knh);
364 static unsigned hex2decimal(char ch)
366 if (ch >= '0' && ch <= '9') {
368 } else if (ch >= 'a' && ch <= 'f') {
369 return 10 + (ch - 'a');
370 } else if (ch >= 'A' && ch <= 'F') {
371 return 10 + (ch - 'A');
377 /* Compare the binary fingerprint (hash of host key) with the
378 * host_key_check parameter.
380 static int compare_fingerprint(const unsigned char *fingerprint, size_t len,
381 const char *host_key_check)
386 while (*host_key_check == ':')
388 if (!qemu_isxdigit(host_key_check[0]) ||
389 !qemu_isxdigit(host_key_check[1]))
391 c = hex2decimal(host_key_check[0]) * 16 +
392 hex2decimal(host_key_check[1]);
393 if (c - *fingerprint != 0)
394 return c - *fingerprint;
399 return *host_key_check - '\0';
403 check_host_key_hash(BDRVSSHState *s, const char *hash,
404 int hash_type, size_t fingerprint_len, Error **errp)
406 const char *fingerprint;
408 fingerprint = libssh2_hostkey_hash(s->session, hash_type);
410 session_error_setg(errp, s, "failed to read remote host key");
414 if(compare_fingerprint((unsigned char *) fingerprint, fingerprint_len,
416 error_setg(errp, "remote host key does not match host_key_check '%s'",
424 static int check_host_key(BDRVSSHState *s, const char *host, int port,
425 SshHostKeyCheck *hkc, Error **errp)
427 SshHostKeyCheckMode mode;
432 mode = SSH_HOST_KEY_CHECK_MODE_KNOWN_HOSTS;
436 case SSH_HOST_KEY_CHECK_MODE_NONE:
438 case SSH_HOST_KEY_CHECK_MODE_HASH:
439 if (hkc->u.hash.type == SSH_HOST_KEY_CHECK_HASH_TYPE_MD5) {
440 return check_host_key_hash(s, hkc->u.hash.hash,
441 LIBSSH2_HOSTKEY_HASH_MD5, 16, errp);
442 } else if (hkc->u.hash.type == SSH_HOST_KEY_CHECK_HASH_TYPE_SHA1) {
443 return check_host_key_hash(s, hkc->u.hash.hash,
444 LIBSSH2_HOSTKEY_HASH_SHA1, 20, errp);
446 g_assert_not_reached();
448 case SSH_HOST_KEY_CHECK_MODE_KNOWN_HOSTS:
449 return check_host_key_knownhosts(s, host, port, errp);
451 g_assert_not_reached();
457 static int authenticate(BDRVSSHState *s, const char *user, Error **errp)
460 const char *userauthlist;
461 LIBSSH2_AGENT *agent = NULL;
462 struct libssh2_agent_publickey *identity;
463 struct libssh2_agent_publickey *prev_identity = NULL;
465 userauthlist = libssh2_userauth_list(s->session, user, strlen(user));
466 if (strstr(userauthlist, "publickey") == NULL) {
469 "remote server does not support \"publickey\" authentication");
473 /* Connect to ssh-agent and try each identity in turn. */
474 agent = libssh2_agent_init(s->session);
477 session_error_setg(errp, s, "failed to initialize ssh-agent support");
480 if (libssh2_agent_connect(agent)) {
482 session_error_setg(errp, s, "failed to connect to ssh-agent");
485 if (libssh2_agent_list_identities(agent)) {
487 session_error_setg(errp, s,
488 "failed requesting identities from ssh-agent");
493 r = libssh2_agent_get_identity(agent, &identity, prev_identity);
494 if (r == 1) { /* end of list */
499 session_error_setg(errp, s,
500 "failed to obtain identity from ssh-agent");
503 r = libssh2_agent_userauth(agent, user, identity);
509 /* Failed to authenticate with this identity, try the next one. */
510 prev_identity = identity;
514 error_setg(errp, "failed to authenticate using publickey authentication "
515 "and the identities held by your ssh-agent");
519 /* Note: libssh2 implementation implicitly calls
520 * libssh2_agent_disconnect if necessary.
522 libssh2_agent_free(agent);
528 static QemuOptsList ssh_runtime_opts = {
530 .head = QTAILQ_HEAD_INITIALIZER(ssh_runtime_opts.head),
534 .type = QEMU_OPT_STRING,
535 .help = "Host to connect to",
539 .type = QEMU_OPT_NUMBER,
540 .help = "Port to connect to",
543 .name = "host_key_check",
544 .type = QEMU_OPT_STRING,
545 .help = "Defines how and what to check the host key against",
547 { /* end of list */ }
551 static bool ssh_process_legacy_options(QDict *output_opts,
552 QemuOpts *legacy_opts,
555 const char *host = qemu_opt_get(legacy_opts, "host");
556 const char *port = qemu_opt_get(legacy_opts, "port");
557 const char *host_key_check = qemu_opt_get(legacy_opts, "host_key_check");
560 error_setg(errp, "port may not be used without host");
565 qdict_put_str(output_opts, "server.host", host);
566 qdict_put_str(output_opts, "server.port", port ?: stringify(22));
569 if (host_key_check) {
570 if (strcmp(host_key_check, "no") == 0) {
571 qdict_put_str(output_opts, "host-key-check.mode", "none");
572 } else if (strncmp(host_key_check, "md5:", 4) == 0) {
573 qdict_put_str(output_opts, "host-key-check.mode", "hash");
574 qdict_put_str(output_opts, "host-key-check.type", "md5");
575 qdict_put_str(output_opts, "host-key-check.hash",
577 } else if (strncmp(host_key_check, "sha1:", 5) == 0) {
578 qdict_put_str(output_opts, "host-key-check.mode", "hash");
579 qdict_put_str(output_opts, "host-key-check.type", "sha1");
580 qdict_put_str(output_opts, "host-key-check.hash",
582 } else if (strcmp(host_key_check, "yes") == 0) {
583 qdict_put_str(output_opts, "host-key-check.mode", "known_hosts");
585 error_setg(errp, "unknown host_key_check setting (%s)",
594 static BlockdevOptionsSsh *ssh_parse_options(QDict *options, Error **errp)
596 BlockdevOptionsSsh *result = NULL;
597 QemuOpts *opts = NULL;
598 Error *local_err = NULL;
602 /* Translate legacy options */
603 opts = qemu_opts_create(&ssh_runtime_opts, NULL, 0, &error_abort);
604 qemu_opts_absorb_qdict(opts, options, &local_err);
606 error_propagate(errp, local_err);
610 if (!ssh_process_legacy_options(options, opts, errp)) {
614 /* Create the QAPI object */
615 v = qobject_input_visitor_new_flat_confused(options, errp);
620 visit_type_BlockdevOptionsSsh(v, NULL, &result, &local_err);
624 error_propagate(errp, local_err);
628 /* Remove the processed options from the QDict (the visitor processes
629 * _all_ options in the QDict) */
630 while ((e = qdict_first(options))) {
631 qdict_del(options, e->key);
639 static int connect_to_ssh(BDRVSSHState *s, BlockdevOptionsSsh *opts,
640 int ssh_flags, int creat_mode, Error **errp)
646 if (opts->has_user) {
649 user = g_get_user_name();
651 error_setg_errno(errp, errno, "Can't get user name");
657 /* Pop the config into our state object, Exit if invalid */
658 s->inet = opts->server;
661 if (qemu_strtol(s->inet->port, NULL, 10, &port) < 0) {
662 error_setg(errp, "Use only numeric port value");
667 /* Open the socket and connect. */
668 s->sock = inet_connect_saddr(s->inet, errp);
674 /* Create SSH session. */
675 s->session = libssh2_session_init();
678 session_error_setg(errp, s, "failed to initialize libssh2 session");
682 #if TRACE_LIBSSH2 != 0
683 libssh2_trace(s->session, TRACE_LIBSSH2);
686 r = libssh2_session_handshake(s->session, s->sock);
689 session_error_setg(errp, s, "failed to establish SSH session");
693 /* Check the remote host's key against known_hosts. */
694 ret = check_host_key(s, s->inet->host, port, opts->host_key_check, errp);
700 ret = authenticate(s, user, errp);
706 s->sftp = libssh2_sftp_init(s->session);
708 session_error_setg(errp, s, "failed to initialize sftp handle");
713 /* Open the remote file. */
714 trace_ssh_connect_to_ssh(opts->path, ssh_flags, creat_mode);
715 s->sftp_handle = libssh2_sftp_open(s->sftp, opts->path, ssh_flags,
717 if (!s->sftp_handle) {
718 session_error_setg(errp, s, "failed to open remote file '%s'",
724 r = libssh2_sftp_fstat(s->sftp_handle, &s->attrs);
726 sftp_error_setg(errp, s, "failed to read file attributes");
733 if (s->sftp_handle) {
734 libssh2_sftp_close(s->sftp_handle);
736 s->sftp_handle = NULL;
738 libssh2_sftp_shutdown(s->sftp);
742 libssh2_session_disconnect(s->session,
743 "from qemu ssh client: "
744 "error opening connection");
745 libssh2_session_free(s->session);
752 static int ssh_file_open(BlockDriverState *bs, QDict *options, int bdrv_flags,
755 BDRVSSHState *s = bs->opaque;
756 BlockdevOptionsSsh *opts;
762 ssh_flags = LIBSSH2_FXF_READ;
763 if (bdrv_flags & BDRV_O_RDWR) {
764 ssh_flags |= LIBSSH2_FXF_WRITE;
767 opts = ssh_parse_options(options, errp);
773 ret = connect_to_ssh(s, opts, ssh_flags, 0, errp);
778 /* Go non-blocking. */
779 libssh2_session_set_blocking(s->session, 0);
781 qapi_free_BlockdevOptionsSsh(opts);
791 qapi_free_BlockdevOptionsSsh(opts);
796 /* Note: This is a blocking operation */
797 static int ssh_grow_file(BDRVSSHState *s, int64_t offset, Error **errp)
800 char c[1] = { '\0' };
801 int was_blocking = libssh2_session_get_blocking(s->session);
803 /* offset must be strictly greater than the current size so we do
804 * not overwrite anything */
805 assert(offset > 0 && offset > s->attrs.filesize);
807 libssh2_session_set_blocking(s->session, 1);
809 libssh2_sftp_seek64(s->sftp_handle, offset - 1);
810 ret = libssh2_sftp_write(s->sftp_handle, c, 1);
812 libssh2_session_set_blocking(s->session, was_blocking);
815 sftp_error_setg(errp, s, "Failed to grow file");
819 s->attrs.filesize = offset;
823 static QemuOptsList ssh_create_opts = {
824 .name = "ssh-create-opts",
825 .head = QTAILQ_HEAD_INITIALIZER(ssh_create_opts.head),
828 .name = BLOCK_OPT_SIZE,
829 .type = QEMU_OPT_SIZE,
830 .help = "Virtual disk size"
832 { /* end of list */ }
836 static int ssh_co_create(BlockdevCreateOptions *options, Error **errp)
838 BlockdevCreateOptionsSsh *opts = &options->u.ssh;
842 assert(options->driver == BLOCKDEV_DRIVER_SSH);
846 ret = connect_to_ssh(&s, opts->location,
847 LIBSSH2_FXF_READ|LIBSSH2_FXF_WRITE|
848 LIBSSH2_FXF_CREAT|LIBSSH2_FXF_TRUNC,
854 if (opts->size > 0) {
855 ret = ssh_grow_file(&s, opts->size, errp);
867 static int coroutine_fn ssh_co_create_opts(const char *filename, QemuOpts *opts,
870 BlockdevCreateOptions *create_options;
871 BlockdevCreateOptionsSsh *ssh_opts;
873 QDict *uri_options = NULL;
875 create_options = g_new0(BlockdevCreateOptions, 1);
876 create_options->driver = BLOCKDEV_DRIVER_SSH;
877 ssh_opts = &create_options->u.ssh;
879 /* Get desired file size. */
880 ssh_opts->size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
882 trace_ssh_co_create_opts(ssh_opts->size);
884 uri_options = qdict_new();
885 ret = parse_uri(filename, uri_options, errp);
890 ssh_opts->location = ssh_parse_options(uri_options, errp);
891 if (ssh_opts->location == NULL) {
896 ret = ssh_co_create(create_options, errp);
899 qobject_unref(uri_options);
900 qapi_free_BlockdevCreateOptions(create_options);
904 static void ssh_close(BlockDriverState *bs)
906 BDRVSSHState *s = bs->opaque;
911 static int ssh_has_zero_init(BlockDriverState *bs)
913 BDRVSSHState *s = bs->opaque;
914 /* Assume false, unless we can positively prove it's true. */
915 int has_zero_init = 0;
917 if (s->attrs.flags & LIBSSH2_SFTP_ATTR_PERMISSIONS) {
918 if (s->attrs.permissions & LIBSSH2_SFTP_S_IFREG) {
923 return has_zero_init;
926 typedef struct BDRVSSHRestart {
927 BlockDriverState *bs;
931 static void restart_coroutine(void *opaque)
933 BDRVSSHRestart *restart = opaque;
934 BlockDriverState *bs = restart->bs;
935 BDRVSSHState *s = bs->opaque;
936 AioContext *ctx = bdrv_get_aio_context(bs);
938 trace_ssh_restart_coroutine(restart->co);
939 aio_set_fd_handler(ctx, s->sock, false, NULL, NULL, NULL, NULL);
941 aio_co_wake(restart->co);
944 /* A non-blocking call returned EAGAIN, so yield, ensuring the
945 * handlers are set up so that we'll be rescheduled when there is an
946 * interesting event on the socket.
948 static coroutine_fn void co_yield(BDRVSSHState *s, BlockDriverState *bs)
951 IOHandler *rd_handler = NULL, *wr_handler = NULL;
952 BDRVSSHRestart restart = {
954 .co = qemu_coroutine_self()
957 r = libssh2_session_block_directions(s->session);
959 if (r & LIBSSH2_SESSION_BLOCK_INBOUND) {
960 rd_handler = restart_coroutine;
962 if (r & LIBSSH2_SESSION_BLOCK_OUTBOUND) {
963 wr_handler = restart_coroutine;
966 trace_ssh_co_yield(s->sock, rd_handler, wr_handler);
968 aio_set_fd_handler(bdrv_get_aio_context(bs), s->sock,
969 false, rd_handler, wr_handler, NULL, &restart);
970 qemu_coroutine_yield();
971 trace_ssh_co_yield_back(s->sock);
974 /* SFTP has a function `libssh2_sftp_seek64' which seeks to a position
975 * in the remote file. Notice that it just updates a field in the
976 * sftp_handle structure, so there is no network traffic and it cannot
979 * However, `libssh2_sftp_seek64' does have a catastrophic effect on
980 * performance since it causes the handle to throw away all in-flight
981 * reads and buffered readahead data. Therefore this function tries
982 * to be intelligent about when to call the underlying libssh2 function.
984 #define SSH_SEEK_WRITE 0
985 #define SSH_SEEK_READ 1
986 #define SSH_SEEK_FORCE 2
988 static void ssh_seek(BDRVSSHState *s, int64_t offset, int flags)
990 bool op_read = (flags & SSH_SEEK_READ) != 0;
991 bool force = (flags & SSH_SEEK_FORCE) != 0;
993 if (force || op_read != s->offset_op_read || offset != s->offset) {
994 trace_ssh_seek(offset);
995 libssh2_sftp_seek64(s->sftp_handle, offset);
997 s->offset_op_read = op_read;
1001 static coroutine_fn int ssh_read(BDRVSSHState *s, BlockDriverState *bs,
1002 int64_t offset, size_t size,
1007 char *buf, *end_of_vec;
1010 trace_ssh_read(offset, size);
1012 ssh_seek(s, offset, SSH_SEEK_READ);
1014 /* This keeps track of the current iovec element ('i'), where we
1015 * will write to next ('buf'), and the end of the current iovec
1020 end_of_vec = i->iov_base + i->iov_len;
1022 /* libssh2 has a hard-coded limit of 2000 bytes per request,
1023 * although it will also do readahead behind our backs. Therefore
1024 * we may have to do repeated reads here until we have read 'size'
1027 for (got = 0; got < size; ) {
1029 trace_ssh_read_buf(buf, end_of_vec - buf);
1030 r = libssh2_sftp_read(s->sftp_handle, buf, end_of_vec - buf);
1031 trace_ssh_read_return(r);
1033 if (r == LIBSSH2_ERROR_EAGAIN || r == LIBSSH2_ERROR_TIMEOUT) {
1038 sftp_error_report(s, "read failed");
1043 /* EOF: Short read so pad the buffer with zeroes and return it. */
1044 qemu_iovec_memset(qiov, got, 0, size - got);
1051 if (buf >= end_of_vec && got < size) {
1054 end_of_vec = i->iov_base + i->iov_len;
1061 static coroutine_fn int ssh_co_readv(BlockDriverState *bs,
1063 int nb_sectors, QEMUIOVector *qiov)
1065 BDRVSSHState *s = bs->opaque;
1068 qemu_co_mutex_lock(&s->lock);
1069 ret = ssh_read(s, bs, sector_num * BDRV_SECTOR_SIZE,
1070 nb_sectors * BDRV_SECTOR_SIZE, qiov);
1071 qemu_co_mutex_unlock(&s->lock);
1076 static int ssh_write(BDRVSSHState *s, BlockDriverState *bs,
1077 int64_t offset, size_t size,
1082 char *buf, *end_of_vec;
1085 trace_ssh_write(offset, size);
1087 ssh_seek(s, offset, SSH_SEEK_WRITE);
1089 /* This keeps track of the current iovec element ('i'), where we
1090 * will read from next ('buf'), and the end of the current iovec
1095 end_of_vec = i->iov_base + i->iov_len;
1097 for (written = 0; written < size; ) {
1099 trace_ssh_write_buf(buf, end_of_vec - buf);
1100 r = libssh2_sftp_write(s->sftp_handle, buf, end_of_vec - buf);
1101 trace_ssh_write_return(r);
1103 if (r == LIBSSH2_ERROR_EAGAIN || r == LIBSSH2_ERROR_TIMEOUT) {
1108 sftp_error_report(s, "write failed");
1112 /* The libssh2 API is very unclear about this. A comment in
1113 * the code says "nothing was acked, and no EAGAIN was
1114 * received!" which apparently means that no data got sent
1115 * out, and the underlying channel didn't return any EAGAIN
1116 * indication. I think this is a bug in either libssh2 or
1117 * OpenSSH (server-side). In any case, forcing a seek (to
1118 * discard libssh2 internal buffers), and then trying again
1122 ssh_seek(s, offset + written, SSH_SEEK_WRITE|SSH_SEEK_FORCE);
1130 if (buf >= end_of_vec && written < size) {
1133 end_of_vec = i->iov_base + i->iov_len;
1136 if (offset + written > s->attrs.filesize)
1137 s->attrs.filesize = offset + written;
1143 static coroutine_fn int ssh_co_writev(BlockDriverState *bs,
1145 int nb_sectors, QEMUIOVector *qiov,
1148 BDRVSSHState *s = bs->opaque;
1152 qemu_co_mutex_lock(&s->lock);
1153 ret = ssh_write(s, bs, sector_num * BDRV_SECTOR_SIZE,
1154 nb_sectors * BDRV_SECTOR_SIZE, qiov);
1155 qemu_co_mutex_unlock(&s->lock);
1160 static void unsafe_flush_warning(BDRVSSHState *s, const char *what)
1162 if (!s->unsafe_flush_warning) {
1163 warn_report("ssh server %s does not support fsync",
1166 error_report("to support fsync, you need %s", what);
1168 s->unsafe_flush_warning = true;
1172 #ifdef HAS_LIBSSH2_SFTP_FSYNC
1174 static coroutine_fn int ssh_flush(BDRVSSHState *s, BlockDriverState *bs)
1180 r = libssh2_sftp_fsync(s->sftp_handle);
1181 if (r == LIBSSH2_ERROR_EAGAIN || r == LIBSSH2_ERROR_TIMEOUT) {
1185 if (r == LIBSSH2_ERROR_SFTP_PROTOCOL &&
1186 libssh2_sftp_last_error(s->sftp) == LIBSSH2_FX_OP_UNSUPPORTED) {
1187 unsafe_flush_warning(s, "OpenSSH >= 6.3");
1191 sftp_error_report(s, "fsync failed");
1198 static coroutine_fn int ssh_co_flush(BlockDriverState *bs)
1200 BDRVSSHState *s = bs->opaque;
1203 qemu_co_mutex_lock(&s->lock);
1204 ret = ssh_flush(s, bs);
1205 qemu_co_mutex_unlock(&s->lock);
1210 #else /* !HAS_LIBSSH2_SFTP_FSYNC */
1212 static coroutine_fn int ssh_co_flush(BlockDriverState *bs)
1214 BDRVSSHState *s = bs->opaque;
1216 unsafe_flush_warning(s, "libssh2 >= 1.4.4");
1220 #endif /* !HAS_LIBSSH2_SFTP_FSYNC */
1222 static int64_t ssh_getlength(BlockDriverState *bs)
1224 BDRVSSHState *s = bs->opaque;
1227 /* Note we cannot make a libssh2 call here. */
1228 length = (int64_t) s->attrs.filesize;
1229 trace_ssh_getlength(length);
1234 static int coroutine_fn ssh_co_truncate(BlockDriverState *bs, int64_t offset,
1235 PreallocMode prealloc, Error **errp)
1237 BDRVSSHState *s = bs->opaque;
1239 if (prealloc != PREALLOC_MODE_OFF) {
1240 error_setg(errp, "Unsupported preallocation mode '%s'",
1241 PreallocMode_str(prealloc));
1245 if (offset < s->attrs.filesize) {
1246 error_setg(errp, "ssh driver does not support shrinking files");
1250 if (offset == s->attrs.filesize) {
1254 return ssh_grow_file(s, offset, errp);
1257 static const char *const ssh_strong_runtime_opts[] = {
1268 static BlockDriver bdrv_ssh = {
1269 .format_name = "ssh",
1270 .protocol_name = "ssh",
1271 .instance_size = sizeof(BDRVSSHState),
1272 .bdrv_parse_filename = ssh_parse_filename,
1273 .bdrv_file_open = ssh_file_open,
1274 .bdrv_co_create = ssh_co_create,
1275 .bdrv_co_create_opts = ssh_co_create_opts,
1276 .bdrv_close = ssh_close,
1277 .bdrv_has_zero_init = ssh_has_zero_init,
1278 .bdrv_co_readv = ssh_co_readv,
1279 .bdrv_co_writev = ssh_co_writev,
1280 .bdrv_getlength = ssh_getlength,
1281 .bdrv_co_truncate = ssh_co_truncate,
1282 .bdrv_co_flush_to_disk = ssh_co_flush,
1283 .create_opts = &ssh_create_opts,
1284 .strong_runtime_opts = ssh_strong_runtime_opts,
1287 static void bdrv_ssh_init(void)
1291 r = libssh2_init(0);
1293 fprintf(stderr, "libssh2 initialization failed, %d\n", r);
1297 bdrv_register(&bdrv_ssh);
1300 block_init(bdrv_ssh_init);