2 * Secure Shell (ssh) backend for QEMU.
4 * Copyright (C) 2013 Red Hat Inc., Richard W.M. Jones <rjones@redhat.com>
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "qemu/osdep.h"
27 #include <libssh/libssh.h>
28 #include <libssh/sftp.h>
30 #include "block/block-io.h"
31 #include "block/block_int.h"
32 #include "block/qdict.h"
33 #include "qapi/error.h"
34 #include "qemu/error-report.h"
35 #include "qemu/module.h"
36 #include "qemu/option.h"
37 #include "qemu/ctype.h"
38 #include "qemu/cutils.h"
39 #include "qemu/sockets.h"
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_LIBSSH=<level> enables tracing in libssh itself.
50 * The meaning of <level> is described here:
51 * http://api.libssh.org/master/group__libssh__log.html
53 #define TRACE_LIBSSH 0 /* see: SSH_LOG_* */
55 typedef struct BDRVSSHState
{
60 int sock
; /* socket */
61 ssh_session session
; /* ssh session */
62 sftp_session sftp
; /* sftp session */
63 sftp_file sftp_handle
; /* sftp remote file handle */
66 * File attributes at open. We try to keep the .size field
67 * updated if it changes (eg by writing at the end of the file).
69 sftp_attributes attrs
;
71 InetSocketAddress
*inet
;
73 /* Used to warn if 'flush' is not supported. */
74 bool unsafe_flush_warning
;
77 * Store the user name for ssh_refresh_filename() because the
78 * default depends on the system you are on -- therefore, when we
79 * generate a filename, it should always contain the user name we
85 static void ssh_state_init(BDRVSSHState
*s
)
87 memset(s
, 0, sizeof *s
);
89 qemu_co_mutex_init(&s
->lock
);
92 static void ssh_state_free(BDRVSSHState
*s
)
97 sftp_attributes_free(s
->attrs
);
100 sftp_close(s
->sftp_handle
);
106 ssh_disconnect(s
->session
);
107 ssh_free(s
->session
); /* This frees s->sock */
111 static void G_GNUC_PRINTF(3, 4)
112 session_error_setg(Error
**errp
, BDRVSSHState
*s
, const char *fs
, ...)
118 msg
= g_strdup_vprintf(fs
, args
);
125 /* This is not an errno. See <libssh/libssh.h>. */
126 ssh_err
= ssh_get_error(s
->session
);
127 ssh_err_code
= ssh_get_error_code(s
->session
);
128 error_setg(errp
, "%s: %s (libssh error code: %d)",
129 msg
, ssh_err
, ssh_err_code
);
131 error_setg(errp
, "%s", msg
);
136 static void G_GNUC_PRINTF(3, 4)
137 sftp_error_setg(Error
**errp
, BDRVSSHState
*s
, const char *fs
, ...)
143 msg
= g_strdup_vprintf(fs
, args
);
151 /* This is not an errno. See <libssh/libssh.h>. */
152 ssh_err
= ssh_get_error(s
->session
);
153 ssh_err_code
= ssh_get_error_code(s
->session
);
154 /* See <libssh/sftp.h>. */
155 sftp_err_code
= sftp_get_error(s
->sftp
);
158 "%s: %s (libssh error code: %d, sftp error code: %d)",
159 msg
, ssh_err
, ssh_err_code
, sftp_err_code
);
161 error_setg(errp
, "%s", msg
);
166 static void sftp_error_trace(BDRVSSHState
*s
, const char *op
)
172 /* This is not an errno. See <libssh/libssh.h>. */
173 ssh_err
= ssh_get_error(s
->session
);
174 ssh_err_code
= ssh_get_error_code(s
->session
);
175 /* See <libssh/sftp.h>. */
176 sftp_err_code
= sftp_get_error(s
->sftp
);
178 trace_sftp_error(op
, ssh_err
, ssh_err_code
, sftp_err_code
);
181 static int parse_uri(const char *filename
, QDict
*options
, Error
**errp
)
183 g_autoptr(GUri
) uri
= g_uri_parse(filename
, G_URI_FLAGS_NONE
, NULL
);
184 const char *uri_host
, *uri_path
, *uri_user
, *uri_query
;
187 g_autoptr(GError
) gerror
= NULL
;
188 char *qp_name
, *qp_value
;
195 if (g_strcmp0(g_uri_get_scheme(uri
), "ssh") != 0) {
196 error_setg(errp
, "URI scheme must be 'ssh'");
200 uri_host
= g_uri_get_host(uri
);
201 if (!uri_host
|| g_str_equal(uri_host
, "")) {
202 error_setg(errp
, "missing hostname in URI");
206 uri_path
= g_uri_get_path(uri
);
207 if (!uri_path
|| g_str_equal(uri_path
, "")) {
208 error_setg(errp
, "missing remote path in URI");
212 uri_user
= g_uri_get_user(uri
);
213 if (uri_user
&& !g_str_equal(uri_user
, "")) {
214 qdict_put_str(options
, "user", uri_user
);
217 qdict_put_str(options
, "server.host", uri_host
);
219 port
= g_uri_get_port(uri
);
220 port_str
= g_strdup_printf("%d", port
> 0 ? port
: 22);
221 qdict_put_str(options
, "server.port", port_str
);
224 qdict_put_str(options
, "path", uri_path
);
226 uri_query
= g_uri_get_query(uri
);
228 g_uri_params_iter_init(&qp
, uri_query
, -1, "&", G_URI_PARAMS_NONE
);
229 while (g_uri_params_iter_next(&qp
, &qp_name
, &qp_value
, &gerror
)) {
230 if (!qp_name
|| !qp_value
|| gerror
) {
231 warn_report("Failed to parse SSH URI parameters '%s'",
236 * Pick out the query parameters that we understand, and ignore
237 * (or rather warn about) the rest.
239 if (g_str_equal(qp_name
, "host_key_check")) {
240 qdict_put_str(options
, "host_key_check", qp_value
);
242 warn_report("Unsupported parameter '%s' in URI", qp_name
);
250 static bool ssh_has_filename_options_conflict(QDict
*options
, Error
**errp
)
252 const QDictEntry
*qe
;
254 for (qe
= qdict_first(options
); qe
; qe
= qdict_next(options
, qe
)) {
255 if (!strcmp(qe
->key
, "host") ||
256 !strcmp(qe
->key
, "port") ||
257 !strcmp(qe
->key
, "path") ||
258 !strcmp(qe
->key
, "user") ||
259 !strcmp(qe
->key
, "host_key_check") ||
260 strstart(qe
->key
, "server.", NULL
))
262 error_setg(errp
, "Option '%s' cannot be used with a file name",
271 static void ssh_parse_filename(const char *filename
, QDict
*options
,
274 if (ssh_has_filename_options_conflict(options
, errp
)) {
278 parse_uri(filename
, options
, errp
);
281 static int check_host_key_knownhosts(BDRVSSHState
*s
, Error
**errp
)
284 enum ssh_known_hosts_e state
;
287 enum ssh_keytypes_e pubkey_type
;
288 unsigned char *server_hash
= NULL
;
289 size_t server_hash_len
;
290 char *fingerprint
= NULL
;
292 state
= ssh_session_is_known_server(s
->session
);
293 trace_ssh_server_status(state
);
296 case SSH_KNOWN_HOSTS_OK
:
298 trace_ssh_check_host_key_knownhosts();
300 case SSH_KNOWN_HOSTS_CHANGED
:
302 r
= ssh_get_server_publickey(s
->session
, &pubkey
);
304 r
= ssh_get_publickey_hash(pubkey
, SSH_PUBLICKEY_HASH_SHA256
,
305 &server_hash
, &server_hash_len
);
306 pubkey_type
= ssh_key_type(pubkey
);
307 ssh_key_free(pubkey
);
310 fingerprint
= ssh_get_fingerprint_hash(SSH_PUBLICKEY_HASH_SHA256
,
313 ssh_clean_pubkey_hash(&server_hash
);
317 "host key (%s key with fingerprint %s) does not match "
318 "the one in known_hosts; this may be a possible attack",
319 ssh_key_type_to_char(pubkey_type
), fingerprint
);
320 ssh_string_free_char(fingerprint
);
323 "host key does not match the one in known_hosts; this "
324 "may be a possible attack");
327 case SSH_KNOWN_HOSTS_OTHER
:
330 "host key for this server not found, another type exists");
332 case SSH_KNOWN_HOSTS_UNKNOWN
:
334 error_setg(errp
, "no host key was found in known_hosts");
336 case SSH_KNOWN_HOSTS_NOT_FOUND
:
338 error_setg(errp
, "known_hosts file not found");
340 case SSH_KNOWN_HOSTS_ERROR
:
342 error_setg(errp
, "error while checking the host");
346 error_setg(errp
, "error while checking for known server (%d)", state
);
350 /* known_hosts checking successful. */
357 static unsigned hex2decimal(char ch
)
359 if (ch
>= '0' && ch
<= '9') {
361 } else if (ch
>= 'a' && ch
<= 'f') {
362 return 10 + (ch
- 'a');
363 } else if (ch
>= 'A' && ch
<= 'F') {
364 return 10 + (ch
- 'A');
370 /* Compare the binary fingerprint (hash of host key) with the
371 * host_key_check parameter.
373 static int compare_fingerprint(const unsigned char *fingerprint
, size_t len
,
374 const char *host_key_check
)
379 while (*host_key_check
== ':')
381 if (!qemu_isxdigit(host_key_check
[0]) ||
382 !qemu_isxdigit(host_key_check
[1]))
384 c
= hex2decimal(host_key_check
[0]) * 16 +
385 hex2decimal(host_key_check
[1]);
386 if (c
- *fingerprint
!= 0)
387 return c
- *fingerprint
;
392 return *host_key_check
- '\0';
395 static char *format_fingerprint(const unsigned char *fingerprint
, size_t len
)
397 static const char *hex
= "0123456789abcdef";
398 char *ret
= g_new0(char, (len
* 2) + 1);
399 for (size_t i
= 0; i
< len
; i
++) {
400 ret
[i
* 2] = hex
[((fingerprint
[i
] >> 4) & 0xf)];
401 ret
[(i
* 2) + 1] = hex
[(fingerprint
[i
] & 0xf)];
408 check_host_key_hash(BDRVSSHState
*s
, const char *hash
,
409 enum ssh_publickey_hash_type type
, const char *typestr
,
414 unsigned char *server_hash
;
415 size_t server_hash_len
;
418 r
= ssh_get_server_publickey(s
->session
, &pubkey
);
420 session_error_setg(errp
, s
, "failed to read remote host key");
424 keytype
= ssh_key_type_to_char(ssh_key_type(pubkey
));
426 r
= ssh_get_publickey_hash(pubkey
, type
, &server_hash
, &server_hash_len
);
427 ssh_key_free(pubkey
);
429 session_error_setg(errp
, s
,
430 "failed reading the hash of the server SSH key");
434 r
= compare_fingerprint(server_hash
, server_hash_len
, hash
);
436 g_autofree
char *server_fp
= format_fingerprint(server_hash
,
438 error_setg(errp
, "remote host %s key fingerprint '%s:%s' "
439 "does not match host_key_check '%s:%s'",
440 keytype
, typestr
, server_fp
, typestr
, hash
);
441 ssh_clean_pubkey_hash(&server_hash
);
444 ssh_clean_pubkey_hash(&server_hash
);
449 static int check_host_key(BDRVSSHState
*s
, SshHostKeyCheck
*hkc
, Error
**errp
)
451 SshHostKeyCheckMode mode
;
456 mode
= SSH_HOST_KEY_CHECK_MODE_KNOWN_HOSTS
;
460 case SSH_HOST_KEY_CHECK_MODE_NONE
:
462 case SSH_HOST_KEY_CHECK_MODE_HASH
:
463 if (hkc
->u
.hash
.type
== SSH_HOST_KEY_CHECK_HASH_TYPE_MD5
) {
464 return check_host_key_hash(s
, hkc
->u
.hash
.hash
,
465 SSH_PUBLICKEY_HASH_MD5
, "md5",
467 } else if (hkc
->u
.hash
.type
== SSH_HOST_KEY_CHECK_HASH_TYPE_SHA1
) {
468 return check_host_key_hash(s
, hkc
->u
.hash
.hash
,
469 SSH_PUBLICKEY_HASH_SHA1
, "sha1",
471 } else if (hkc
->u
.hash
.type
== SSH_HOST_KEY_CHECK_HASH_TYPE_SHA256
) {
472 return check_host_key_hash(s
, hkc
->u
.hash
.hash
,
473 SSH_PUBLICKEY_HASH_SHA256
, "sha256",
476 g_assert_not_reached();
477 case SSH_HOST_KEY_CHECK_MODE_KNOWN_HOSTS
:
478 return check_host_key_knownhosts(s
, errp
);
480 g_assert_not_reached();
486 static int authenticate(BDRVSSHState
*s
, Error
**errp
)
491 /* Try to authenticate with the "none" method. */
492 r
= ssh_userauth_none(s
->session
, NULL
);
493 if (r
== SSH_AUTH_ERROR
) {
495 session_error_setg(errp
, s
, "failed to authenticate using none "
498 } else if (r
== SSH_AUTH_SUCCESS
) {
504 method
= ssh_userauth_list(s
->session
, NULL
);
505 trace_ssh_auth_methods(method
);
508 * Try to authenticate with publickey, using the ssh-agent
511 if (method
& SSH_AUTH_METHOD_PUBLICKEY
) {
512 r
= ssh_userauth_publickey_auto(s
->session
, NULL
, NULL
);
513 if (r
== SSH_AUTH_ERROR
) {
515 session_error_setg(errp
, s
, "failed to authenticate using "
516 "publickey authentication");
518 } else if (r
== SSH_AUTH_SUCCESS
) {
526 error_setg(errp
, "failed to authenticate using publickey authentication "
527 "and the identities held by your ssh-agent");
533 static QemuOptsList ssh_runtime_opts
= {
535 .head
= QTAILQ_HEAD_INITIALIZER(ssh_runtime_opts
.head
),
539 .type
= QEMU_OPT_STRING
,
540 .help
= "Host to connect to",
544 .type
= QEMU_OPT_NUMBER
,
545 .help
= "Port to connect to",
548 .name
= "host_key_check",
549 .type
= QEMU_OPT_STRING
,
550 .help
= "Defines how and what to check the host key against",
552 { /* end of list */ }
556 static bool ssh_process_legacy_options(QDict
*output_opts
,
557 QemuOpts
*legacy_opts
,
560 const char *host
= qemu_opt_get(legacy_opts
, "host");
561 const char *port
= qemu_opt_get(legacy_opts
, "port");
562 const char *host_key_check
= qemu_opt_get(legacy_opts
, "host_key_check");
565 error_setg(errp
, "port may not be used without host");
570 qdict_put_str(output_opts
, "server.host", host
);
571 qdict_put_str(output_opts
, "server.port", port
?: stringify(22));
574 if (host_key_check
) {
575 if (strcmp(host_key_check
, "no") == 0) {
576 qdict_put_str(output_opts
, "host-key-check.mode", "none");
577 } else if (strncmp(host_key_check
, "md5:", 4) == 0) {
578 qdict_put_str(output_opts
, "host-key-check.mode", "hash");
579 qdict_put_str(output_opts
, "host-key-check.type", "md5");
580 qdict_put_str(output_opts
, "host-key-check.hash",
582 } else if (strncmp(host_key_check
, "sha1:", 5) == 0) {
583 qdict_put_str(output_opts
, "host-key-check.mode", "hash");
584 qdict_put_str(output_opts
, "host-key-check.type", "sha1");
585 qdict_put_str(output_opts
, "host-key-check.hash",
587 } else if (strncmp(host_key_check
, "sha256:", 7) == 0) {
588 qdict_put_str(output_opts
, "host-key-check.mode", "hash");
589 qdict_put_str(output_opts
, "host-key-check.type", "sha256");
590 qdict_put_str(output_opts
, "host-key-check.hash",
592 } else if (strcmp(host_key_check
, "yes") == 0) {
593 qdict_put_str(output_opts
, "host-key-check.mode", "known_hosts");
595 error_setg(errp
, "unknown host_key_check setting (%s)",
604 static BlockdevOptionsSsh
*ssh_parse_options(QDict
*options
, Error
**errp
)
606 BlockdevOptionsSsh
*result
= NULL
;
607 QemuOpts
*opts
= NULL
;
611 /* Translate legacy options */
612 opts
= qemu_opts_create(&ssh_runtime_opts
, NULL
, 0, &error_abort
);
613 if (!qemu_opts_absorb_qdict(opts
, options
, errp
)) {
617 if (!ssh_process_legacy_options(options
, opts
, errp
)) {
621 /* Create the QAPI object */
622 v
= qobject_input_visitor_new_flat_confused(options
, errp
);
627 visit_type_BlockdevOptionsSsh(v
, NULL
, &result
, errp
);
633 /* Remove the processed options from the QDict (the visitor processes
634 * _all_ options in the QDict) */
635 while ((e
= qdict_first(options
))) {
636 qdict_del(options
, e
->key
);
644 static int connect_to_ssh(BDRVSSHState
*s
, BlockdevOptionsSsh
*opts
,
645 int ssh_flags
, int creat_mode
, Error
**errp
)
648 unsigned int port
= 0;
652 s
->user
= g_strdup(opts
->user
);
654 s
->user
= g_strdup(g_get_user_name());
656 error_setg_errno(errp
, errno
, "Can't get user name");
662 /* Pop the config into our state object, Exit if invalid */
663 s
->inet
= opts
->server
;
666 if (qemu_strtoui(s
->inet
->port
, NULL
, 10, &port
) < 0) {
667 error_setg(errp
, "Use only numeric port value");
672 /* Open the socket and connect. */
673 new_sock
= inet_connect_saddr(s
->inet
, errp
);
680 * Try to disable the Nagle algorithm on TCP sockets to reduce latency,
681 * but do not fail if it cannot be disabled.
683 r
= socket_set_nodelay(new_sock
);
685 warn_report("can't set TCP_NODELAY for the ssh server %s: %s",
686 s
->inet
->host
, strerror(errno
));
689 /* Create SSH session. */
690 s
->session
= ssh_new();
693 session_error_setg(errp
, s
, "failed to initialize libssh session");
698 * Make sure we are in blocking mode during the connection and
699 * authentication phases.
701 ssh_set_blocking(s
->session
, 1);
703 r
= ssh_options_set(s
->session
, SSH_OPTIONS_USER
, s
->user
);
706 session_error_setg(errp
, s
,
707 "failed to set the user in the libssh session");
711 r
= ssh_options_set(s
->session
, SSH_OPTIONS_HOST
, s
->inet
->host
);
714 session_error_setg(errp
, s
,
715 "failed to set the host in the libssh session");
720 r
= ssh_options_set(s
->session
, SSH_OPTIONS_PORT
, &port
);
723 session_error_setg(errp
, s
,
724 "failed to set the port in the libssh session");
729 r
= ssh_options_set(s
->session
, SSH_OPTIONS_COMPRESSION
, "none");
732 session_error_setg(errp
, s
,
733 "failed to disable the compression in the libssh "
738 /* Read ~/.ssh/config. */
739 r
= ssh_options_parse_config(s
->session
, NULL
);
742 session_error_setg(errp
, s
, "failed to parse ~/.ssh/config");
746 r
= ssh_options_set(s
->session
, SSH_OPTIONS_FD
, &new_sock
);
749 session_error_setg(errp
, s
,
750 "failed to set the socket in the libssh session");
753 /* libssh took ownership of the socket. */
758 r
= ssh_connect(s
->session
);
761 session_error_setg(errp
, s
, "failed to establish SSH session");
765 /* Check the remote host's key against known_hosts. */
766 ret
= check_host_key(s
, opts
->host_key_check
, errp
);
772 ret
= authenticate(s
, errp
);
778 s
->sftp
= sftp_new(s
->session
);
780 session_error_setg(errp
, s
, "failed to create sftp handle");
785 r
= sftp_init(s
->sftp
);
787 sftp_error_setg(errp
, s
, "failed to initialize sftp handle");
792 /* Open the remote file. */
793 trace_ssh_connect_to_ssh(opts
->path
, ssh_flags
, creat_mode
);
794 s
->sftp_handle
= sftp_open(s
->sftp
, opts
->path
, ssh_flags
, creat_mode
);
795 if (!s
->sftp_handle
) {
796 sftp_error_setg(errp
, s
, "failed to open remote file '%s'",
802 /* Make sure the SFTP file is handled in blocking mode. */
803 sftp_file_set_blocking(s
->sftp_handle
);
805 s
->attrs
= sftp_fstat(s
->sftp_handle
);
807 sftp_error_setg(errp
, s
, "failed to read file attributes");
815 sftp_attributes_free(s
->attrs
);
818 if (s
->sftp_handle
) {
819 sftp_close(s
->sftp_handle
);
821 s
->sftp_handle
= NULL
;
827 ssh_disconnect(s
->session
);
828 ssh_free(s
->session
);
839 static int ssh_open(BlockDriverState
*bs
, QDict
*options
, int bdrv_flags
,
842 BDRVSSHState
*s
= bs
->opaque
;
843 BlockdevOptionsSsh
*opts
;
850 if (bdrv_flags
& BDRV_O_RDWR
) {
853 ssh_flags
|= O_RDONLY
;
856 opts
= ssh_parse_options(options
, errp
);
862 ret
= connect_to_ssh(s
, opts
, ssh_flags
, 0, errp
);
867 /* Go non-blocking. */
868 ssh_set_blocking(s
->session
, 0);
870 if (s
->attrs
->type
== SSH_FILEXFER_TYPE_REGULAR
) {
871 bs
->supported_truncate_flags
= BDRV_REQ_ZERO_WRITE
;
874 qapi_free_BlockdevOptionsSsh(opts
);
879 qapi_free_BlockdevOptionsSsh(opts
);
884 /* Note: This is a blocking operation */
885 static int ssh_grow_file(BDRVSSHState
*s
, int64_t offset
, Error
**errp
)
888 char c
[1] = { '\0' };
889 int was_blocking
= ssh_is_blocking(s
->session
);
891 /* offset must be strictly greater than the current size so we do
892 * not overwrite anything */
893 assert(offset
> 0 && offset
> s
->attrs
->size
);
895 ssh_set_blocking(s
->session
, 1);
897 sftp_seek64(s
->sftp_handle
, offset
- 1);
898 ret
= sftp_write(s
->sftp_handle
, c
, 1);
900 ssh_set_blocking(s
->session
, was_blocking
);
903 sftp_error_setg(errp
, s
, "Failed to grow file");
907 s
->attrs
->size
= offset
;
911 static QemuOptsList ssh_create_opts
= {
912 .name
= "ssh-create-opts",
913 .head
= QTAILQ_HEAD_INITIALIZER(ssh_create_opts
.head
),
916 .name
= BLOCK_OPT_SIZE
,
917 .type
= QEMU_OPT_SIZE
,
918 .help
= "Virtual disk size"
920 { /* end of list */ }
924 static int ssh_co_create(BlockdevCreateOptions
*options
, Error
**errp
)
926 BlockdevCreateOptionsSsh
*opts
= &options
->u
.ssh
;
930 assert(options
->driver
== BLOCKDEV_DRIVER_SSH
);
934 ret
= connect_to_ssh(&s
, opts
->location
,
935 O_RDWR
| O_CREAT
| O_TRUNC
,
941 if (opts
->size
> 0) {
942 ret
= ssh_grow_file(&s
, opts
->size
, errp
);
954 static int coroutine_fn
ssh_co_create_opts(BlockDriver
*drv
,
955 const char *filename
,
959 BlockdevCreateOptions
*create_options
;
960 BlockdevCreateOptionsSsh
*ssh_opts
;
962 QDict
*uri_options
= NULL
;
964 create_options
= g_new0(BlockdevCreateOptions
, 1);
965 create_options
->driver
= BLOCKDEV_DRIVER_SSH
;
966 ssh_opts
= &create_options
->u
.ssh
;
968 /* Get desired file size. */
969 ssh_opts
->size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
971 trace_ssh_co_create_opts(ssh_opts
->size
);
973 uri_options
= qdict_new();
974 ret
= parse_uri(filename
, uri_options
, errp
);
979 ssh_opts
->location
= ssh_parse_options(uri_options
, errp
);
980 if (ssh_opts
->location
== NULL
) {
985 ret
= ssh_co_create(create_options
, errp
);
988 qobject_unref(uri_options
);
989 qapi_free_BlockdevCreateOptions(create_options
);
993 static void ssh_close(BlockDriverState
*bs
)
995 BDRVSSHState
*s
= bs
->opaque
;
1000 static int ssh_has_zero_init(BlockDriverState
*bs
)
1002 BDRVSSHState
*s
= bs
->opaque
;
1003 /* Assume false, unless we can positively prove it's true. */
1004 int has_zero_init
= 0;
1006 if (s
->attrs
->type
== SSH_FILEXFER_TYPE_REGULAR
) {
1010 return has_zero_init
;
1013 typedef struct BDRVSSHRestart
{
1014 BlockDriverState
*bs
;
1018 static void restart_coroutine(void *opaque
)
1020 BDRVSSHRestart
*restart
= opaque
;
1021 BlockDriverState
*bs
= restart
->bs
;
1022 BDRVSSHState
*s
= bs
->opaque
;
1023 AioContext
*ctx
= bdrv_get_aio_context(bs
);
1025 trace_ssh_restart_coroutine(restart
->co
);
1026 aio_set_fd_handler(ctx
, s
->sock
, NULL
, NULL
, NULL
, NULL
, NULL
);
1028 aio_co_wake(restart
->co
);
1031 /* A non-blocking call returned EAGAIN, so yield, ensuring the
1032 * handlers are set up so that we'll be rescheduled when there is an
1033 * interesting event on the socket.
1035 static coroutine_fn
void co_yield(BDRVSSHState
*s
, BlockDriverState
*bs
)
1038 IOHandler
*rd_handler
= NULL
, *wr_handler
= NULL
;
1039 BDRVSSHRestart restart
= {
1041 .co
= qemu_coroutine_self()
1044 r
= ssh_get_poll_flags(s
->session
);
1046 if (r
& SSH_READ_PENDING
) {
1047 rd_handler
= restart_coroutine
;
1049 if (r
& SSH_WRITE_PENDING
) {
1050 wr_handler
= restart_coroutine
;
1053 trace_ssh_co_yield(s
->sock
, rd_handler
, wr_handler
);
1055 aio_set_fd_handler(bdrv_get_aio_context(bs
), s
->sock
,
1056 rd_handler
, wr_handler
, NULL
, NULL
, &restart
);
1057 qemu_coroutine_yield();
1058 trace_ssh_co_yield_back(s
->sock
);
1061 static coroutine_fn
int ssh_read(BDRVSSHState
*s
, BlockDriverState
*bs
,
1062 int64_t offset
, size_t size
,
1067 char *buf
, *end_of_vec
;
1070 trace_ssh_read(offset
, size
);
1072 trace_ssh_seek(offset
);
1073 sftp_seek64(s
->sftp_handle
, offset
);
1075 /* This keeps track of the current iovec element ('i'), where we
1076 * will write to next ('buf'), and the end of the current iovec
1081 end_of_vec
= i
->iov_base
+ i
->iov_len
;
1083 for (got
= 0; got
< size
; ) {
1084 size_t request_read_size
;
1087 * The size of SFTP packets is limited to 32K bytes, so limit
1088 * the amount of data requested to 16K, as libssh currently
1089 * does not handle multiple requests on its own.
1091 request_read_size
= MIN(end_of_vec
- buf
, 16384);
1092 trace_ssh_read_buf(buf
, end_of_vec
- buf
, request_read_size
);
1093 r
= sftp_read(s
->sftp_handle
, buf
, request_read_size
);
1094 trace_ssh_read_return(r
, sftp_get_error(s
->sftp
));
1096 if (r
== SSH_AGAIN
) {
1100 if (r
== SSH_EOF
|| (r
== 0 && sftp_get_error(s
->sftp
) == SSH_FX_EOF
)) {
1101 /* EOF: Short read so pad the buffer with zeroes and return it. */
1102 qemu_iovec_memset(qiov
, got
, 0, size
- got
);
1106 sftp_error_trace(s
, "read");
1112 if (buf
>= end_of_vec
&& got
< size
) {
1115 end_of_vec
= i
->iov_base
+ i
->iov_len
;
1122 static coroutine_fn
int ssh_co_readv(BlockDriverState
*bs
,
1124 int nb_sectors
, QEMUIOVector
*qiov
)
1126 BDRVSSHState
*s
= bs
->opaque
;
1129 qemu_co_mutex_lock(&s
->lock
);
1130 ret
= ssh_read(s
, bs
, sector_num
* BDRV_SECTOR_SIZE
,
1131 nb_sectors
* BDRV_SECTOR_SIZE
, qiov
);
1132 qemu_co_mutex_unlock(&s
->lock
);
1137 static coroutine_fn
int ssh_write(BDRVSSHState
*s
, BlockDriverState
*bs
,
1138 int64_t offset
, size_t size
,
1143 char *buf
, *end_of_vec
;
1146 trace_ssh_write(offset
, size
);
1148 trace_ssh_seek(offset
);
1149 sftp_seek64(s
->sftp_handle
, offset
);
1151 /* This keeps track of the current iovec element ('i'), where we
1152 * will read from next ('buf'), and the end of the current iovec
1157 end_of_vec
= i
->iov_base
+ i
->iov_len
;
1159 for (written
= 0; written
< size
; ) {
1160 size_t request_write_size
;
1163 * Avoid too large data packets, as libssh currently does not
1164 * handle multiple requests on its own.
1166 request_write_size
= MIN(end_of_vec
- buf
, 131072);
1167 trace_ssh_write_buf(buf
, end_of_vec
- buf
, request_write_size
);
1168 r
= sftp_write(s
->sftp_handle
, buf
, request_write_size
);
1169 trace_ssh_write_return(r
, sftp_get_error(s
->sftp
));
1171 if (r
== SSH_AGAIN
) {
1176 sftp_error_trace(s
, "write");
1182 if (buf
>= end_of_vec
&& written
< size
) {
1185 end_of_vec
= i
->iov_base
+ i
->iov_len
;
1188 if (offset
+ written
> s
->attrs
->size
) {
1189 s
->attrs
->size
= offset
+ written
;
1196 static coroutine_fn
int ssh_co_writev(BlockDriverState
*bs
,
1198 int nb_sectors
, QEMUIOVector
*qiov
,
1201 BDRVSSHState
*s
= bs
->opaque
;
1204 qemu_co_mutex_lock(&s
->lock
);
1205 ret
= ssh_write(s
, bs
, sector_num
* BDRV_SECTOR_SIZE
,
1206 nb_sectors
* BDRV_SECTOR_SIZE
, qiov
);
1207 qemu_co_mutex_unlock(&s
->lock
);
1212 static void unsafe_flush_warning(BDRVSSHState
*s
, const char *what
)
1214 if (!s
->unsafe_flush_warning
) {
1215 warn_report("ssh server %s does not support fsync",
1218 error_report("to support fsync, you need %s", what
);
1220 s
->unsafe_flush_warning
= true;
1224 static coroutine_fn
int ssh_flush(BDRVSSHState
*s
, BlockDriverState
*bs
)
1230 if (!sftp_extension_supported(s
->sftp
, "fsync@openssh.com", "1")) {
1231 unsafe_flush_warning(s
, "OpenSSH >= 6.3");
1235 r
= sftp_fsync(s
->sftp_handle
);
1236 if (r
== SSH_AGAIN
) {
1241 sftp_error_trace(s
, "fsync");
1248 static coroutine_fn
int ssh_co_flush(BlockDriverState
*bs
)
1250 BDRVSSHState
*s
= bs
->opaque
;
1253 qemu_co_mutex_lock(&s
->lock
);
1254 ret
= ssh_flush(s
, bs
);
1255 qemu_co_mutex_unlock(&s
->lock
);
1260 static int64_t coroutine_fn
ssh_co_getlength(BlockDriverState
*bs
)
1262 BDRVSSHState
*s
= bs
->opaque
;
1265 /* Note we cannot make a libssh call here. */
1266 length
= (int64_t) s
->attrs
->size
;
1267 trace_ssh_getlength(length
);
1272 static int coroutine_fn
ssh_co_truncate(BlockDriverState
*bs
, int64_t offset
,
1273 bool exact
, PreallocMode prealloc
,
1274 BdrvRequestFlags flags
, Error
**errp
)
1276 BDRVSSHState
*s
= bs
->opaque
;
1278 if (prealloc
!= PREALLOC_MODE_OFF
) {
1279 error_setg(errp
, "Unsupported preallocation mode '%s'",
1280 PreallocMode_str(prealloc
));
1284 if (offset
< s
->attrs
->size
) {
1285 error_setg(errp
, "ssh driver does not support shrinking files");
1289 if (offset
== s
->attrs
->size
) {
1293 return ssh_grow_file(s
, offset
, errp
);
1296 static void ssh_refresh_filename(BlockDriverState
*bs
)
1298 BDRVSSHState
*s
= bs
->opaque
;
1299 const char *path
, *host_key_check
;
1303 * None of these options can be represented in a plain "host:port"
1304 * format, so if any was given, we have to abort.
1306 if (s
->inet
->has_ipv4
|| s
->inet
->has_ipv6
|| s
->inet
->has_to
||
1307 s
->inet
->has_numeric
)
1312 path
= qdict_get_try_str(bs
->full_open_options
, "path");
1313 assert(path
); /* mandatory option */
1315 host_key_check
= qdict_get_try_str(bs
->full_open_options
, "host_key_check");
1317 ret
= snprintf(bs
->exact_filename
, sizeof(bs
->exact_filename
),
1318 "ssh://%s@%s:%s%s%s%s",
1319 s
->user
, s
->inet
->host
, s
->inet
->port
, path
,
1320 host_key_check
? "?host_key_check=" : "",
1321 host_key_check
?: "");
1322 if (ret
>= sizeof(bs
->exact_filename
)) {
1323 /* An overflow makes the filename unusable, so do not report any */
1324 bs
->exact_filename
[0] = '\0';
1328 static char *ssh_bdrv_dirname(BlockDriverState
*bs
, Error
**errp
)
1330 if (qdict_haskey(bs
->full_open_options
, "host_key_check")) {
1332 * We cannot generate a simple prefix if we would have to
1333 * append a query string.
1336 "Cannot generate a base directory with host_key_check set");
1340 if (bs
->exact_filename
[0] == '\0') {
1341 error_setg(errp
, "Cannot generate a base directory for this ssh node");
1345 return path_combine(bs
->exact_filename
, "");
1348 static const char *const ssh_strong_runtime_opts
[] = {
1359 static BlockDriver bdrv_ssh
= {
1360 .format_name
= "ssh",
1361 .protocol_name
= "ssh",
1362 .instance_size
= sizeof(BDRVSSHState
),
1363 .bdrv_parse_filename
= ssh_parse_filename
,
1364 .bdrv_open
= ssh_open
,
1365 .bdrv_co_create
= ssh_co_create
,
1366 .bdrv_co_create_opts
= ssh_co_create_opts
,
1367 .bdrv_close
= ssh_close
,
1368 .bdrv_has_zero_init
= ssh_has_zero_init
,
1369 .bdrv_co_readv
= ssh_co_readv
,
1370 .bdrv_co_writev
= ssh_co_writev
,
1371 .bdrv_co_getlength
= ssh_co_getlength
,
1372 .bdrv_co_truncate
= ssh_co_truncate
,
1373 .bdrv_co_flush_to_disk
= ssh_co_flush
,
1374 .bdrv_refresh_filename
= ssh_refresh_filename
,
1375 .bdrv_dirname
= ssh_bdrv_dirname
,
1376 .create_opts
= &ssh_create_opts
,
1377 .strong_runtime_opts
= ssh_strong_runtime_opts
,
1380 static void bdrv_ssh_init(void)
1386 fprintf(stderr
, "libssh initialization failed, %d\n", r
);
1390 #if TRACE_LIBSSH != 0
1391 ssh_set_log_level(TRACE_LIBSSH
);
1394 bdrv_register(&bdrv_ssh
);
1397 block_init(bdrv_ssh_init
);