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/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 sftp_error_trace(BDRVSSHState
*s
, const char *op
)
166 unsigned long sftp_err_code
;
168 /* This is not an errno. See <libssh2.h>. */
169 ssh_err_code
= libssh2_session_last_error(s
->session
,
171 /* See <libssh2_sftp.h>. */
172 sftp_err_code
= libssh2_sftp_last_error((s
)->sftp
);
174 trace_sftp_error(op
, ssh_err
, ssh_err_code
, sftp_err_code
);
177 static int parse_uri(const char *filename
, QDict
*options
, Error
**errp
)
184 uri
= uri_parse(filename
);
189 if (g_strcmp0(uri
->scheme
, "ssh") != 0) {
190 error_setg(errp
, "URI scheme must be 'ssh'");
194 if (!uri
->server
|| strcmp(uri
->server
, "") == 0) {
195 error_setg(errp
, "missing hostname in URI");
199 if (!uri
->path
|| strcmp(uri
->path
, "") == 0) {
200 error_setg(errp
, "missing remote path in URI");
204 qp
= query_params_parse(uri
->query
);
206 error_setg(errp
, "could not parse query parameters");
210 if(uri
->user
&& strcmp(uri
->user
, "") != 0) {
211 qdict_put_str(options
, "user", uri
->user
);
214 qdict_put_str(options
, "server.host", uri
->server
);
216 port_str
= g_strdup_printf("%d", uri
->port
?: 22);
217 qdict_put_str(options
, "server.port", port_str
);
220 qdict_put_str(options
, "path", uri
->path
);
222 /* Pick out any query parameters that we understand, and ignore
225 for (i
= 0; i
< qp
->n
; ++i
) {
226 if (strcmp(qp
->p
[i
].name
, "host_key_check") == 0) {
227 qdict_put_str(options
, "host_key_check", qp
->p
[i
].value
);
231 query_params_free(qp
);
242 static bool ssh_has_filename_options_conflict(QDict
*options
, Error
**errp
)
244 const QDictEntry
*qe
;
246 for (qe
= qdict_first(options
); qe
; qe
= qdict_next(options
, qe
)) {
247 if (!strcmp(qe
->key
, "host") ||
248 !strcmp(qe
->key
, "port") ||
249 !strcmp(qe
->key
, "path") ||
250 !strcmp(qe
->key
, "user") ||
251 !strcmp(qe
->key
, "host_key_check") ||
252 strstart(qe
->key
, "server.", NULL
))
254 error_setg(errp
, "Option '%s' cannot be used with a file name",
263 static void ssh_parse_filename(const char *filename
, QDict
*options
,
266 if (ssh_has_filename_options_conflict(options
, errp
)) {
270 parse_uri(filename
, options
, errp
);
273 static int check_host_key_knownhosts(BDRVSSHState
*s
,
274 const char *host
, int port
, Error
**errp
)
277 char *knh_file
= NULL
;
278 LIBSSH2_KNOWNHOSTS
*knh
= NULL
;
279 struct libssh2_knownhost
*found
;
285 hostkey
= libssh2_session_hostkey(s
->session
, &len
, &type
);
288 session_error_setg(errp
, s
, "failed to read remote host key");
292 knh
= libssh2_knownhost_init(s
->session
);
295 session_error_setg(errp
, s
,
296 "failed to initialize known hosts support");
300 home
= getenv("HOME");
302 knh_file
= g_strdup_printf("%s/.ssh/known_hosts", home
);
304 knh_file
= g_strdup_printf("/root/.ssh/known_hosts");
307 /* Read all known hosts from OpenSSH-style known_hosts file. */
308 libssh2_knownhost_readfile(knh
, knh_file
, LIBSSH2_KNOWNHOST_FILE_OPENSSH
);
310 r
= libssh2_knownhost_checkp(knh
, host
, port
, hostkey
, len
,
311 LIBSSH2_KNOWNHOST_TYPE_PLAIN
|
312 LIBSSH2_KNOWNHOST_KEYENC_RAW
,
315 case LIBSSH2_KNOWNHOST_CHECK_MATCH
:
317 trace_ssh_check_host_key_knownhosts(found
->key
);
319 case LIBSSH2_KNOWNHOST_CHECK_MISMATCH
:
321 session_error_setg(errp
, s
,
322 "host key does not match the one in known_hosts"
323 " (found key %s)", found
->key
);
325 case LIBSSH2_KNOWNHOST_CHECK_NOTFOUND
:
327 session_error_setg(errp
, s
, "no host key was found in known_hosts");
329 case LIBSSH2_KNOWNHOST_CHECK_FAILURE
:
331 session_error_setg(errp
, s
,
332 "failure matching the host key with known_hosts");
336 session_error_setg(errp
, s
, "unknown error matching the host key"
337 " with known_hosts (%d)", r
);
341 /* known_hosts checking successful. */
346 libssh2_knownhost_free(knh
);
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';
391 check_host_key_hash(BDRVSSHState
*s
, const char *hash
,
392 int hash_type
, size_t fingerprint_len
, Error
**errp
)
394 const char *fingerprint
;
396 fingerprint
= libssh2_hostkey_hash(s
->session
, hash_type
);
398 session_error_setg(errp
, s
, "failed to read remote host key");
402 if(compare_fingerprint((unsigned char *) fingerprint
, fingerprint_len
,
404 error_setg(errp
, "remote host key does not match host_key_check '%s'",
412 static int check_host_key(BDRVSSHState
*s
, const char *host
, int port
,
413 SshHostKeyCheck
*hkc
, Error
**errp
)
415 SshHostKeyCheckMode mode
;
420 mode
= SSH_HOST_KEY_CHECK_MODE_KNOWN_HOSTS
;
424 case SSH_HOST_KEY_CHECK_MODE_NONE
:
426 case SSH_HOST_KEY_CHECK_MODE_HASH
:
427 if (hkc
->u
.hash
.type
== SSH_HOST_KEY_CHECK_HASH_TYPE_MD5
) {
428 return check_host_key_hash(s
, hkc
->u
.hash
.hash
,
429 LIBSSH2_HOSTKEY_HASH_MD5
, 16, errp
);
430 } else if (hkc
->u
.hash
.type
== SSH_HOST_KEY_CHECK_HASH_TYPE_SHA1
) {
431 return check_host_key_hash(s
, hkc
->u
.hash
.hash
,
432 LIBSSH2_HOSTKEY_HASH_SHA1
, 20, errp
);
434 g_assert_not_reached();
436 case SSH_HOST_KEY_CHECK_MODE_KNOWN_HOSTS
:
437 return check_host_key_knownhosts(s
, host
, port
, errp
);
439 g_assert_not_reached();
445 static int authenticate(BDRVSSHState
*s
, const char *user
, Error
**errp
)
448 const char *userauthlist
;
449 LIBSSH2_AGENT
*agent
= NULL
;
450 struct libssh2_agent_publickey
*identity
;
451 struct libssh2_agent_publickey
*prev_identity
= NULL
;
453 userauthlist
= libssh2_userauth_list(s
->session
, user
, strlen(user
));
454 if (strstr(userauthlist
, "publickey") == NULL
) {
457 "remote server does not support \"publickey\" authentication");
461 /* Connect to ssh-agent and try each identity in turn. */
462 agent
= libssh2_agent_init(s
->session
);
465 session_error_setg(errp
, s
, "failed to initialize ssh-agent support");
468 if (libssh2_agent_connect(agent
)) {
470 session_error_setg(errp
, s
, "failed to connect to ssh-agent");
473 if (libssh2_agent_list_identities(agent
)) {
475 session_error_setg(errp
, s
,
476 "failed requesting identities from ssh-agent");
481 r
= libssh2_agent_get_identity(agent
, &identity
, prev_identity
);
482 if (r
== 1) { /* end of list */
487 session_error_setg(errp
, s
,
488 "failed to obtain identity from ssh-agent");
491 r
= libssh2_agent_userauth(agent
, user
, identity
);
497 /* Failed to authenticate with this identity, try the next one. */
498 prev_identity
= identity
;
502 error_setg(errp
, "failed to authenticate using publickey authentication "
503 "and the identities held by your ssh-agent");
507 /* Note: libssh2 implementation implicitly calls
508 * libssh2_agent_disconnect if necessary.
510 libssh2_agent_free(agent
);
516 static QemuOptsList ssh_runtime_opts
= {
518 .head
= QTAILQ_HEAD_INITIALIZER(ssh_runtime_opts
.head
),
522 .type
= QEMU_OPT_STRING
,
523 .help
= "Host to connect to",
527 .type
= QEMU_OPT_NUMBER
,
528 .help
= "Port to connect to",
531 .name
= "host_key_check",
532 .type
= QEMU_OPT_STRING
,
533 .help
= "Defines how and what to check the host key against",
535 { /* end of list */ }
539 static bool ssh_process_legacy_options(QDict
*output_opts
,
540 QemuOpts
*legacy_opts
,
543 const char *host
= qemu_opt_get(legacy_opts
, "host");
544 const char *port
= qemu_opt_get(legacy_opts
, "port");
545 const char *host_key_check
= qemu_opt_get(legacy_opts
, "host_key_check");
548 error_setg(errp
, "port may not be used without host");
553 qdict_put_str(output_opts
, "server.host", host
);
554 qdict_put_str(output_opts
, "server.port", port
?: stringify(22));
557 if (host_key_check
) {
558 if (strcmp(host_key_check
, "no") == 0) {
559 qdict_put_str(output_opts
, "host-key-check.mode", "none");
560 } else if (strncmp(host_key_check
, "md5:", 4) == 0) {
561 qdict_put_str(output_opts
, "host-key-check.mode", "hash");
562 qdict_put_str(output_opts
, "host-key-check.type", "md5");
563 qdict_put_str(output_opts
, "host-key-check.hash",
565 } else if (strncmp(host_key_check
, "sha1:", 5) == 0) {
566 qdict_put_str(output_opts
, "host-key-check.mode", "hash");
567 qdict_put_str(output_opts
, "host-key-check.type", "sha1");
568 qdict_put_str(output_opts
, "host-key-check.hash",
570 } else if (strcmp(host_key_check
, "yes") == 0) {
571 qdict_put_str(output_opts
, "host-key-check.mode", "known_hosts");
573 error_setg(errp
, "unknown host_key_check setting (%s)",
582 static BlockdevOptionsSsh
*ssh_parse_options(QDict
*options
, Error
**errp
)
584 BlockdevOptionsSsh
*result
= NULL
;
585 QemuOpts
*opts
= NULL
;
586 Error
*local_err
= NULL
;
590 /* Translate legacy options */
591 opts
= qemu_opts_create(&ssh_runtime_opts
, NULL
, 0, &error_abort
);
592 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
594 error_propagate(errp
, local_err
);
598 if (!ssh_process_legacy_options(options
, opts
, errp
)) {
602 /* Create the QAPI object */
603 v
= qobject_input_visitor_new_flat_confused(options
, errp
);
608 visit_type_BlockdevOptionsSsh(v
, NULL
, &result
, &local_err
);
612 error_propagate(errp
, local_err
);
616 /* Remove the processed options from the QDict (the visitor processes
617 * _all_ options in the QDict) */
618 while ((e
= qdict_first(options
))) {
619 qdict_del(options
, e
->key
);
627 static int connect_to_ssh(BDRVSSHState
*s
, BlockdevOptionsSsh
*opts
,
628 int ssh_flags
, int creat_mode
, Error
**errp
)
634 if (opts
->has_user
) {
637 user
= g_get_user_name();
639 error_setg_errno(errp
, errno
, "Can't get user name");
645 /* Pop the config into our state object, Exit if invalid */
646 s
->inet
= opts
->server
;
649 if (qemu_strtol(s
->inet
->port
, NULL
, 10, &port
) < 0) {
650 error_setg(errp
, "Use only numeric port value");
655 /* Open the socket and connect. */
656 s
->sock
= inet_connect_saddr(s
->inet
, errp
);
662 /* Create SSH session. */
663 s
->session
= libssh2_session_init();
666 session_error_setg(errp
, s
, "failed to initialize libssh2 session");
670 #if TRACE_LIBSSH2 != 0
671 libssh2_trace(s
->session
, TRACE_LIBSSH2
);
674 r
= libssh2_session_handshake(s
->session
, s
->sock
);
677 session_error_setg(errp
, s
, "failed to establish SSH session");
681 /* Check the remote host's key against known_hosts. */
682 ret
= check_host_key(s
, s
->inet
->host
, port
, opts
->host_key_check
, errp
);
688 ret
= authenticate(s
, user
, errp
);
694 s
->sftp
= libssh2_sftp_init(s
->session
);
696 session_error_setg(errp
, s
, "failed to initialize sftp handle");
701 /* Open the remote file. */
702 trace_ssh_connect_to_ssh(opts
->path
, ssh_flags
, creat_mode
);
703 s
->sftp_handle
= libssh2_sftp_open(s
->sftp
, opts
->path
, ssh_flags
,
705 if (!s
->sftp_handle
) {
706 session_error_setg(errp
, s
, "failed to open remote file '%s'",
712 r
= libssh2_sftp_fstat(s
->sftp_handle
, &s
->attrs
);
714 sftp_error_setg(errp
, s
, "failed to read file attributes");
721 if (s
->sftp_handle
) {
722 libssh2_sftp_close(s
->sftp_handle
);
724 s
->sftp_handle
= NULL
;
726 libssh2_sftp_shutdown(s
->sftp
);
730 libssh2_session_disconnect(s
->session
,
731 "from qemu ssh client: "
732 "error opening connection");
733 libssh2_session_free(s
->session
);
740 static int ssh_file_open(BlockDriverState
*bs
, QDict
*options
, int bdrv_flags
,
743 BDRVSSHState
*s
= bs
->opaque
;
744 BlockdevOptionsSsh
*opts
;
750 ssh_flags
= LIBSSH2_FXF_READ
;
751 if (bdrv_flags
& BDRV_O_RDWR
) {
752 ssh_flags
|= LIBSSH2_FXF_WRITE
;
755 opts
= ssh_parse_options(options
, errp
);
761 ret
= connect_to_ssh(s
, opts
, ssh_flags
, 0, errp
);
766 /* Go non-blocking. */
767 libssh2_session_set_blocking(s
->session
, 0);
769 qapi_free_BlockdevOptionsSsh(opts
);
779 qapi_free_BlockdevOptionsSsh(opts
);
784 /* Note: This is a blocking operation */
785 static int ssh_grow_file(BDRVSSHState
*s
, int64_t offset
, Error
**errp
)
788 char c
[1] = { '\0' };
789 int was_blocking
= libssh2_session_get_blocking(s
->session
);
791 /* offset must be strictly greater than the current size so we do
792 * not overwrite anything */
793 assert(offset
> 0 && offset
> s
->attrs
.filesize
);
795 libssh2_session_set_blocking(s
->session
, 1);
797 libssh2_sftp_seek64(s
->sftp_handle
, offset
- 1);
798 ret
= libssh2_sftp_write(s
->sftp_handle
, c
, 1);
800 libssh2_session_set_blocking(s
->session
, was_blocking
);
803 sftp_error_setg(errp
, s
, "Failed to grow file");
807 s
->attrs
.filesize
= offset
;
811 static QemuOptsList ssh_create_opts
= {
812 .name
= "ssh-create-opts",
813 .head
= QTAILQ_HEAD_INITIALIZER(ssh_create_opts
.head
),
816 .name
= BLOCK_OPT_SIZE
,
817 .type
= QEMU_OPT_SIZE
,
818 .help
= "Virtual disk size"
820 { /* end of list */ }
824 static int ssh_co_create(BlockdevCreateOptions
*options
, Error
**errp
)
826 BlockdevCreateOptionsSsh
*opts
= &options
->u
.ssh
;
830 assert(options
->driver
== BLOCKDEV_DRIVER_SSH
);
834 ret
= connect_to_ssh(&s
, opts
->location
,
835 LIBSSH2_FXF_READ
|LIBSSH2_FXF_WRITE
|
836 LIBSSH2_FXF_CREAT
|LIBSSH2_FXF_TRUNC
,
842 if (opts
->size
> 0) {
843 ret
= ssh_grow_file(&s
, opts
->size
, errp
);
855 static int coroutine_fn
ssh_co_create_opts(const char *filename
, QemuOpts
*opts
,
858 BlockdevCreateOptions
*create_options
;
859 BlockdevCreateOptionsSsh
*ssh_opts
;
861 QDict
*uri_options
= NULL
;
863 create_options
= g_new0(BlockdevCreateOptions
, 1);
864 create_options
->driver
= BLOCKDEV_DRIVER_SSH
;
865 ssh_opts
= &create_options
->u
.ssh
;
867 /* Get desired file size. */
868 ssh_opts
->size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
870 trace_ssh_co_create_opts(ssh_opts
->size
);
872 uri_options
= qdict_new();
873 ret
= parse_uri(filename
, uri_options
, errp
);
878 ssh_opts
->location
= ssh_parse_options(uri_options
, errp
);
879 if (ssh_opts
->location
== NULL
) {
884 ret
= ssh_co_create(create_options
, errp
);
887 qobject_unref(uri_options
);
888 qapi_free_BlockdevCreateOptions(create_options
);
892 static void ssh_close(BlockDriverState
*bs
)
894 BDRVSSHState
*s
= bs
->opaque
;
899 static int ssh_has_zero_init(BlockDriverState
*bs
)
901 BDRVSSHState
*s
= bs
->opaque
;
902 /* Assume false, unless we can positively prove it's true. */
903 int has_zero_init
= 0;
905 if (s
->attrs
.flags
& LIBSSH2_SFTP_ATTR_PERMISSIONS
) {
906 if (s
->attrs
.permissions
& LIBSSH2_SFTP_S_IFREG
) {
911 return has_zero_init
;
914 typedef struct BDRVSSHRestart
{
915 BlockDriverState
*bs
;
919 static void restart_coroutine(void *opaque
)
921 BDRVSSHRestart
*restart
= opaque
;
922 BlockDriverState
*bs
= restart
->bs
;
923 BDRVSSHState
*s
= bs
->opaque
;
924 AioContext
*ctx
= bdrv_get_aio_context(bs
);
926 trace_ssh_restart_coroutine(restart
->co
);
927 aio_set_fd_handler(ctx
, s
->sock
, false, NULL
, NULL
, NULL
, NULL
);
929 aio_co_wake(restart
->co
);
932 /* A non-blocking call returned EAGAIN, so yield, ensuring the
933 * handlers are set up so that we'll be rescheduled when there is an
934 * interesting event on the socket.
936 static coroutine_fn
void co_yield(BDRVSSHState
*s
, BlockDriverState
*bs
)
939 IOHandler
*rd_handler
= NULL
, *wr_handler
= NULL
;
940 BDRVSSHRestart restart
= {
942 .co
= qemu_coroutine_self()
945 r
= libssh2_session_block_directions(s
->session
);
947 if (r
& LIBSSH2_SESSION_BLOCK_INBOUND
) {
948 rd_handler
= restart_coroutine
;
950 if (r
& LIBSSH2_SESSION_BLOCK_OUTBOUND
) {
951 wr_handler
= restart_coroutine
;
954 trace_ssh_co_yield(s
->sock
, rd_handler
, wr_handler
);
956 aio_set_fd_handler(bdrv_get_aio_context(bs
), s
->sock
,
957 false, rd_handler
, wr_handler
, NULL
, &restart
);
958 qemu_coroutine_yield();
959 trace_ssh_co_yield_back(s
->sock
);
962 /* SFTP has a function `libssh2_sftp_seek64' which seeks to a position
963 * in the remote file. Notice that it just updates a field in the
964 * sftp_handle structure, so there is no network traffic and it cannot
967 * However, `libssh2_sftp_seek64' does have a catastrophic effect on
968 * performance since it causes the handle to throw away all in-flight
969 * reads and buffered readahead data. Therefore this function tries
970 * to be intelligent about when to call the underlying libssh2 function.
972 #define SSH_SEEK_WRITE 0
973 #define SSH_SEEK_READ 1
974 #define SSH_SEEK_FORCE 2
976 static void ssh_seek(BDRVSSHState
*s
, int64_t offset
, int flags
)
978 bool op_read
= (flags
& SSH_SEEK_READ
) != 0;
979 bool force
= (flags
& SSH_SEEK_FORCE
) != 0;
981 if (force
|| op_read
!= s
->offset_op_read
|| offset
!= s
->offset
) {
982 trace_ssh_seek(offset
);
983 libssh2_sftp_seek64(s
->sftp_handle
, offset
);
985 s
->offset_op_read
= op_read
;
989 static coroutine_fn
int ssh_read(BDRVSSHState
*s
, BlockDriverState
*bs
,
990 int64_t offset
, size_t size
,
995 char *buf
, *end_of_vec
;
998 trace_ssh_read(offset
, size
);
1000 ssh_seek(s
, offset
, SSH_SEEK_READ
);
1002 /* This keeps track of the current iovec element ('i'), where we
1003 * will write to next ('buf'), and the end of the current iovec
1008 end_of_vec
= i
->iov_base
+ i
->iov_len
;
1010 /* libssh2 has a hard-coded limit of 2000 bytes per request,
1011 * although it will also do readahead behind our backs. Therefore
1012 * we may have to do repeated reads here until we have read 'size'
1015 for (got
= 0; got
< size
; ) {
1017 trace_ssh_read_buf(buf
, end_of_vec
- buf
);
1018 r
= libssh2_sftp_read(s
->sftp_handle
, buf
, end_of_vec
- buf
);
1019 trace_ssh_read_return(r
);
1021 if (r
== LIBSSH2_ERROR_EAGAIN
|| r
== LIBSSH2_ERROR_TIMEOUT
) {
1026 sftp_error_trace(s
, "read");
1031 /* EOF: Short read so pad the buffer with zeroes and return it. */
1032 qemu_iovec_memset(qiov
, got
, 0, size
- got
);
1039 if (buf
>= end_of_vec
&& got
< size
) {
1042 end_of_vec
= i
->iov_base
+ i
->iov_len
;
1049 static coroutine_fn
int ssh_co_readv(BlockDriverState
*bs
,
1051 int nb_sectors
, QEMUIOVector
*qiov
)
1053 BDRVSSHState
*s
= bs
->opaque
;
1056 qemu_co_mutex_lock(&s
->lock
);
1057 ret
= ssh_read(s
, bs
, sector_num
* BDRV_SECTOR_SIZE
,
1058 nb_sectors
* BDRV_SECTOR_SIZE
, qiov
);
1059 qemu_co_mutex_unlock(&s
->lock
);
1064 static int ssh_write(BDRVSSHState
*s
, BlockDriverState
*bs
,
1065 int64_t offset
, size_t size
,
1070 char *buf
, *end_of_vec
;
1073 trace_ssh_write(offset
, size
);
1075 ssh_seek(s
, offset
, SSH_SEEK_WRITE
);
1077 /* This keeps track of the current iovec element ('i'), where we
1078 * will read from next ('buf'), and the end of the current iovec
1083 end_of_vec
= i
->iov_base
+ i
->iov_len
;
1085 for (written
= 0; written
< size
; ) {
1087 trace_ssh_write_buf(buf
, end_of_vec
- buf
);
1088 r
= libssh2_sftp_write(s
->sftp_handle
, buf
, end_of_vec
- buf
);
1089 trace_ssh_write_return(r
);
1091 if (r
== LIBSSH2_ERROR_EAGAIN
|| r
== LIBSSH2_ERROR_TIMEOUT
) {
1096 sftp_error_trace(s
, "write");
1100 /* The libssh2 API is very unclear about this. A comment in
1101 * the code says "nothing was acked, and no EAGAIN was
1102 * received!" which apparently means that no data got sent
1103 * out, and the underlying channel didn't return any EAGAIN
1104 * indication. I think this is a bug in either libssh2 or
1105 * OpenSSH (server-side). In any case, forcing a seek (to
1106 * discard libssh2 internal buffers), and then trying again
1110 ssh_seek(s
, offset
+ written
, SSH_SEEK_WRITE
|SSH_SEEK_FORCE
);
1118 if (buf
>= end_of_vec
&& written
< size
) {
1121 end_of_vec
= i
->iov_base
+ i
->iov_len
;
1124 if (offset
+ written
> s
->attrs
.filesize
)
1125 s
->attrs
.filesize
= offset
+ written
;
1131 static coroutine_fn
int ssh_co_writev(BlockDriverState
*bs
,
1133 int nb_sectors
, QEMUIOVector
*qiov
,
1136 BDRVSSHState
*s
= bs
->opaque
;
1140 qemu_co_mutex_lock(&s
->lock
);
1141 ret
= ssh_write(s
, bs
, sector_num
* BDRV_SECTOR_SIZE
,
1142 nb_sectors
* BDRV_SECTOR_SIZE
, qiov
);
1143 qemu_co_mutex_unlock(&s
->lock
);
1148 static void unsafe_flush_warning(BDRVSSHState
*s
, const char *what
)
1150 if (!s
->unsafe_flush_warning
) {
1151 warn_report("ssh server %s does not support fsync",
1154 error_report("to support fsync, you need %s", what
);
1156 s
->unsafe_flush_warning
= true;
1160 #ifdef HAS_LIBSSH2_SFTP_FSYNC
1162 static coroutine_fn
int ssh_flush(BDRVSSHState
*s
, BlockDriverState
*bs
)
1168 r
= libssh2_sftp_fsync(s
->sftp_handle
);
1169 if (r
== LIBSSH2_ERROR_EAGAIN
|| r
== LIBSSH2_ERROR_TIMEOUT
) {
1173 if (r
== LIBSSH2_ERROR_SFTP_PROTOCOL
&&
1174 libssh2_sftp_last_error(s
->sftp
) == LIBSSH2_FX_OP_UNSUPPORTED
) {
1175 unsafe_flush_warning(s
, "OpenSSH >= 6.3");
1179 sftp_error_trace(s
, "fsync");
1186 static coroutine_fn
int ssh_co_flush(BlockDriverState
*bs
)
1188 BDRVSSHState
*s
= bs
->opaque
;
1191 qemu_co_mutex_lock(&s
->lock
);
1192 ret
= ssh_flush(s
, bs
);
1193 qemu_co_mutex_unlock(&s
->lock
);
1198 #else /* !HAS_LIBSSH2_SFTP_FSYNC */
1200 static coroutine_fn
int ssh_co_flush(BlockDriverState
*bs
)
1202 BDRVSSHState
*s
= bs
->opaque
;
1204 unsafe_flush_warning(s
, "libssh2 >= 1.4.4");
1208 #endif /* !HAS_LIBSSH2_SFTP_FSYNC */
1210 static int64_t ssh_getlength(BlockDriverState
*bs
)
1212 BDRVSSHState
*s
= bs
->opaque
;
1215 /* Note we cannot make a libssh2 call here. */
1216 length
= (int64_t) s
->attrs
.filesize
;
1217 trace_ssh_getlength(length
);
1222 static int coroutine_fn
ssh_co_truncate(BlockDriverState
*bs
, int64_t offset
,
1223 PreallocMode prealloc
, Error
**errp
)
1225 BDRVSSHState
*s
= bs
->opaque
;
1227 if (prealloc
!= PREALLOC_MODE_OFF
) {
1228 error_setg(errp
, "Unsupported preallocation mode '%s'",
1229 PreallocMode_str(prealloc
));
1233 if (offset
< s
->attrs
.filesize
) {
1234 error_setg(errp
, "ssh driver does not support shrinking files");
1238 if (offset
== s
->attrs
.filesize
) {
1242 return ssh_grow_file(s
, offset
, errp
);
1245 static const char *const ssh_strong_runtime_opts
[] = {
1256 static BlockDriver bdrv_ssh
= {
1257 .format_name
= "ssh",
1258 .protocol_name
= "ssh",
1259 .instance_size
= sizeof(BDRVSSHState
),
1260 .bdrv_parse_filename
= ssh_parse_filename
,
1261 .bdrv_file_open
= ssh_file_open
,
1262 .bdrv_co_create
= ssh_co_create
,
1263 .bdrv_co_create_opts
= ssh_co_create_opts
,
1264 .bdrv_close
= ssh_close
,
1265 .bdrv_has_zero_init
= ssh_has_zero_init
,
1266 .bdrv_co_readv
= ssh_co_readv
,
1267 .bdrv_co_writev
= ssh_co_writev
,
1268 .bdrv_getlength
= ssh_getlength
,
1269 .bdrv_co_truncate
= ssh_co_truncate
,
1270 .bdrv_co_flush_to_disk
= ssh_co_flush
,
1271 .create_opts
= &ssh_create_opts
,
1272 .strong_runtime_opts
= ssh_strong_runtime_opts
,
1275 static void bdrv_ssh_init(void)
1279 r
= libssh2_init(0);
1281 fprintf(stderr
, "libssh2 initialization failed, %d\n", r
);
1285 bdrv_register(&bdrv_ssh
);
1288 block_init(bdrv_ssh_init
);