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_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_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 GCC_FMT_ATTR(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 GCC_FMT_ATTR(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
)
188 uri
= uri_parse(filename
);
193 if (g_strcmp0(uri
->scheme
, "ssh") != 0) {
194 error_setg(errp
, "URI scheme must be 'ssh'");
198 if (!uri
->server
|| strcmp(uri
->server
, "") == 0) {
199 error_setg(errp
, "missing hostname in URI");
203 if (!uri
->path
|| strcmp(uri
->path
, "") == 0) {
204 error_setg(errp
, "missing remote path in URI");
208 qp
= query_params_parse(uri
->query
);
210 error_setg(errp
, "could not parse query parameters");
214 if(uri
->user
&& strcmp(uri
->user
, "") != 0) {
215 qdict_put_str(options
, "user", uri
->user
);
218 qdict_put_str(options
, "server.host", uri
->server
);
220 port_str
= g_strdup_printf("%d", uri
->port
?: 22);
221 qdict_put_str(options
, "server.port", port_str
);
224 qdict_put_str(options
, "path", uri
->path
);
226 /* Pick out any query parameters that we understand, and ignore
229 for (i
= 0; i
< qp
->n
; ++i
) {
230 if (strcmp(qp
->p
[i
].name
, "host_key_check") == 0) {
231 qdict_put_str(options
, "host_key_check", qp
->p
[i
].value
);
235 query_params_free(qp
);
244 static bool ssh_has_filename_options_conflict(QDict
*options
, Error
**errp
)
246 const QDictEntry
*qe
;
248 for (qe
= qdict_first(options
); qe
; qe
= qdict_next(options
, qe
)) {
249 if (!strcmp(qe
->key
, "host") ||
250 !strcmp(qe
->key
, "port") ||
251 !strcmp(qe
->key
, "path") ||
252 !strcmp(qe
->key
, "user") ||
253 !strcmp(qe
->key
, "host_key_check") ||
254 strstart(qe
->key
, "server.", NULL
))
256 error_setg(errp
, "Option '%s' cannot be used with a file name",
265 static void ssh_parse_filename(const char *filename
, QDict
*options
,
268 if (ssh_has_filename_options_conflict(options
, errp
)) {
272 parse_uri(filename
, options
, errp
);
275 static int check_host_key_knownhosts(BDRVSSHState
*s
, Error
**errp
)
278 enum ssh_known_hosts_e state
;
281 enum ssh_keytypes_e pubkey_type
;
282 unsigned char *server_hash
= NULL
;
283 size_t server_hash_len
;
284 char *fingerprint
= NULL
;
286 state
= ssh_session_is_known_server(s
->session
);
287 trace_ssh_server_status(state
);
290 case SSH_KNOWN_HOSTS_OK
:
292 trace_ssh_check_host_key_knownhosts();
294 case SSH_KNOWN_HOSTS_CHANGED
:
296 r
= ssh_get_server_publickey(s
->session
, &pubkey
);
298 r
= ssh_get_publickey_hash(pubkey
, SSH_PUBLICKEY_HASH_SHA256
,
299 &server_hash
, &server_hash_len
);
300 pubkey_type
= ssh_key_type(pubkey
);
301 ssh_key_free(pubkey
);
304 fingerprint
= ssh_get_fingerprint_hash(SSH_PUBLICKEY_HASH_SHA256
,
307 ssh_clean_pubkey_hash(&server_hash
);
311 "host key (%s key with fingerprint %s) does not match "
312 "the one in known_hosts; this may be a possible attack",
313 ssh_key_type_to_char(pubkey_type
), fingerprint
);
314 ssh_string_free_char(fingerprint
);
317 "host key does not match the one in known_hosts; this "
318 "may be a possible attack");
321 case SSH_KNOWN_HOSTS_OTHER
:
324 "host key for this server not found, another type exists");
326 case SSH_KNOWN_HOSTS_UNKNOWN
:
328 error_setg(errp
, "no host key was found in known_hosts");
330 case SSH_KNOWN_HOSTS_NOT_FOUND
:
332 error_setg(errp
, "known_hosts file not found");
334 case SSH_KNOWN_HOSTS_ERROR
:
336 error_setg(errp
, "error while checking the host");
340 error_setg(errp
, "error while checking for known server (%d)", state
);
344 /* known_hosts checking successful. */
351 static unsigned hex2decimal(char ch
)
353 if (ch
>= '0' && ch
<= '9') {
355 } else if (ch
>= 'a' && ch
<= 'f') {
356 return 10 + (ch
- 'a');
357 } else if (ch
>= 'A' && ch
<= 'F') {
358 return 10 + (ch
- 'A');
364 /* Compare the binary fingerprint (hash of host key) with the
365 * host_key_check parameter.
367 static int compare_fingerprint(const unsigned char *fingerprint
, size_t len
,
368 const char *host_key_check
)
373 while (*host_key_check
== ':')
375 if (!qemu_isxdigit(host_key_check
[0]) ||
376 !qemu_isxdigit(host_key_check
[1]))
378 c
= hex2decimal(host_key_check
[0]) * 16 +
379 hex2decimal(host_key_check
[1]);
380 if (c
- *fingerprint
!= 0)
381 return c
- *fingerprint
;
386 return *host_key_check
- '\0';
389 static char *format_fingerprint(const unsigned char *fingerprint
, size_t len
)
391 static const char *hex
= "0123456789abcdef";
392 char *ret
= g_new0(char, (len
* 2) + 1);
393 for (size_t i
= 0; i
< len
; i
++) {
394 ret
[i
* 2] = hex
[((fingerprint
[i
] >> 4) & 0xf)];
395 ret
[(i
* 2) + 1] = hex
[(fingerprint
[i
] & 0xf)];
402 check_host_key_hash(BDRVSSHState
*s
, const char *hash
,
403 enum ssh_publickey_hash_type type
, const char *typestr
,
408 unsigned char *server_hash
;
409 size_t server_hash_len
;
412 r
= ssh_get_server_publickey(s
->session
, &pubkey
);
414 session_error_setg(errp
, s
, "failed to read remote host key");
418 keytype
= ssh_key_type_to_char(ssh_key_type(pubkey
));
420 r
= ssh_get_publickey_hash(pubkey
, type
, &server_hash
, &server_hash_len
);
421 ssh_key_free(pubkey
);
423 session_error_setg(errp
, s
,
424 "failed reading the hash of the server SSH key");
428 r
= compare_fingerprint(server_hash
, server_hash_len
, hash
);
430 g_autofree
char *server_fp
= format_fingerprint(server_hash
,
432 error_setg(errp
, "remote host %s key fingerprint '%s:%s' "
433 "does not match host_key_check '%s:%s'",
434 keytype
, typestr
, server_fp
, typestr
, hash
);
435 ssh_clean_pubkey_hash(&server_hash
);
438 ssh_clean_pubkey_hash(&server_hash
);
443 static int check_host_key(BDRVSSHState
*s
, SshHostKeyCheck
*hkc
, Error
**errp
)
445 SshHostKeyCheckMode mode
;
450 mode
= SSH_HOST_KEY_CHECK_MODE_KNOWN_HOSTS
;
454 case SSH_HOST_KEY_CHECK_MODE_NONE
:
456 case SSH_HOST_KEY_CHECK_MODE_HASH
:
457 if (hkc
->u
.hash
.type
== SSH_HOST_KEY_CHECK_HASH_TYPE_MD5
) {
458 return check_host_key_hash(s
, hkc
->u
.hash
.hash
,
459 SSH_PUBLICKEY_HASH_MD5
, "md5",
461 } else if (hkc
->u
.hash
.type
== SSH_HOST_KEY_CHECK_HASH_TYPE_SHA1
) {
462 return check_host_key_hash(s
, hkc
->u
.hash
.hash
,
463 SSH_PUBLICKEY_HASH_SHA1
, "sha1",
465 } else if (hkc
->u
.hash
.type
== SSH_HOST_KEY_CHECK_HASH_TYPE_SHA256
) {
466 return check_host_key_hash(s
, hkc
->u
.hash
.hash
,
467 SSH_PUBLICKEY_HASH_SHA256
, "sha256",
470 g_assert_not_reached();
472 case SSH_HOST_KEY_CHECK_MODE_KNOWN_HOSTS
:
473 return check_host_key_knownhosts(s
, errp
);
475 g_assert_not_reached();
481 static int authenticate(BDRVSSHState
*s
, Error
**errp
)
486 /* Try to authenticate with the "none" method. */
487 r
= ssh_userauth_none(s
->session
, NULL
);
488 if (r
== SSH_AUTH_ERROR
) {
490 session_error_setg(errp
, s
, "failed to authenticate using none "
493 } else if (r
== SSH_AUTH_SUCCESS
) {
499 method
= ssh_userauth_list(s
->session
, NULL
);
500 trace_ssh_auth_methods(method
);
503 * Try to authenticate with publickey, using the ssh-agent
506 if (method
& SSH_AUTH_METHOD_PUBLICKEY
) {
507 r
= ssh_userauth_publickey_auto(s
->session
, NULL
, NULL
);
508 if (r
== SSH_AUTH_ERROR
) {
510 session_error_setg(errp
, s
, "failed to authenticate using "
511 "publickey authentication");
513 } else if (r
== SSH_AUTH_SUCCESS
) {
521 error_setg(errp
, "failed to authenticate using publickey authentication "
522 "and the identities held by your ssh-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 (strncmp(host_key_check
, "sha256:", 7) == 0) {
583 qdict_put_str(output_opts
, "host-key-check.mode", "hash");
584 qdict_put_str(output_opts
, "host-key-check.type", "sha256");
585 qdict_put_str(output_opts
, "host-key-check.hash",
587 } else if (strcmp(host_key_check
, "yes") == 0) {
588 qdict_put_str(output_opts
, "host-key-check.mode", "known_hosts");
590 error_setg(errp
, "unknown host_key_check setting (%s)",
599 static BlockdevOptionsSsh
*ssh_parse_options(QDict
*options
, Error
**errp
)
601 BlockdevOptionsSsh
*result
= NULL
;
602 QemuOpts
*opts
= NULL
;
606 /* Translate legacy options */
607 opts
= qemu_opts_create(&ssh_runtime_opts
, NULL
, 0, &error_abort
);
608 if (!qemu_opts_absorb_qdict(opts
, options
, errp
)) {
612 if (!ssh_process_legacy_options(options
, opts
, errp
)) {
616 /* Create the QAPI object */
617 v
= qobject_input_visitor_new_flat_confused(options
, errp
);
622 visit_type_BlockdevOptionsSsh(v
, NULL
, &result
, errp
);
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
)
643 unsigned int port
= 0;
646 if (opts
->has_user
) {
647 s
->user
= g_strdup(opts
->user
);
649 s
->user
= g_strdup(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_strtoui(s
->inet
->port
, NULL
, 10, &port
) < 0) {
662 error_setg(errp
, "Use only numeric port value");
667 /* Open the socket and connect. */
668 new_sock
= inet_connect_saddr(s
->inet
, errp
);
675 * Try to disable the Nagle algorithm on TCP sockets to reduce latency,
676 * but do not fail if it cannot be disabled.
678 r
= socket_set_nodelay(new_sock
);
680 warn_report("can't set TCP_NODELAY for the ssh server %s: %s",
681 s
->inet
->host
, strerror(errno
));
684 /* Create SSH session. */
685 s
->session
= ssh_new();
688 session_error_setg(errp
, s
, "failed to initialize libssh session");
693 * Make sure we are in blocking mode during the connection and
694 * authentication phases.
696 ssh_set_blocking(s
->session
, 1);
698 r
= ssh_options_set(s
->session
, SSH_OPTIONS_USER
, s
->user
);
701 session_error_setg(errp
, s
,
702 "failed to set the user in the libssh session");
706 r
= ssh_options_set(s
->session
, SSH_OPTIONS_HOST
, s
->inet
->host
);
709 session_error_setg(errp
, s
,
710 "failed to set the host in the libssh session");
715 r
= ssh_options_set(s
->session
, SSH_OPTIONS_PORT
, &port
);
718 session_error_setg(errp
, s
,
719 "failed to set the port in the libssh session");
724 r
= ssh_options_set(s
->session
, SSH_OPTIONS_COMPRESSION
, "none");
727 session_error_setg(errp
, s
,
728 "failed to disable the compression in the libssh "
733 /* Read ~/.ssh/config. */
734 r
= ssh_options_parse_config(s
->session
, NULL
);
737 session_error_setg(errp
, s
, "failed to parse ~/.ssh/config");
741 r
= ssh_options_set(s
->session
, SSH_OPTIONS_FD
, &new_sock
);
744 session_error_setg(errp
, s
,
745 "failed to set the socket in the libssh session");
748 /* libssh took ownership of the socket. */
753 r
= ssh_connect(s
->session
);
756 session_error_setg(errp
, s
, "failed to establish SSH session");
760 /* Check the remote host's key against known_hosts. */
761 ret
= check_host_key(s
, opts
->host_key_check
, errp
);
767 ret
= authenticate(s
, errp
);
773 s
->sftp
= sftp_new(s
->session
);
775 session_error_setg(errp
, s
, "failed to create sftp handle");
780 r
= sftp_init(s
->sftp
);
782 sftp_error_setg(errp
, s
, "failed to initialize sftp handle");
787 /* Open the remote file. */
788 trace_ssh_connect_to_ssh(opts
->path
, ssh_flags
, creat_mode
);
789 s
->sftp_handle
= sftp_open(s
->sftp
, opts
->path
, ssh_flags
, creat_mode
);
790 if (!s
->sftp_handle
) {
791 sftp_error_setg(errp
, s
, "failed to open remote file '%s'",
797 /* Make sure the SFTP file is handled in blocking mode. */
798 sftp_file_set_blocking(s
->sftp_handle
);
800 s
->attrs
= sftp_fstat(s
->sftp_handle
);
802 sftp_error_setg(errp
, s
, "failed to read file attributes");
810 sftp_attributes_free(s
->attrs
);
813 if (s
->sftp_handle
) {
814 sftp_close(s
->sftp_handle
);
816 s
->sftp_handle
= NULL
;
822 ssh_disconnect(s
->session
);
823 ssh_free(s
->session
);
834 static int ssh_file_open(BlockDriverState
*bs
, QDict
*options
, int bdrv_flags
,
837 BDRVSSHState
*s
= bs
->opaque
;
838 BlockdevOptionsSsh
*opts
;
845 if (bdrv_flags
& BDRV_O_RDWR
) {
848 ssh_flags
|= O_RDONLY
;
851 opts
= ssh_parse_options(options
, errp
);
857 ret
= connect_to_ssh(s
, opts
, ssh_flags
, 0, errp
);
862 /* Go non-blocking. */
863 ssh_set_blocking(s
->session
, 0);
865 if (s
->attrs
->type
== SSH_FILEXFER_TYPE_REGULAR
) {
866 bs
->supported_truncate_flags
= BDRV_REQ_ZERO_WRITE
;
869 qapi_free_BlockdevOptionsSsh(opts
);
874 qapi_free_BlockdevOptionsSsh(opts
);
879 /* Note: This is a blocking operation */
880 static int ssh_grow_file(BDRVSSHState
*s
, int64_t offset
, Error
**errp
)
883 char c
[1] = { '\0' };
884 int was_blocking
= ssh_is_blocking(s
->session
);
886 /* offset must be strictly greater than the current size so we do
887 * not overwrite anything */
888 assert(offset
> 0 && offset
> s
->attrs
->size
);
890 ssh_set_blocking(s
->session
, 1);
892 sftp_seek64(s
->sftp_handle
, offset
- 1);
893 ret
= sftp_write(s
->sftp_handle
, c
, 1);
895 ssh_set_blocking(s
->session
, was_blocking
);
898 sftp_error_setg(errp
, s
, "Failed to grow file");
902 s
->attrs
->size
= offset
;
906 static QemuOptsList ssh_create_opts
= {
907 .name
= "ssh-create-opts",
908 .head
= QTAILQ_HEAD_INITIALIZER(ssh_create_opts
.head
),
911 .name
= BLOCK_OPT_SIZE
,
912 .type
= QEMU_OPT_SIZE
,
913 .help
= "Virtual disk size"
915 { /* end of list */ }
919 static int ssh_co_create(BlockdevCreateOptions
*options
, Error
**errp
)
921 BlockdevCreateOptionsSsh
*opts
= &options
->u
.ssh
;
925 assert(options
->driver
== BLOCKDEV_DRIVER_SSH
);
929 ret
= connect_to_ssh(&s
, opts
->location
,
930 O_RDWR
| O_CREAT
| O_TRUNC
,
936 if (opts
->size
> 0) {
937 ret
= ssh_grow_file(&s
, opts
->size
, errp
);
949 static int coroutine_fn
ssh_co_create_opts(BlockDriver
*drv
,
950 const char *filename
,
954 BlockdevCreateOptions
*create_options
;
955 BlockdevCreateOptionsSsh
*ssh_opts
;
957 QDict
*uri_options
= NULL
;
959 create_options
= g_new0(BlockdevCreateOptions
, 1);
960 create_options
->driver
= BLOCKDEV_DRIVER_SSH
;
961 ssh_opts
= &create_options
->u
.ssh
;
963 /* Get desired file size. */
964 ssh_opts
->size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
966 trace_ssh_co_create_opts(ssh_opts
->size
);
968 uri_options
= qdict_new();
969 ret
= parse_uri(filename
, uri_options
, errp
);
974 ssh_opts
->location
= ssh_parse_options(uri_options
, errp
);
975 if (ssh_opts
->location
== NULL
) {
980 ret
= ssh_co_create(create_options
, errp
);
983 qobject_unref(uri_options
);
984 qapi_free_BlockdevCreateOptions(create_options
);
988 static void ssh_close(BlockDriverState
*bs
)
990 BDRVSSHState
*s
= bs
->opaque
;
995 static int ssh_has_zero_init(BlockDriverState
*bs
)
997 BDRVSSHState
*s
= bs
->opaque
;
998 /* Assume false, unless we can positively prove it's true. */
999 int has_zero_init
= 0;
1001 if (s
->attrs
->type
== SSH_FILEXFER_TYPE_REGULAR
) {
1005 return has_zero_init
;
1008 typedef struct BDRVSSHRestart
{
1009 BlockDriverState
*bs
;
1013 static void restart_coroutine(void *opaque
)
1015 BDRVSSHRestart
*restart
= opaque
;
1016 BlockDriverState
*bs
= restart
->bs
;
1017 BDRVSSHState
*s
= bs
->opaque
;
1018 AioContext
*ctx
= bdrv_get_aio_context(bs
);
1020 trace_ssh_restart_coroutine(restart
->co
);
1021 aio_set_fd_handler(ctx
, s
->sock
, false, NULL
, NULL
, NULL
, NULL
, NULL
);
1023 aio_co_wake(restart
->co
);
1026 /* A non-blocking call returned EAGAIN, so yield, ensuring the
1027 * handlers are set up so that we'll be rescheduled when there is an
1028 * interesting event on the socket.
1030 static coroutine_fn
void co_yield(BDRVSSHState
*s
, BlockDriverState
*bs
)
1033 IOHandler
*rd_handler
= NULL
, *wr_handler
= NULL
;
1034 BDRVSSHRestart restart
= {
1036 .co
= qemu_coroutine_self()
1039 r
= ssh_get_poll_flags(s
->session
);
1041 if (r
& SSH_READ_PENDING
) {
1042 rd_handler
= restart_coroutine
;
1044 if (r
& SSH_WRITE_PENDING
) {
1045 wr_handler
= restart_coroutine
;
1048 trace_ssh_co_yield(s
->sock
, rd_handler
, wr_handler
);
1050 aio_set_fd_handler(bdrv_get_aio_context(bs
), s
->sock
,
1051 false, rd_handler
, wr_handler
, NULL
, NULL
, &restart
);
1052 qemu_coroutine_yield();
1053 trace_ssh_co_yield_back(s
->sock
);
1056 static coroutine_fn
int ssh_read(BDRVSSHState
*s
, BlockDriverState
*bs
,
1057 int64_t offset
, size_t size
,
1062 char *buf
, *end_of_vec
;
1065 trace_ssh_read(offset
, size
);
1067 trace_ssh_seek(offset
);
1068 sftp_seek64(s
->sftp_handle
, offset
);
1070 /* This keeps track of the current iovec element ('i'), where we
1071 * will write to next ('buf'), and the end of the current iovec
1076 end_of_vec
= i
->iov_base
+ i
->iov_len
;
1078 for (got
= 0; got
< size
; ) {
1079 size_t request_read_size
;
1082 * The size of SFTP packets is limited to 32K bytes, so limit
1083 * the amount of data requested to 16K, as libssh currently
1084 * does not handle multiple requests on its own.
1086 request_read_size
= MIN(end_of_vec
- buf
, 16384);
1087 trace_ssh_read_buf(buf
, end_of_vec
- buf
, request_read_size
);
1088 r
= sftp_read(s
->sftp_handle
, buf
, request_read_size
);
1089 trace_ssh_read_return(r
, sftp_get_error(s
->sftp
));
1091 if (r
== SSH_AGAIN
) {
1095 if (r
== SSH_EOF
|| (r
== 0 && sftp_get_error(s
->sftp
) == SSH_FX_EOF
)) {
1096 /* EOF: Short read so pad the buffer with zeroes and return it. */
1097 qemu_iovec_memset(qiov
, got
, 0, size
- got
);
1101 sftp_error_trace(s
, "read");
1107 if (buf
>= end_of_vec
&& got
< size
) {
1110 end_of_vec
= i
->iov_base
+ i
->iov_len
;
1117 static coroutine_fn
int ssh_co_readv(BlockDriverState
*bs
,
1119 int nb_sectors
, QEMUIOVector
*qiov
)
1121 BDRVSSHState
*s
= bs
->opaque
;
1124 qemu_co_mutex_lock(&s
->lock
);
1125 ret
= ssh_read(s
, bs
, sector_num
* BDRV_SECTOR_SIZE
,
1126 nb_sectors
* BDRV_SECTOR_SIZE
, qiov
);
1127 qemu_co_mutex_unlock(&s
->lock
);
1132 static int ssh_write(BDRVSSHState
*s
, BlockDriverState
*bs
,
1133 int64_t offset
, size_t size
,
1138 char *buf
, *end_of_vec
;
1141 trace_ssh_write(offset
, size
);
1143 trace_ssh_seek(offset
);
1144 sftp_seek64(s
->sftp_handle
, offset
);
1146 /* This keeps track of the current iovec element ('i'), where we
1147 * will read from next ('buf'), and the end of the current iovec
1152 end_of_vec
= i
->iov_base
+ i
->iov_len
;
1154 for (written
= 0; written
< size
; ) {
1155 size_t request_write_size
;
1158 * Avoid too large data packets, as libssh currently does not
1159 * handle multiple requests on its own.
1161 request_write_size
= MIN(end_of_vec
- buf
, 131072);
1162 trace_ssh_write_buf(buf
, end_of_vec
- buf
, request_write_size
);
1163 r
= sftp_write(s
->sftp_handle
, buf
, request_write_size
);
1164 trace_ssh_write_return(r
, sftp_get_error(s
->sftp
));
1166 if (r
== SSH_AGAIN
) {
1171 sftp_error_trace(s
, "write");
1177 if (buf
>= end_of_vec
&& written
< size
) {
1180 end_of_vec
= i
->iov_base
+ i
->iov_len
;
1183 if (offset
+ written
> s
->attrs
->size
) {
1184 s
->attrs
->size
= offset
+ written
;
1191 static coroutine_fn
int ssh_co_writev(BlockDriverState
*bs
,
1193 int nb_sectors
, QEMUIOVector
*qiov
,
1196 BDRVSSHState
*s
= bs
->opaque
;
1200 qemu_co_mutex_lock(&s
->lock
);
1201 ret
= ssh_write(s
, bs
, sector_num
* BDRV_SECTOR_SIZE
,
1202 nb_sectors
* BDRV_SECTOR_SIZE
, qiov
);
1203 qemu_co_mutex_unlock(&s
->lock
);
1208 static void unsafe_flush_warning(BDRVSSHState
*s
, const char *what
)
1210 if (!s
->unsafe_flush_warning
) {
1211 warn_report("ssh server %s does not support fsync",
1214 error_report("to support fsync, you need %s", what
);
1216 s
->unsafe_flush_warning
= true;
1220 static coroutine_fn
int ssh_flush(BDRVSSHState
*s
, BlockDriverState
*bs
)
1226 if (!sftp_extension_supported(s
->sftp
, "fsync@openssh.com", "1")) {
1227 unsafe_flush_warning(s
, "OpenSSH >= 6.3");
1231 r
= sftp_fsync(s
->sftp_handle
);
1232 if (r
== SSH_AGAIN
) {
1237 sftp_error_trace(s
, "fsync");
1244 static coroutine_fn
int ssh_co_flush(BlockDriverState
*bs
)
1246 BDRVSSHState
*s
= bs
->opaque
;
1249 qemu_co_mutex_lock(&s
->lock
);
1250 ret
= ssh_flush(s
, bs
);
1251 qemu_co_mutex_unlock(&s
->lock
);
1256 static int64_t ssh_getlength(BlockDriverState
*bs
)
1258 BDRVSSHState
*s
= bs
->opaque
;
1261 /* Note we cannot make a libssh call here. */
1262 length
= (int64_t) s
->attrs
->size
;
1263 trace_ssh_getlength(length
);
1268 static int coroutine_fn
ssh_co_truncate(BlockDriverState
*bs
, int64_t offset
,
1269 bool exact
, PreallocMode prealloc
,
1270 BdrvRequestFlags flags
, Error
**errp
)
1272 BDRVSSHState
*s
= bs
->opaque
;
1274 if (prealloc
!= PREALLOC_MODE_OFF
) {
1275 error_setg(errp
, "Unsupported preallocation mode '%s'",
1276 PreallocMode_str(prealloc
));
1280 if (offset
< s
->attrs
->size
) {
1281 error_setg(errp
, "ssh driver does not support shrinking files");
1285 if (offset
== s
->attrs
->size
) {
1289 return ssh_grow_file(s
, offset
, errp
);
1292 static void ssh_refresh_filename(BlockDriverState
*bs
)
1294 BDRVSSHState
*s
= bs
->opaque
;
1295 const char *path
, *host_key_check
;
1299 * None of these options can be represented in a plain "host:port"
1300 * format, so if any was given, we have to abort.
1302 if (s
->inet
->has_ipv4
|| s
->inet
->has_ipv6
|| s
->inet
->has_to
||
1303 s
->inet
->has_numeric
)
1308 path
= qdict_get_try_str(bs
->full_open_options
, "path");
1309 assert(path
); /* mandatory option */
1311 host_key_check
= qdict_get_try_str(bs
->full_open_options
, "host_key_check");
1313 ret
= snprintf(bs
->exact_filename
, sizeof(bs
->exact_filename
),
1314 "ssh://%s@%s:%s%s%s%s",
1315 s
->user
, s
->inet
->host
, s
->inet
->port
, path
,
1316 host_key_check
? "?host_key_check=" : "",
1317 host_key_check
?: "");
1318 if (ret
>= sizeof(bs
->exact_filename
)) {
1319 /* An overflow makes the filename unusable, so do not report any */
1320 bs
->exact_filename
[0] = '\0';
1324 static char *ssh_bdrv_dirname(BlockDriverState
*bs
, Error
**errp
)
1326 if (qdict_haskey(bs
->full_open_options
, "host_key_check")) {
1328 * We cannot generate a simple prefix if we would have to
1329 * append a query string.
1332 "Cannot generate a base directory with host_key_check set");
1336 if (bs
->exact_filename
[0] == '\0') {
1337 error_setg(errp
, "Cannot generate a base directory for this ssh node");
1341 return path_combine(bs
->exact_filename
, "");
1344 static const char *const ssh_strong_runtime_opts
[] = {
1355 static BlockDriver bdrv_ssh
= {
1356 .format_name
= "ssh",
1357 .protocol_name
= "ssh",
1358 .instance_size
= sizeof(BDRVSSHState
),
1359 .bdrv_parse_filename
= ssh_parse_filename
,
1360 .bdrv_file_open
= ssh_file_open
,
1361 .bdrv_co_create
= ssh_co_create
,
1362 .bdrv_co_create_opts
= ssh_co_create_opts
,
1363 .bdrv_close
= ssh_close
,
1364 .bdrv_has_zero_init
= ssh_has_zero_init
,
1365 .bdrv_co_readv
= ssh_co_readv
,
1366 .bdrv_co_writev
= ssh_co_writev
,
1367 .bdrv_getlength
= ssh_getlength
,
1368 .bdrv_co_truncate
= ssh_co_truncate
,
1369 .bdrv_co_flush_to_disk
= ssh_co_flush
,
1370 .bdrv_refresh_filename
= ssh_refresh_filename
,
1371 .bdrv_dirname
= ssh_bdrv_dirname
,
1372 .create_opts
= &ssh_create_opts
,
1373 .strong_runtime_opts
= ssh_strong_runtime_opts
,
1376 static void bdrv_ssh_init(void)
1382 fprintf(stderr
, "libssh initialization failed, %d\n", r
);
1386 #if TRACE_LIBSSH != 0
1387 ssh_set_log_level(TRACE_LIBSSH
);
1390 bdrv_register(&bdrv_ssh
);
1393 block_init(bdrv_ssh_init
);