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"
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/module.h"
35 #include "qemu/option.h"
36 #include "qemu/ctype.h"
37 #include "qemu/cutils.h"
38 #include "qemu/sockets.h"
40 #include "qapi/qapi-visit-sockets.h"
41 #include "qapi/qapi-visit-block-core.h"
42 #include "qapi/qmp/qdict.h"
43 #include "qapi/qmp/qstring.h"
44 #include "qapi/qobject-input-visitor.h"
45 #include "qapi/qobject-output-visitor.h"
49 * TRACE_LIBSSH2=<bitmask> enables tracing in libssh2 itself. Note
50 * that this requires that libssh2 was specially compiled with the
51 * `./configure --enable-debug' option, so most likely you will have
52 * to compile it yourself. The meaning of <bitmask> is described
53 * here: http://www.libssh2.org/libssh2_trace.html
55 #define TRACE_LIBSSH2 0 /* or try: LIBSSH2_TRACE_SFTP */
57 typedef struct BDRVSSHState
{
62 int sock
; /* socket */
63 LIBSSH2_SESSION
*session
; /* ssh session */
64 LIBSSH2_SFTP
*sftp
; /* sftp session */
65 LIBSSH2_SFTP_HANDLE
*sftp_handle
; /* sftp remote file handle */
67 /* See ssh_seek() function below. */
71 /* File attributes at open. We try to keep the .filesize field
72 * updated if it changes (eg by writing at the end of the file).
74 LIBSSH2_SFTP_ATTRIBUTES attrs
;
76 InetSocketAddress
*inet
;
78 /* Used to warn if 'flush' is not supported. */
79 bool unsafe_flush_warning
;
82 * Store the user name for ssh_refresh_filename() because the
83 * default depends on the system you are on -- therefore, when we
84 * generate a filename, it should always contain the user name we
90 static void ssh_state_init(BDRVSSHState
*s
)
92 memset(s
, 0, sizeof *s
);
95 qemu_co_mutex_init(&s
->lock
);
98 static void ssh_state_free(BDRVSSHState
*s
)
102 if (s
->sftp_handle
) {
103 libssh2_sftp_close(s
->sftp_handle
);
106 libssh2_sftp_shutdown(s
->sftp
);
109 libssh2_session_disconnect(s
->session
,
110 "from qemu ssh client: "
111 "user closed the connection");
112 libssh2_session_free(s
->session
);
119 static void GCC_FMT_ATTR(3, 4)
120 session_error_setg(Error
**errp
, BDRVSSHState
*s
, const char *fs
, ...)
126 msg
= g_strdup_vprintf(fs
, args
);
133 /* This is not an errno. See <libssh2.h>. */
134 ssh_err_code
= libssh2_session_last_error(s
->session
,
136 error_setg(errp
, "%s: %s (libssh2 error code: %d)",
137 msg
, ssh_err
, ssh_err_code
);
139 error_setg(errp
, "%s", msg
);
144 static void GCC_FMT_ATTR(3, 4)
145 sftp_error_setg(Error
**errp
, BDRVSSHState
*s
, const char *fs
, ...)
151 msg
= g_strdup_vprintf(fs
, args
);
157 unsigned long sftp_err_code
;
159 /* This is not an errno. See <libssh2.h>. */
160 ssh_err_code
= libssh2_session_last_error(s
->session
,
162 /* See <libssh2_sftp.h>. */
163 sftp_err_code
= libssh2_sftp_last_error((s
)->sftp
);
166 "%s: %s (libssh2 error code: %d, sftp error code: %lu)",
167 msg
, ssh_err
, ssh_err_code
, sftp_err_code
);
169 error_setg(errp
, "%s", msg
);
174 static void sftp_error_trace(BDRVSSHState
*s
, const char *op
)
178 unsigned long sftp_err_code
;
180 /* This is not an errno. See <libssh2.h>. */
181 ssh_err_code
= libssh2_session_last_error(s
->session
,
183 /* See <libssh2_sftp.h>. */
184 sftp_err_code
= libssh2_sftp_last_error((s
)->sftp
);
186 trace_sftp_error(op
, 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
)
645 if (opts
->has_user
) {
646 s
->user
= g_strdup(opts
->user
);
648 s
->user
= g_strdup(g_get_user_name());
650 error_setg_errno(errp
, errno
, "Can't get user name");
656 /* Pop the config into our state object, Exit if invalid */
657 s
->inet
= opts
->server
;
660 if (qemu_strtol(s
->inet
->port
, NULL
, 10, &port
) < 0) {
661 error_setg(errp
, "Use only numeric port value");
666 /* Open the socket and connect. */
667 s
->sock
= inet_connect_saddr(s
->inet
, errp
);
673 /* Create SSH session. */
674 s
->session
= libssh2_session_init();
677 session_error_setg(errp
, s
, "failed to initialize libssh2 session");
681 #if TRACE_LIBSSH2 != 0
682 libssh2_trace(s
->session
, TRACE_LIBSSH2
);
685 r
= libssh2_session_handshake(s
->session
, s
->sock
);
688 session_error_setg(errp
, s
, "failed to establish SSH session");
692 /* Check the remote host's key against known_hosts. */
693 ret
= check_host_key(s
, s
->inet
->host
, port
, opts
->host_key_check
, errp
);
699 ret
= authenticate(s
, s
->user
, errp
);
705 s
->sftp
= libssh2_sftp_init(s
->session
);
707 session_error_setg(errp
, s
, "failed to initialize sftp handle");
712 /* Open the remote file. */
713 trace_ssh_connect_to_ssh(opts
->path
, ssh_flags
, creat_mode
);
714 s
->sftp_handle
= libssh2_sftp_open(s
->sftp
, opts
->path
, ssh_flags
,
716 if (!s
->sftp_handle
) {
717 session_error_setg(errp
, s
, "failed to open remote file '%s'",
723 r
= libssh2_sftp_fstat(s
->sftp_handle
, &s
->attrs
);
725 sftp_error_setg(errp
, s
, "failed to read file attributes");
732 if (s
->sftp_handle
) {
733 libssh2_sftp_close(s
->sftp_handle
);
735 s
->sftp_handle
= NULL
;
737 libssh2_sftp_shutdown(s
->sftp
);
741 libssh2_session_disconnect(s
->session
,
742 "from qemu ssh client: "
743 "error opening connection");
744 libssh2_session_free(s
->session
);
751 static int ssh_file_open(BlockDriverState
*bs
, QDict
*options
, int bdrv_flags
,
754 BDRVSSHState
*s
= bs
->opaque
;
755 BlockdevOptionsSsh
*opts
;
761 ssh_flags
= LIBSSH2_FXF_READ
;
762 if (bdrv_flags
& BDRV_O_RDWR
) {
763 ssh_flags
|= LIBSSH2_FXF_WRITE
;
766 opts
= ssh_parse_options(options
, errp
);
772 ret
= connect_to_ssh(s
, opts
, ssh_flags
, 0, errp
);
777 /* Go non-blocking. */
778 libssh2_session_set_blocking(s
->session
, 0);
780 qapi_free_BlockdevOptionsSsh(opts
);
790 qapi_free_BlockdevOptionsSsh(opts
);
795 /* Note: This is a blocking operation */
796 static int ssh_grow_file(BDRVSSHState
*s
, int64_t offset
, Error
**errp
)
799 char c
[1] = { '\0' };
800 int was_blocking
= libssh2_session_get_blocking(s
->session
);
802 /* offset must be strictly greater than the current size so we do
803 * not overwrite anything */
804 assert(offset
> 0 && offset
> s
->attrs
.filesize
);
806 libssh2_session_set_blocking(s
->session
, 1);
808 libssh2_sftp_seek64(s
->sftp_handle
, offset
- 1);
809 ret
= libssh2_sftp_write(s
->sftp_handle
, c
, 1);
811 libssh2_session_set_blocking(s
->session
, was_blocking
);
814 sftp_error_setg(errp
, s
, "Failed to grow file");
818 s
->attrs
.filesize
= offset
;
822 static QemuOptsList ssh_create_opts
= {
823 .name
= "ssh-create-opts",
824 .head
= QTAILQ_HEAD_INITIALIZER(ssh_create_opts
.head
),
827 .name
= BLOCK_OPT_SIZE
,
828 .type
= QEMU_OPT_SIZE
,
829 .help
= "Virtual disk size"
831 { /* end of list */ }
835 static int ssh_co_create(BlockdevCreateOptions
*options
, Error
**errp
)
837 BlockdevCreateOptionsSsh
*opts
= &options
->u
.ssh
;
841 assert(options
->driver
== BLOCKDEV_DRIVER_SSH
);
845 ret
= connect_to_ssh(&s
, opts
->location
,
846 LIBSSH2_FXF_READ
|LIBSSH2_FXF_WRITE
|
847 LIBSSH2_FXF_CREAT
|LIBSSH2_FXF_TRUNC
,
853 if (opts
->size
> 0) {
854 ret
= ssh_grow_file(&s
, opts
->size
, errp
);
866 static int coroutine_fn
ssh_co_create_opts(const char *filename
, QemuOpts
*opts
,
869 BlockdevCreateOptions
*create_options
;
870 BlockdevCreateOptionsSsh
*ssh_opts
;
872 QDict
*uri_options
= NULL
;
874 create_options
= g_new0(BlockdevCreateOptions
, 1);
875 create_options
->driver
= BLOCKDEV_DRIVER_SSH
;
876 ssh_opts
= &create_options
->u
.ssh
;
878 /* Get desired file size. */
879 ssh_opts
->size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
881 trace_ssh_co_create_opts(ssh_opts
->size
);
883 uri_options
= qdict_new();
884 ret
= parse_uri(filename
, uri_options
, errp
);
889 ssh_opts
->location
= ssh_parse_options(uri_options
, errp
);
890 if (ssh_opts
->location
== NULL
) {
895 ret
= ssh_co_create(create_options
, errp
);
898 qobject_unref(uri_options
);
899 qapi_free_BlockdevCreateOptions(create_options
);
903 static void ssh_close(BlockDriverState
*bs
)
905 BDRVSSHState
*s
= bs
->opaque
;
910 static int ssh_has_zero_init(BlockDriverState
*bs
)
912 BDRVSSHState
*s
= bs
->opaque
;
913 /* Assume false, unless we can positively prove it's true. */
914 int has_zero_init
= 0;
916 if (s
->attrs
.flags
& LIBSSH2_SFTP_ATTR_PERMISSIONS
) {
917 if (s
->attrs
.permissions
& LIBSSH2_SFTP_S_IFREG
) {
922 return has_zero_init
;
925 typedef struct BDRVSSHRestart
{
926 BlockDriverState
*bs
;
930 static void restart_coroutine(void *opaque
)
932 BDRVSSHRestart
*restart
= opaque
;
933 BlockDriverState
*bs
= restart
->bs
;
934 BDRVSSHState
*s
= bs
->opaque
;
935 AioContext
*ctx
= bdrv_get_aio_context(bs
);
937 trace_ssh_restart_coroutine(restart
->co
);
938 aio_set_fd_handler(ctx
, s
->sock
, false, NULL
, NULL
, NULL
, NULL
);
940 aio_co_wake(restart
->co
);
943 /* A non-blocking call returned EAGAIN, so yield, ensuring the
944 * handlers are set up so that we'll be rescheduled when there is an
945 * interesting event on the socket.
947 static coroutine_fn
void co_yield(BDRVSSHState
*s
, BlockDriverState
*bs
)
950 IOHandler
*rd_handler
= NULL
, *wr_handler
= NULL
;
951 BDRVSSHRestart restart
= {
953 .co
= qemu_coroutine_self()
956 r
= libssh2_session_block_directions(s
->session
);
958 if (r
& LIBSSH2_SESSION_BLOCK_INBOUND
) {
959 rd_handler
= restart_coroutine
;
961 if (r
& LIBSSH2_SESSION_BLOCK_OUTBOUND
) {
962 wr_handler
= restart_coroutine
;
965 trace_ssh_co_yield(s
->sock
, rd_handler
, wr_handler
);
967 aio_set_fd_handler(bdrv_get_aio_context(bs
), s
->sock
,
968 false, rd_handler
, wr_handler
, NULL
, &restart
);
969 qemu_coroutine_yield();
970 trace_ssh_co_yield_back(s
->sock
);
973 /* SFTP has a function `libssh2_sftp_seek64' which seeks to a position
974 * in the remote file. Notice that it just updates a field in the
975 * sftp_handle structure, so there is no network traffic and it cannot
978 * However, `libssh2_sftp_seek64' does have a catastrophic effect on
979 * performance since it causes the handle to throw away all in-flight
980 * reads and buffered readahead data. Therefore this function tries
981 * to be intelligent about when to call the underlying libssh2 function.
983 #define SSH_SEEK_WRITE 0
984 #define SSH_SEEK_READ 1
985 #define SSH_SEEK_FORCE 2
987 static void ssh_seek(BDRVSSHState
*s
, int64_t offset
, int flags
)
989 bool op_read
= (flags
& SSH_SEEK_READ
) != 0;
990 bool force
= (flags
& SSH_SEEK_FORCE
) != 0;
992 if (force
|| op_read
!= s
->offset_op_read
|| offset
!= s
->offset
) {
993 trace_ssh_seek(offset
);
994 libssh2_sftp_seek64(s
->sftp_handle
, offset
);
996 s
->offset_op_read
= op_read
;
1000 static coroutine_fn
int ssh_read(BDRVSSHState
*s
, BlockDriverState
*bs
,
1001 int64_t offset
, size_t size
,
1006 char *buf
, *end_of_vec
;
1009 trace_ssh_read(offset
, size
);
1011 ssh_seek(s
, offset
, SSH_SEEK_READ
);
1013 /* This keeps track of the current iovec element ('i'), where we
1014 * will write to next ('buf'), and the end of the current iovec
1019 end_of_vec
= i
->iov_base
+ i
->iov_len
;
1021 /* libssh2 has a hard-coded limit of 2000 bytes per request,
1022 * although it will also do readahead behind our backs. Therefore
1023 * we may have to do repeated reads here until we have read 'size'
1026 for (got
= 0; got
< size
; ) {
1028 trace_ssh_read_buf(buf
, end_of_vec
- buf
);
1029 r
= libssh2_sftp_read(s
->sftp_handle
, buf
, end_of_vec
- buf
);
1030 trace_ssh_read_return(r
);
1032 if (r
== LIBSSH2_ERROR_EAGAIN
|| r
== LIBSSH2_ERROR_TIMEOUT
) {
1037 sftp_error_trace(s
, "read");
1042 /* EOF: Short read so pad the buffer with zeroes and return it. */
1043 qemu_iovec_memset(qiov
, got
, 0, size
- got
);
1050 if (buf
>= end_of_vec
&& got
< size
) {
1053 end_of_vec
= i
->iov_base
+ i
->iov_len
;
1060 static coroutine_fn
int ssh_co_readv(BlockDriverState
*bs
,
1062 int nb_sectors
, QEMUIOVector
*qiov
)
1064 BDRVSSHState
*s
= bs
->opaque
;
1067 qemu_co_mutex_lock(&s
->lock
);
1068 ret
= ssh_read(s
, bs
, sector_num
* BDRV_SECTOR_SIZE
,
1069 nb_sectors
* BDRV_SECTOR_SIZE
, qiov
);
1070 qemu_co_mutex_unlock(&s
->lock
);
1075 static int ssh_write(BDRVSSHState
*s
, BlockDriverState
*bs
,
1076 int64_t offset
, size_t size
,
1081 char *buf
, *end_of_vec
;
1084 trace_ssh_write(offset
, size
);
1086 ssh_seek(s
, offset
, SSH_SEEK_WRITE
);
1088 /* This keeps track of the current iovec element ('i'), where we
1089 * will read from next ('buf'), and the end of the current iovec
1094 end_of_vec
= i
->iov_base
+ i
->iov_len
;
1096 for (written
= 0; written
< size
; ) {
1098 trace_ssh_write_buf(buf
, end_of_vec
- buf
);
1099 r
= libssh2_sftp_write(s
->sftp_handle
, buf
, end_of_vec
- buf
);
1100 trace_ssh_write_return(r
);
1102 if (r
== LIBSSH2_ERROR_EAGAIN
|| r
== LIBSSH2_ERROR_TIMEOUT
) {
1107 sftp_error_trace(s
, "write");
1111 /* The libssh2 API is very unclear about this. A comment in
1112 * the code says "nothing was acked, and no EAGAIN was
1113 * received!" which apparently means that no data got sent
1114 * out, and the underlying channel didn't return any EAGAIN
1115 * indication. I think this is a bug in either libssh2 or
1116 * OpenSSH (server-side). In any case, forcing a seek (to
1117 * discard libssh2 internal buffers), and then trying again
1121 ssh_seek(s
, offset
+ written
, SSH_SEEK_WRITE
|SSH_SEEK_FORCE
);
1129 if (buf
>= end_of_vec
&& written
< size
) {
1132 end_of_vec
= i
->iov_base
+ i
->iov_len
;
1135 if (offset
+ written
> s
->attrs
.filesize
)
1136 s
->attrs
.filesize
= offset
+ written
;
1142 static coroutine_fn
int ssh_co_writev(BlockDriverState
*bs
,
1144 int nb_sectors
, QEMUIOVector
*qiov
,
1147 BDRVSSHState
*s
= bs
->opaque
;
1151 qemu_co_mutex_lock(&s
->lock
);
1152 ret
= ssh_write(s
, bs
, sector_num
* BDRV_SECTOR_SIZE
,
1153 nb_sectors
* BDRV_SECTOR_SIZE
, qiov
);
1154 qemu_co_mutex_unlock(&s
->lock
);
1159 static void unsafe_flush_warning(BDRVSSHState
*s
, const char *what
)
1161 if (!s
->unsafe_flush_warning
) {
1162 warn_report("ssh server %s does not support fsync",
1165 error_report("to support fsync, you need %s", what
);
1167 s
->unsafe_flush_warning
= true;
1171 #ifdef HAS_LIBSSH2_SFTP_FSYNC
1173 static coroutine_fn
int ssh_flush(BDRVSSHState
*s
, BlockDriverState
*bs
)
1179 r
= libssh2_sftp_fsync(s
->sftp_handle
);
1180 if (r
== LIBSSH2_ERROR_EAGAIN
|| r
== LIBSSH2_ERROR_TIMEOUT
) {
1184 if (r
== LIBSSH2_ERROR_SFTP_PROTOCOL
&&
1185 libssh2_sftp_last_error(s
->sftp
) == LIBSSH2_FX_OP_UNSUPPORTED
) {
1186 unsafe_flush_warning(s
, "OpenSSH >= 6.3");
1190 sftp_error_trace(s
, "fsync");
1197 static coroutine_fn
int ssh_co_flush(BlockDriverState
*bs
)
1199 BDRVSSHState
*s
= bs
->opaque
;
1202 qemu_co_mutex_lock(&s
->lock
);
1203 ret
= ssh_flush(s
, bs
);
1204 qemu_co_mutex_unlock(&s
->lock
);
1209 #else /* !HAS_LIBSSH2_SFTP_FSYNC */
1211 static coroutine_fn
int ssh_co_flush(BlockDriverState
*bs
)
1213 BDRVSSHState
*s
= bs
->opaque
;
1215 unsafe_flush_warning(s
, "libssh2 >= 1.4.4");
1219 #endif /* !HAS_LIBSSH2_SFTP_FSYNC */
1221 static int64_t ssh_getlength(BlockDriverState
*bs
)
1223 BDRVSSHState
*s
= bs
->opaque
;
1226 /* Note we cannot make a libssh2 call here. */
1227 length
= (int64_t) s
->attrs
.filesize
;
1228 trace_ssh_getlength(length
);
1233 static int coroutine_fn
ssh_co_truncate(BlockDriverState
*bs
, int64_t offset
,
1234 PreallocMode prealloc
, Error
**errp
)
1236 BDRVSSHState
*s
= bs
->opaque
;
1238 if (prealloc
!= PREALLOC_MODE_OFF
) {
1239 error_setg(errp
, "Unsupported preallocation mode '%s'",
1240 PreallocMode_str(prealloc
));
1244 if (offset
< s
->attrs
.filesize
) {
1245 error_setg(errp
, "ssh driver does not support shrinking files");
1249 if (offset
== s
->attrs
.filesize
) {
1253 return ssh_grow_file(s
, offset
, errp
);
1256 static void ssh_refresh_filename(BlockDriverState
*bs
)
1258 BDRVSSHState
*s
= bs
->opaque
;
1259 const char *path
, *host_key_check
;
1263 * None of these options can be represented in a plain "host:port"
1264 * format, so if any was given, we have to abort.
1266 if (s
->inet
->has_ipv4
|| s
->inet
->has_ipv6
|| s
->inet
->has_to
||
1267 s
->inet
->has_numeric
)
1272 path
= qdict_get_try_str(bs
->full_open_options
, "path");
1273 assert(path
); /* mandatory option */
1275 host_key_check
= qdict_get_try_str(bs
->full_open_options
, "host_key_check");
1277 ret
= snprintf(bs
->exact_filename
, sizeof(bs
->exact_filename
),
1278 "ssh://%s@%s:%s%s%s%s",
1279 s
->user
, s
->inet
->host
, s
->inet
->port
, path
,
1280 host_key_check
? "?host_key_check=" : "",
1281 host_key_check
?: "");
1282 if (ret
>= sizeof(bs
->exact_filename
)) {
1283 /* An overflow makes the filename unusable, so do not report any */
1284 bs
->exact_filename
[0] = '\0';
1288 static char *ssh_bdrv_dirname(BlockDriverState
*bs
, Error
**errp
)
1290 if (qdict_haskey(bs
->full_open_options
, "host_key_check")) {
1292 * We cannot generate a simple prefix if we would have to
1293 * append a query string.
1296 "Cannot generate a base directory with host_key_check set");
1300 if (bs
->exact_filename
[0] == '\0') {
1301 error_setg(errp
, "Cannot generate a base directory for this ssh node");
1305 return path_combine(bs
->exact_filename
, "");
1308 static const char *const ssh_strong_runtime_opts
[] = {
1319 static BlockDriver bdrv_ssh
= {
1320 .format_name
= "ssh",
1321 .protocol_name
= "ssh",
1322 .instance_size
= sizeof(BDRVSSHState
),
1323 .bdrv_parse_filename
= ssh_parse_filename
,
1324 .bdrv_file_open
= ssh_file_open
,
1325 .bdrv_co_create
= ssh_co_create
,
1326 .bdrv_co_create_opts
= ssh_co_create_opts
,
1327 .bdrv_close
= ssh_close
,
1328 .bdrv_has_zero_init
= ssh_has_zero_init
,
1329 .bdrv_co_readv
= ssh_co_readv
,
1330 .bdrv_co_writev
= ssh_co_writev
,
1331 .bdrv_getlength
= ssh_getlength
,
1332 .bdrv_co_truncate
= ssh_co_truncate
,
1333 .bdrv_co_flush_to_disk
= ssh_co_flush
,
1334 .bdrv_refresh_filename
= ssh_refresh_filename
,
1335 .bdrv_dirname
= ssh_bdrv_dirname
,
1336 .create_opts
= &ssh_create_opts
,
1337 .strong_runtime_opts
= ssh_strong_runtime_opts
,
1340 static void bdrv_ssh_init(void)
1344 r
= libssh2_init(0);
1346 fprintf(stderr
, "libssh2 initialization failed, %d\n", r
);
1350 bdrv_register(&bdrv_ssh
);
1353 block_init(bdrv_ssh_init
);