spapr/xive: introduce a VM state change handler
[qemu/ar7.git] / block / ssh.c
blob12fd4f39e8e96e78ec414d2a3fbfc47b7849da27
1 /*
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
22 * THE SOFTWARE.
25 #include "qemu/osdep.h"
27 #include <libssh2.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"
37 #include "qemu/uri.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"
44 #include "trace.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 {
56 /* Coroutine. */
57 CoMutex lock;
59 /* SSH connection. */
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. */
66 int64_t offset;
67 bool offset_op_read;
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 * Store the user name for ssh_refresh_filename() because the
81 * default depends on the system you are on -- therefore, when we
82 * generate a filename, it should always contain the user name we
83 * are actually using.
85 char *user;
86 } BDRVSSHState;
88 static void ssh_state_init(BDRVSSHState *s)
90 memset(s, 0, sizeof *s);
91 s->sock = -1;
92 s->offset = -1;
93 qemu_co_mutex_init(&s->lock);
96 static void ssh_state_free(BDRVSSHState *s)
98 g_free(s->user);
100 if (s->sftp_handle) {
101 libssh2_sftp_close(s->sftp_handle);
103 if (s->sftp) {
104 libssh2_sftp_shutdown(s->sftp);
106 if (s->session) {
107 libssh2_session_disconnect(s->session,
108 "from qemu ssh client: "
109 "user closed the connection");
110 libssh2_session_free(s->session);
112 if (s->sock >= 0) {
113 close(s->sock);
117 static void GCC_FMT_ATTR(3, 4)
118 session_error_setg(Error **errp, BDRVSSHState *s, const char *fs, ...)
120 va_list args;
121 char *msg;
123 va_start(args, fs);
124 msg = g_strdup_vprintf(fs, args);
125 va_end(args);
127 if (s->session) {
128 char *ssh_err;
129 int ssh_err_code;
131 /* This is not an errno. See <libssh2.h>. */
132 ssh_err_code = libssh2_session_last_error(s->session,
133 &ssh_err, NULL, 0);
134 error_setg(errp, "%s: %s (libssh2 error code: %d)",
135 msg, ssh_err, ssh_err_code);
136 } else {
137 error_setg(errp, "%s", msg);
139 g_free(msg);
142 static void GCC_FMT_ATTR(3, 4)
143 sftp_error_setg(Error **errp, BDRVSSHState *s, const char *fs, ...)
145 va_list args;
146 char *msg;
148 va_start(args, fs);
149 msg = g_strdup_vprintf(fs, args);
150 va_end(args);
152 if (s->sftp) {
153 char *ssh_err;
154 int ssh_err_code;
155 unsigned long sftp_err_code;
157 /* This is not an errno. See <libssh2.h>. */
158 ssh_err_code = libssh2_session_last_error(s->session,
159 &ssh_err, NULL, 0);
160 /* See <libssh2_sftp.h>. */
161 sftp_err_code = libssh2_sftp_last_error((s)->sftp);
163 error_setg(errp,
164 "%s: %s (libssh2 error code: %d, sftp error code: %lu)",
165 msg, ssh_err, ssh_err_code, sftp_err_code);
166 } else {
167 error_setg(errp, "%s", msg);
169 g_free(msg);
172 static void sftp_error_trace(BDRVSSHState *s, const char *op)
174 char *ssh_err;
175 int ssh_err_code;
176 unsigned long sftp_err_code;
178 /* This is not an errno. See <libssh2.h>. */
179 ssh_err_code = libssh2_session_last_error(s->session,
180 &ssh_err, NULL, 0);
181 /* See <libssh2_sftp.h>. */
182 sftp_err_code = libssh2_sftp_last_error((s)->sftp);
184 trace_sftp_error(op, ssh_err, ssh_err_code, sftp_err_code);
187 static int parse_uri(const char *filename, QDict *options, Error **errp)
189 URI *uri = NULL;
190 QueryParams *qp;
191 char *port_str;
192 int i;
194 uri = uri_parse(filename);
195 if (!uri) {
196 return -EINVAL;
199 if (g_strcmp0(uri->scheme, "ssh") != 0) {
200 error_setg(errp, "URI scheme must be 'ssh'");
201 goto err;
204 if (!uri->server || strcmp(uri->server, "") == 0) {
205 error_setg(errp, "missing hostname in URI");
206 goto err;
209 if (!uri->path || strcmp(uri->path, "") == 0) {
210 error_setg(errp, "missing remote path in URI");
211 goto err;
214 qp = query_params_parse(uri->query);
215 if (!qp) {
216 error_setg(errp, "could not parse query parameters");
217 goto err;
220 if(uri->user && strcmp(uri->user, "") != 0) {
221 qdict_put_str(options, "user", uri->user);
224 qdict_put_str(options, "server.host", uri->server);
226 port_str = g_strdup_printf("%d", uri->port ?: 22);
227 qdict_put_str(options, "server.port", port_str);
228 g_free(port_str);
230 qdict_put_str(options, "path", uri->path);
232 /* Pick out any query parameters that we understand, and ignore
233 * the rest.
235 for (i = 0; i < qp->n; ++i) {
236 if (strcmp(qp->p[i].name, "host_key_check") == 0) {
237 qdict_put_str(options, "host_key_check", qp->p[i].value);
241 query_params_free(qp);
242 uri_free(uri);
243 return 0;
245 err:
246 if (uri) {
247 uri_free(uri);
249 return -EINVAL;
252 static bool ssh_has_filename_options_conflict(QDict *options, Error **errp)
254 const QDictEntry *qe;
256 for (qe = qdict_first(options); qe; qe = qdict_next(options, qe)) {
257 if (!strcmp(qe->key, "host") ||
258 !strcmp(qe->key, "port") ||
259 !strcmp(qe->key, "path") ||
260 !strcmp(qe->key, "user") ||
261 !strcmp(qe->key, "host_key_check") ||
262 strstart(qe->key, "server.", NULL))
264 error_setg(errp, "Option '%s' cannot be used with a file name",
265 qe->key);
266 return true;
270 return false;
273 static void ssh_parse_filename(const char *filename, QDict *options,
274 Error **errp)
276 if (ssh_has_filename_options_conflict(options, errp)) {
277 return;
280 parse_uri(filename, options, errp);
283 static int check_host_key_knownhosts(BDRVSSHState *s,
284 const char *host, int port, Error **errp)
286 const char *home;
287 char *knh_file = NULL;
288 LIBSSH2_KNOWNHOSTS *knh = NULL;
289 struct libssh2_knownhost *found;
290 int ret, r;
291 const char *hostkey;
292 size_t len;
293 int type;
295 hostkey = libssh2_session_hostkey(s->session, &len, &type);
296 if (!hostkey) {
297 ret = -EINVAL;
298 session_error_setg(errp, s, "failed to read remote host key");
299 goto out;
302 knh = libssh2_knownhost_init(s->session);
303 if (!knh) {
304 ret = -EINVAL;
305 session_error_setg(errp, s,
306 "failed to initialize known hosts support");
307 goto out;
310 home = getenv("HOME");
311 if (home) {
312 knh_file = g_strdup_printf("%s/.ssh/known_hosts", home);
313 } else {
314 knh_file = g_strdup_printf("/root/.ssh/known_hosts");
317 /* Read all known hosts from OpenSSH-style known_hosts file. */
318 libssh2_knownhost_readfile(knh, knh_file, LIBSSH2_KNOWNHOST_FILE_OPENSSH);
320 r = libssh2_knownhost_checkp(knh, host, port, hostkey, len,
321 LIBSSH2_KNOWNHOST_TYPE_PLAIN|
322 LIBSSH2_KNOWNHOST_KEYENC_RAW,
323 &found);
324 switch (r) {
325 case LIBSSH2_KNOWNHOST_CHECK_MATCH:
326 /* OK */
327 trace_ssh_check_host_key_knownhosts(found->key);
328 break;
329 case LIBSSH2_KNOWNHOST_CHECK_MISMATCH:
330 ret = -EINVAL;
331 session_error_setg(errp, s,
332 "host key does not match the one in known_hosts"
333 " (found key %s)", found->key);
334 goto out;
335 case LIBSSH2_KNOWNHOST_CHECK_NOTFOUND:
336 ret = -EINVAL;
337 session_error_setg(errp, s, "no host key was found in known_hosts");
338 goto out;
339 case LIBSSH2_KNOWNHOST_CHECK_FAILURE:
340 ret = -EINVAL;
341 session_error_setg(errp, s,
342 "failure matching the host key with known_hosts");
343 goto out;
344 default:
345 ret = -EINVAL;
346 session_error_setg(errp, s, "unknown error matching the host key"
347 " with known_hosts (%d)", r);
348 goto out;
351 /* known_hosts checking successful. */
352 ret = 0;
354 out:
355 if (knh != NULL) {
356 libssh2_knownhost_free(knh);
358 g_free(knh_file);
359 return ret;
362 static unsigned hex2decimal(char ch)
364 if (ch >= '0' && ch <= '9') {
365 return (ch - '0');
366 } else if (ch >= 'a' && ch <= 'f') {
367 return 10 + (ch - 'a');
368 } else if (ch >= 'A' && ch <= 'F') {
369 return 10 + (ch - 'A');
372 return -1;
375 /* Compare the binary fingerprint (hash of host key) with the
376 * host_key_check parameter.
378 static int compare_fingerprint(const unsigned char *fingerprint, size_t len,
379 const char *host_key_check)
381 unsigned c;
383 while (len > 0) {
384 while (*host_key_check == ':')
385 host_key_check++;
386 if (!qemu_isxdigit(host_key_check[0]) ||
387 !qemu_isxdigit(host_key_check[1]))
388 return 1;
389 c = hex2decimal(host_key_check[0]) * 16 +
390 hex2decimal(host_key_check[1]);
391 if (c - *fingerprint != 0)
392 return c - *fingerprint;
393 fingerprint++;
394 len--;
395 host_key_check += 2;
397 return *host_key_check - '\0';
400 static int
401 check_host_key_hash(BDRVSSHState *s, const char *hash,
402 int hash_type, size_t fingerprint_len, Error **errp)
404 const char *fingerprint;
406 fingerprint = libssh2_hostkey_hash(s->session, hash_type);
407 if (!fingerprint) {
408 session_error_setg(errp, s, "failed to read remote host key");
409 return -EINVAL;
412 if(compare_fingerprint((unsigned char *) fingerprint, fingerprint_len,
413 hash) != 0) {
414 error_setg(errp, "remote host key does not match host_key_check '%s'",
415 hash);
416 return -EPERM;
419 return 0;
422 static int check_host_key(BDRVSSHState *s, const char *host, int port,
423 SshHostKeyCheck *hkc, Error **errp)
425 SshHostKeyCheckMode mode;
427 if (hkc) {
428 mode = hkc->mode;
429 } else {
430 mode = SSH_HOST_KEY_CHECK_MODE_KNOWN_HOSTS;
433 switch (mode) {
434 case SSH_HOST_KEY_CHECK_MODE_NONE:
435 return 0;
436 case SSH_HOST_KEY_CHECK_MODE_HASH:
437 if (hkc->u.hash.type == SSH_HOST_KEY_CHECK_HASH_TYPE_MD5) {
438 return check_host_key_hash(s, hkc->u.hash.hash,
439 LIBSSH2_HOSTKEY_HASH_MD5, 16, errp);
440 } else if (hkc->u.hash.type == SSH_HOST_KEY_CHECK_HASH_TYPE_SHA1) {
441 return check_host_key_hash(s, hkc->u.hash.hash,
442 LIBSSH2_HOSTKEY_HASH_SHA1, 20, errp);
444 g_assert_not_reached();
445 break;
446 case SSH_HOST_KEY_CHECK_MODE_KNOWN_HOSTS:
447 return check_host_key_knownhosts(s, host, port, errp);
448 default:
449 g_assert_not_reached();
452 return -EINVAL;
455 static int authenticate(BDRVSSHState *s, const char *user, Error **errp)
457 int r, ret;
458 const char *userauthlist;
459 LIBSSH2_AGENT *agent = NULL;
460 struct libssh2_agent_publickey *identity;
461 struct libssh2_agent_publickey *prev_identity = NULL;
463 userauthlist = libssh2_userauth_list(s->session, user, strlen(user));
464 if (strstr(userauthlist, "publickey") == NULL) {
465 ret = -EPERM;
466 error_setg(errp,
467 "remote server does not support \"publickey\" authentication");
468 goto out;
471 /* Connect to ssh-agent and try each identity in turn. */
472 agent = libssh2_agent_init(s->session);
473 if (!agent) {
474 ret = -EINVAL;
475 session_error_setg(errp, s, "failed to initialize ssh-agent support");
476 goto out;
478 if (libssh2_agent_connect(agent)) {
479 ret = -ECONNREFUSED;
480 session_error_setg(errp, s, "failed to connect to ssh-agent");
481 goto out;
483 if (libssh2_agent_list_identities(agent)) {
484 ret = -EINVAL;
485 session_error_setg(errp, s,
486 "failed requesting identities from ssh-agent");
487 goto out;
490 for(;;) {
491 r = libssh2_agent_get_identity(agent, &identity, prev_identity);
492 if (r == 1) { /* end of list */
493 break;
495 if (r < 0) {
496 ret = -EINVAL;
497 session_error_setg(errp, s,
498 "failed to obtain identity from ssh-agent");
499 goto out;
501 r = libssh2_agent_userauth(agent, user, identity);
502 if (r == 0) {
503 /* Authenticated! */
504 ret = 0;
505 goto out;
507 /* Failed to authenticate with this identity, try the next one. */
508 prev_identity = identity;
511 ret = -EPERM;
512 error_setg(errp, "failed to authenticate using publickey authentication "
513 "and the identities held by your ssh-agent");
515 out:
516 if (agent != NULL) {
517 /* Note: libssh2 implementation implicitly calls
518 * libssh2_agent_disconnect if necessary.
520 libssh2_agent_free(agent);
523 return ret;
526 static QemuOptsList ssh_runtime_opts = {
527 .name = "ssh",
528 .head = QTAILQ_HEAD_INITIALIZER(ssh_runtime_opts.head),
529 .desc = {
531 .name = "host",
532 .type = QEMU_OPT_STRING,
533 .help = "Host to connect to",
536 .name = "port",
537 .type = QEMU_OPT_NUMBER,
538 .help = "Port to connect to",
541 .name = "host_key_check",
542 .type = QEMU_OPT_STRING,
543 .help = "Defines how and what to check the host key against",
545 { /* end of list */ }
549 static bool ssh_process_legacy_options(QDict *output_opts,
550 QemuOpts *legacy_opts,
551 Error **errp)
553 const char *host = qemu_opt_get(legacy_opts, "host");
554 const char *port = qemu_opt_get(legacy_opts, "port");
555 const char *host_key_check = qemu_opt_get(legacy_opts, "host_key_check");
557 if (!host && port) {
558 error_setg(errp, "port may not be used without host");
559 return false;
562 if (host) {
563 qdict_put_str(output_opts, "server.host", host);
564 qdict_put_str(output_opts, "server.port", port ?: stringify(22));
567 if (host_key_check) {
568 if (strcmp(host_key_check, "no") == 0) {
569 qdict_put_str(output_opts, "host-key-check.mode", "none");
570 } else if (strncmp(host_key_check, "md5:", 4) == 0) {
571 qdict_put_str(output_opts, "host-key-check.mode", "hash");
572 qdict_put_str(output_opts, "host-key-check.type", "md5");
573 qdict_put_str(output_opts, "host-key-check.hash",
574 &host_key_check[4]);
575 } else if (strncmp(host_key_check, "sha1:", 5) == 0) {
576 qdict_put_str(output_opts, "host-key-check.mode", "hash");
577 qdict_put_str(output_opts, "host-key-check.type", "sha1");
578 qdict_put_str(output_opts, "host-key-check.hash",
579 &host_key_check[5]);
580 } else if (strcmp(host_key_check, "yes") == 0) {
581 qdict_put_str(output_opts, "host-key-check.mode", "known_hosts");
582 } else {
583 error_setg(errp, "unknown host_key_check setting (%s)",
584 host_key_check);
585 return false;
589 return true;
592 static BlockdevOptionsSsh *ssh_parse_options(QDict *options, Error **errp)
594 BlockdevOptionsSsh *result = NULL;
595 QemuOpts *opts = NULL;
596 Error *local_err = NULL;
597 const QDictEntry *e;
598 Visitor *v;
600 /* Translate legacy options */
601 opts = qemu_opts_create(&ssh_runtime_opts, NULL, 0, &error_abort);
602 qemu_opts_absorb_qdict(opts, options, &local_err);
603 if (local_err) {
604 error_propagate(errp, local_err);
605 goto fail;
608 if (!ssh_process_legacy_options(options, opts, errp)) {
609 goto fail;
612 /* Create the QAPI object */
613 v = qobject_input_visitor_new_flat_confused(options, errp);
614 if (!v) {
615 goto fail;
618 visit_type_BlockdevOptionsSsh(v, NULL, &result, &local_err);
619 visit_free(v);
621 if (local_err) {
622 error_propagate(errp, local_err);
623 goto fail;
626 /* Remove the processed options from the QDict (the visitor processes
627 * _all_ options in the QDict) */
628 while ((e = qdict_first(options))) {
629 qdict_del(options, e->key);
632 fail:
633 qemu_opts_del(opts);
634 return result;
637 static int connect_to_ssh(BDRVSSHState *s, BlockdevOptionsSsh *opts,
638 int ssh_flags, int creat_mode, Error **errp)
640 int r, ret;
641 long port = 0;
643 if (opts->has_user) {
644 s->user = g_strdup(opts->user);
645 } else {
646 s->user = g_strdup(g_get_user_name());
647 if (!s->user) {
648 error_setg_errno(errp, errno, "Can't get user name");
649 ret = -errno;
650 goto err;
654 /* Pop the config into our state object, Exit if invalid */
655 s->inet = opts->server;
656 opts->server = NULL;
658 if (qemu_strtol(s->inet->port, NULL, 10, &port) < 0) {
659 error_setg(errp, "Use only numeric port value");
660 ret = -EINVAL;
661 goto err;
664 /* Open the socket and connect. */
665 s->sock = inet_connect_saddr(s->inet, errp);
666 if (s->sock < 0) {
667 ret = -EIO;
668 goto err;
671 /* Create SSH session. */
672 s->session = libssh2_session_init();
673 if (!s->session) {
674 ret = -EINVAL;
675 session_error_setg(errp, s, "failed to initialize libssh2 session");
676 goto err;
679 #if TRACE_LIBSSH2 != 0
680 libssh2_trace(s->session, TRACE_LIBSSH2);
681 #endif
683 r = libssh2_session_handshake(s->session, s->sock);
684 if (r != 0) {
685 ret = -EINVAL;
686 session_error_setg(errp, s, "failed to establish SSH session");
687 goto err;
690 /* Check the remote host's key against known_hosts. */
691 ret = check_host_key(s, s->inet->host, port, opts->host_key_check, errp);
692 if (ret < 0) {
693 goto err;
696 /* Authenticate. */
697 ret = authenticate(s, s->user, errp);
698 if (ret < 0) {
699 goto err;
702 /* Start SFTP. */
703 s->sftp = libssh2_sftp_init(s->session);
704 if (!s->sftp) {
705 session_error_setg(errp, s, "failed to initialize sftp handle");
706 ret = -EINVAL;
707 goto err;
710 /* Open the remote file. */
711 trace_ssh_connect_to_ssh(opts->path, ssh_flags, creat_mode);
712 s->sftp_handle = libssh2_sftp_open(s->sftp, opts->path, ssh_flags,
713 creat_mode);
714 if (!s->sftp_handle) {
715 session_error_setg(errp, s, "failed to open remote file '%s'",
716 opts->path);
717 ret = -EINVAL;
718 goto err;
721 r = libssh2_sftp_fstat(s->sftp_handle, &s->attrs);
722 if (r < 0) {
723 sftp_error_setg(errp, s, "failed to read file attributes");
724 return -EINVAL;
727 return 0;
729 err:
730 if (s->sftp_handle) {
731 libssh2_sftp_close(s->sftp_handle);
733 s->sftp_handle = NULL;
734 if (s->sftp) {
735 libssh2_sftp_shutdown(s->sftp);
737 s->sftp = NULL;
738 if (s->session) {
739 libssh2_session_disconnect(s->session,
740 "from qemu ssh client: "
741 "error opening connection");
742 libssh2_session_free(s->session);
744 s->session = NULL;
746 return ret;
749 static int ssh_file_open(BlockDriverState *bs, QDict *options, int bdrv_flags,
750 Error **errp)
752 BDRVSSHState *s = bs->opaque;
753 BlockdevOptionsSsh *opts;
754 int ret;
755 int ssh_flags;
757 ssh_state_init(s);
759 ssh_flags = LIBSSH2_FXF_READ;
760 if (bdrv_flags & BDRV_O_RDWR) {
761 ssh_flags |= LIBSSH2_FXF_WRITE;
764 opts = ssh_parse_options(options, errp);
765 if (opts == NULL) {
766 return -EINVAL;
769 /* Start up SSH. */
770 ret = connect_to_ssh(s, opts, ssh_flags, 0, errp);
771 if (ret < 0) {
772 goto err;
775 /* Go non-blocking. */
776 libssh2_session_set_blocking(s->session, 0);
778 qapi_free_BlockdevOptionsSsh(opts);
780 return 0;
782 err:
783 if (s->sock >= 0) {
784 close(s->sock);
786 s->sock = -1;
788 qapi_free_BlockdevOptionsSsh(opts);
790 return ret;
793 /* Note: This is a blocking operation */
794 static int ssh_grow_file(BDRVSSHState *s, int64_t offset, Error **errp)
796 ssize_t ret;
797 char c[1] = { '\0' };
798 int was_blocking = libssh2_session_get_blocking(s->session);
800 /* offset must be strictly greater than the current size so we do
801 * not overwrite anything */
802 assert(offset > 0 && offset > s->attrs.filesize);
804 libssh2_session_set_blocking(s->session, 1);
806 libssh2_sftp_seek64(s->sftp_handle, offset - 1);
807 ret = libssh2_sftp_write(s->sftp_handle, c, 1);
809 libssh2_session_set_blocking(s->session, was_blocking);
811 if (ret < 0) {
812 sftp_error_setg(errp, s, "Failed to grow file");
813 return -EIO;
816 s->attrs.filesize = offset;
817 return 0;
820 static QemuOptsList ssh_create_opts = {
821 .name = "ssh-create-opts",
822 .head = QTAILQ_HEAD_INITIALIZER(ssh_create_opts.head),
823 .desc = {
825 .name = BLOCK_OPT_SIZE,
826 .type = QEMU_OPT_SIZE,
827 .help = "Virtual disk size"
829 { /* end of list */ }
833 static int ssh_co_create(BlockdevCreateOptions *options, Error **errp)
835 BlockdevCreateOptionsSsh *opts = &options->u.ssh;
836 BDRVSSHState s;
837 int ret;
839 assert(options->driver == BLOCKDEV_DRIVER_SSH);
841 ssh_state_init(&s);
843 ret = connect_to_ssh(&s, opts->location,
844 LIBSSH2_FXF_READ|LIBSSH2_FXF_WRITE|
845 LIBSSH2_FXF_CREAT|LIBSSH2_FXF_TRUNC,
846 0644, errp);
847 if (ret < 0) {
848 goto fail;
851 if (opts->size > 0) {
852 ret = ssh_grow_file(&s, opts->size, errp);
853 if (ret < 0) {
854 goto fail;
858 ret = 0;
859 fail:
860 ssh_state_free(&s);
861 return ret;
864 static int coroutine_fn ssh_co_create_opts(const char *filename, QemuOpts *opts,
865 Error **errp)
867 BlockdevCreateOptions *create_options;
868 BlockdevCreateOptionsSsh *ssh_opts;
869 int ret;
870 QDict *uri_options = NULL;
872 create_options = g_new0(BlockdevCreateOptions, 1);
873 create_options->driver = BLOCKDEV_DRIVER_SSH;
874 ssh_opts = &create_options->u.ssh;
876 /* Get desired file size. */
877 ssh_opts->size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
878 BDRV_SECTOR_SIZE);
879 trace_ssh_co_create_opts(ssh_opts->size);
881 uri_options = qdict_new();
882 ret = parse_uri(filename, uri_options, errp);
883 if (ret < 0) {
884 goto out;
887 ssh_opts->location = ssh_parse_options(uri_options, errp);
888 if (ssh_opts->location == NULL) {
889 ret = -EINVAL;
890 goto out;
893 ret = ssh_co_create(create_options, errp);
895 out:
896 qobject_unref(uri_options);
897 qapi_free_BlockdevCreateOptions(create_options);
898 return ret;
901 static void ssh_close(BlockDriverState *bs)
903 BDRVSSHState *s = bs->opaque;
905 ssh_state_free(s);
908 static int ssh_has_zero_init(BlockDriverState *bs)
910 BDRVSSHState *s = bs->opaque;
911 /* Assume false, unless we can positively prove it's true. */
912 int has_zero_init = 0;
914 if (s->attrs.flags & LIBSSH2_SFTP_ATTR_PERMISSIONS) {
915 if (s->attrs.permissions & LIBSSH2_SFTP_S_IFREG) {
916 has_zero_init = 1;
920 return has_zero_init;
923 typedef struct BDRVSSHRestart {
924 BlockDriverState *bs;
925 Coroutine *co;
926 } BDRVSSHRestart;
928 static void restart_coroutine(void *opaque)
930 BDRVSSHRestart *restart = opaque;
931 BlockDriverState *bs = restart->bs;
932 BDRVSSHState *s = bs->opaque;
933 AioContext *ctx = bdrv_get_aio_context(bs);
935 trace_ssh_restart_coroutine(restart->co);
936 aio_set_fd_handler(ctx, s->sock, false, NULL, NULL, NULL, NULL);
938 aio_co_wake(restart->co);
941 /* A non-blocking call returned EAGAIN, so yield, ensuring the
942 * handlers are set up so that we'll be rescheduled when there is an
943 * interesting event on the socket.
945 static coroutine_fn void co_yield(BDRVSSHState *s, BlockDriverState *bs)
947 int r;
948 IOHandler *rd_handler = NULL, *wr_handler = NULL;
949 BDRVSSHRestart restart = {
950 .bs = bs,
951 .co = qemu_coroutine_self()
954 r = libssh2_session_block_directions(s->session);
956 if (r & LIBSSH2_SESSION_BLOCK_INBOUND) {
957 rd_handler = restart_coroutine;
959 if (r & LIBSSH2_SESSION_BLOCK_OUTBOUND) {
960 wr_handler = restart_coroutine;
963 trace_ssh_co_yield(s->sock, rd_handler, wr_handler);
965 aio_set_fd_handler(bdrv_get_aio_context(bs), s->sock,
966 false, rd_handler, wr_handler, NULL, &restart);
967 qemu_coroutine_yield();
968 trace_ssh_co_yield_back(s->sock);
971 /* SFTP has a function `libssh2_sftp_seek64' which seeks to a position
972 * in the remote file. Notice that it just updates a field in the
973 * sftp_handle structure, so there is no network traffic and it cannot
974 * fail.
976 * However, `libssh2_sftp_seek64' does have a catastrophic effect on
977 * performance since it causes the handle to throw away all in-flight
978 * reads and buffered readahead data. Therefore this function tries
979 * to be intelligent about when to call the underlying libssh2 function.
981 #define SSH_SEEK_WRITE 0
982 #define SSH_SEEK_READ 1
983 #define SSH_SEEK_FORCE 2
985 static void ssh_seek(BDRVSSHState *s, int64_t offset, int flags)
987 bool op_read = (flags & SSH_SEEK_READ) != 0;
988 bool force = (flags & SSH_SEEK_FORCE) != 0;
990 if (force || op_read != s->offset_op_read || offset != s->offset) {
991 trace_ssh_seek(offset);
992 libssh2_sftp_seek64(s->sftp_handle, offset);
993 s->offset = offset;
994 s->offset_op_read = op_read;
998 static coroutine_fn int ssh_read(BDRVSSHState *s, BlockDriverState *bs,
999 int64_t offset, size_t size,
1000 QEMUIOVector *qiov)
1002 ssize_t r;
1003 size_t got;
1004 char *buf, *end_of_vec;
1005 struct iovec *i;
1007 trace_ssh_read(offset, size);
1009 ssh_seek(s, offset, SSH_SEEK_READ);
1011 /* This keeps track of the current iovec element ('i'), where we
1012 * will write to next ('buf'), and the end of the current iovec
1013 * ('end_of_vec').
1015 i = &qiov->iov[0];
1016 buf = i->iov_base;
1017 end_of_vec = i->iov_base + i->iov_len;
1019 /* libssh2 has a hard-coded limit of 2000 bytes per request,
1020 * although it will also do readahead behind our backs. Therefore
1021 * we may have to do repeated reads here until we have read 'size'
1022 * bytes.
1024 for (got = 0; got < size; ) {
1025 again:
1026 trace_ssh_read_buf(buf, end_of_vec - buf);
1027 r = libssh2_sftp_read(s->sftp_handle, buf, end_of_vec - buf);
1028 trace_ssh_read_return(r);
1030 if (r == LIBSSH2_ERROR_EAGAIN || r == LIBSSH2_ERROR_TIMEOUT) {
1031 co_yield(s, bs);
1032 goto again;
1034 if (r < 0) {
1035 sftp_error_trace(s, "read");
1036 s->offset = -1;
1037 return -EIO;
1039 if (r == 0) {
1040 /* EOF: Short read so pad the buffer with zeroes and return it. */
1041 qemu_iovec_memset(qiov, got, 0, size - got);
1042 return 0;
1045 got += r;
1046 buf += r;
1047 s->offset += r;
1048 if (buf >= end_of_vec && got < size) {
1049 i++;
1050 buf = i->iov_base;
1051 end_of_vec = i->iov_base + i->iov_len;
1055 return 0;
1058 static coroutine_fn int ssh_co_readv(BlockDriverState *bs,
1059 int64_t sector_num,
1060 int nb_sectors, QEMUIOVector *qiov)
1062 BDRVSSHState *s = bs->opaque;
1063 int ret;
1065 qemu_co_mutex_lock(&s->lock);
1066 ret = ssh_read(s, bs, sector_num * BDRV_SECTOR_SIZE,
1067 nb_sectors * BDRV_SECTOR_SIZE, qiov);
1068 qemu_co_mutex_unlock(&s->lock);
1070 return ret;
1073 static int ssh_write(BDRVSSHState *s, BlockDriverState *bs,
1074 int64_t offset, size_t size,
1075 QEMUIOVector *qiov)
1077 ssize_t r;
1078 size_t written;
1079 char *buf, *end_of_vec;
1080 struct iovec *i;
1082 trace_ssh_write(offset, size);
1084 ssh_seek(s, offset, SSH_SEEK_WRITE);
1086 /* This keeps track of the current iovec element ('i'), where we
1087 * will read from next ('buf'), and the end of the current iovec
1088 * ('end_of_vec').
1090 i = &qiov->iov[0];
1091 buf = i->iov_base;
1092 end_of_vec = i->iov_base + i->iov_len;
1094 for (written = 0; written < size; ) {
1095 again:
1096 trace_ssh_write_buf(buf, end_of_vec - buf);
1097 r = libssh2_sftp_write(s->sftp_handle, buf, end_of_vec - buf);
1098 trace_ssh_write_return(r);
1100 if (r == LIBSSH2_ERROR_EAGAIN || r == LIBSSH2_ERROR_TIMEOUT) {
1101 co_yield(s, bs);
1102 goto again;
1104 if (r < 0) {
1105 sftp_error_trace(s, "write");
1106 s->offset = -1;
1107 return -EIO;
1109 /* The libssh2 API is very unclear about this. A comment in
1110 * the code says "nothing was acked, and no EAGAIN was
1111 * received!" which apparently means that no data got sent
1112 * out, and the underlying channel didn't return any EAGAIN
1113 * indication. I think this is a bug in either libssh2 or
1114 * OpenSSH (server-side). In any case, forcing a seek (to
1115 * discard libssh2 internal buffers), and then trying again
1116 * works for me.
1118 if (r == 0) {
1119 ssh_seek(s, offset + written, SSH_SEEK_WRITE|SSH_SEEK_FORCE);
1120 co_yield(s, bs);
1121 goto again;
1124 written += r;
1125 buf += r;
1126 s->offset += r;
1127 if (buf >= end_of_vec && written < size) {
1128 i++;
1129 buf = i->iov_base;
1130 end_of_vec = i->iov_base + i->iov_len;
1133 if (offset + written > s->attrs.filesize)
1134 s->attrs.filesize = offset + written;
1137 return 0;
1140 static coroutine_fn int ssh_co_writev(BlockDriverState *bs,
1141 int64_t sector_num,
1142 int nb_sectors, QEMUIOVector *qiov,
1143 int flags)
1145 BDRVSSHState *s = bs->opaque;
1146 int ret;
1148 assert(!flags);
1149 qemu_co_mutex_lock(&s->lock);
1150 ret = ssh_write(s, bs, sector_num * BDRV_SECTOR_SIZE,
1151 nb_sectors * BDRV_SECTOR_SIZE, qiov);
1152 qemu_co_mutex_unlock(&s->lock);
1154 return ret;
1157 static void unsafe_flush_warning(BDRVSSHState *s, const char *what)
1159 if (!s->unsafe_flush_warning) {
1160 warn_report("ssh server %s does not support fsync",
1161 s->inet->host);
1162 if (what) {
1163 error_report("to support fsync, you need %s", what);
1165 s->unsafe_flush_warning = true;
1169 #ifdef HAS_LIBSSH2_SFTP_FSYNC
1171 static coroutine_fn int ssh_flush(BDRVSSHState *s, BlockDriverState *bs)
1173 int r;
1175 trace_ssh_flush();
1176 again:
1177 r = libssh2_sftp_fsync(s->sftp_handle);
1178 if (r == LIBSSH2_ERROR_EAGAIN || r == LIBSSH2_ERROR_TIMEOUT) {
1179 co_yield(s, bs);
1180 goto again;
1182 if (r == LIBSSH2_ERROR_SFTP_PROTOCOL &&
1183 libssh2_sftp_last_error(s->sftp) == LIBSSH2_FX_OP_UNSUPPORTED) {
1184 unsafe_flush_warning(s, "OpenSSH >= 6.3");
1185 return 0;
1187 if (r < 0) {
1188 sftp_error_trace(s, "fsync");
1189 return -EIO;
1192 return 0;
1195 static coroutine_fn int ssh_co_flush(BlockDriverState *bs)
1197 BDRVSSHState *s = bs->opaque;
1198 int ret;
1200 qemu_co_mutex_lock(&s->lock);
1201 ret = ssh_flush(s, bs);
1202 qemu_co_mutex_unlock(&s->lock);
1204 return ret;
1207 #else /* !HAS_LIBSSH2_SFTP_FSYNC */
1209 static coroutine_fn int ssh_co_flush(BlockDriverState *bs)
1211 BDRVSSHState *s = bs->opaque;
1213 unsafe_flush_warning(s, "libssh2 >= 1.4.4");
1214 return 0;
1217 #endif /* !HAS_LIBSSH2_SFTP_FSYNC */
1219 static int64_t ssh_getlength(BlockDriverState *bs)
1221 BDRVSSHState *s = bs->opaque;
1222 int64_t length;
1224 /* Note we cannot make a libssh2 call here. */
1225 length = (int64_t) s->attrs.filesize;
1226 trace_ssh_getlength(length);
1228 return length;
1231 static int coroutine_fn ssh_co_truncate(BlockDriverState *bs, int64_t offset,
1232 PreallocMode prealloc, Error **errp)
1234 BDRVSSHState *s = bs->opaque;
1236 if (prealloc != PREALLOC_MODE_OFF) {
1237 error_setg(errp, "Unsupported preallocation mode '%s'",
1238 PreallocMode_str(prealloc));
1239 return -ENOTSUP;
1242 if (offset < s->attrs.filesize) {
1243 error_setg(errp, "ssh driver does not support shrinking files");
1244 return -ENOTSUP;
1247 if (offset == s->attrs.filesize) {
1248 return 0;
1251 return ssh_grow_file(s, offset, errp);
1254 static void ssh_refresh_filename(BlockDriverState *bs)
1256 BDRVSSHState *s = bs->opaque;
1257 const char *path, *host_key_check;
1258 int ret;
1261 * None of these options can be represented in a plain "host:port"
1262 * format, so if any was given, we have to abort.
1264 if (s->inet->has_ipv4 || s->inet->has_ipv6 || s->inet->has_to ||
1265 s->inet->has_numeric)
1267 return;
1270 path = qdict_get_try_str(bs->full_open_options, "path");
1271 assert(path); /* mandatory option */
1273 host_key_check = qdict_get_try_str(bs->full_open_options, "host_key_check");
1275 ret = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
1276 "ssh://%s@%s:%s%s%s%s",
1277 s->user, s->inet->host, s->inet->port, path,
1278 host_key_check ? "?host_key_check=" : "",
1279 host_key_check ?: "");
1280 if (ret >= sizeof(bs->exact_filename)) {
1281 /* An overflow makes the filename unusable, so do not report any */
1282 bs->exact_filename[0] = '\0';
1286 static char *ssh_bdrv_dirname(BlockDriverState *bs, Error **errp)
1288 if (qdict_haskey(bs->full_open_options, "host_key_check")) {
1290 * We cannot generate a simple prefix if we would have to
1291 * append a query string.
1293 error_setg(errp,
1294 "Cannot generate a base directory with host_key_check set");
1295 return NULL;
1298 if (bs->exact_filename[0] == '\0') {
1299 error_setg(errp, "Cannot generate a base directory for this ssh node");
1300 return NULL;
1303 return path_combine(bs->exact_filename, "");
1306 static const char *const ssh_strong_runtime_opts[] = {
1307 "host",
1308 "port",
1309 "path",
1310 "user",
1311 "host_key_check",
1312 "server.",
1314 NULL
1317 static BlockDriver bdrv_ssh = {
1318 .format_name = "ssh",
1319 .protocol_name = "ssh",
1320 .instance_size = sizeof(BDRVSSHState),
1321 .bdrv_parse_filename = ssh_parse_filename,
1322 .bdrv_file_open = ssh_file_open,
1323 .bdrv_co_create = ssh_co_create,
1324 .bdrv_co_create_opts = ssh_co_create_opts,
1325 .bdrv_close = ssh_close,
1326 .bdrv_has_zero_init = ssh_has_zero_init,
1327 .bdrv_co_readv = ssh_co_readv,
1328 .bdrv_co_writev = ssh_co_writev,
1329 .bdrv_getlength = ssh_getlength,
1330 .bdrv_co_truncate = ssh_co_truncate,
1331 .bdrv_co_flush_to_disk = ssh_co_flush,
1332 .bdrv_refresh_filename = ssh_refresh_filename,
1333 .bdrv_dirname = ssh_bdrv_dirname,
1334 .create_opts = &ssh_create_opts,
1335 .strong_runtime_opts = ssh_strong_runtime_opts,
1338 static void bdrv_ssh_init(void)
1340 int r;
1342 r = libssh2_init(0);
1343 if (r != 0) {
1344 fprintf(stderr, "libssh2 initialization failed, %d\n", r);
1345 exit(EXIT_FAILURE);
1348 bdrv_register(&bdrv_ssh);
1351 block_init(bdrv_ssh_init);