usb: drop usb_host_dev_is_scsi_storage hook
[qemu/kevin.git] / block / ssh.c
blobd008caf059995ab5887c1dc9bfa25789fd886212
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 <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"
39 #include "qemu/uri.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"
46 #include "trace.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 {
56 /* Coroutine. */
57 CoMutex lock;
59 /* SSH connection. */
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
80 * are actually using.
82 char *user;
83 } BDRVSSHState;
85 static void ssh_state_init(BDRVSSHState *s)
87 memset(s, 0, sizeof *s);
88 s->sock = -1;
89 qemu_co_mutex_init(&s->lock);
92 static void ssh_state_free(BDRVSSHState *s)
94 g_free(s->user);
96 if (s->attrs) {
97 sftp_attributes_free(s->attrs);
99 if (s->sftp_handle) {
100 sftp_close(s->sftp_handle);
102 if (s->sftp) {
103 sftp_free(s->sftp);
105 if (s->session) {
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, ...)
114 va_list args;
115 char *msg;
117 va_start(args, fs);
118 msg = g_strdup_vprintf(fs, args);
119 va_end(args);
121 if (s->session) {
122 const char *ssh_err;
123 int ssh_err_code;
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);
130 } else {
131 error_setg(errp, "%s", msg);
133 g_free(msg);
136 static void GCC_FMT_ATTR(3, 4)
137 sftp_error_setg(Error **errp, BDRVSSHState *s, const char *fs, ...)
139 va_list args;
140 char *msg;
142 va_start(args, fs);
143 msg = g_strdup_vprintf(fs, args);
144 va_end(args);
146 if (s->sftp) {
147 const char *ssh_err;
148 int ssh_err_code;
149 int sftp_err_code;
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);
157 error_setg(errp,
158 "%s: %s (libssh error code: %d, sftp error code: %d)",
159 msg, ssh_err, ssh_err_code, sftp_err_code);
160 } else {
161 error_setg(errp, "%s", msg);
163 g_free(msg);
166 static void sftp_error_trace(BDRVSSHState *s, const char *op)
168 const char *ssh_err;
169 int ssh_err_code;
170 int sftp_err_code;
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 URI *uri = NULL;
184 QueryParams *qp;
185 char *port_str;
186 int i;
188 uri = uri_parse(filename);
189 if (!uri) {
190 return -EINVAL;
193 if (g_strcmp0(uri->scheme, "ssh") != 0) {
194 error_setg(errp, "URI scheme must be 'ssh'");
195 goto err;
198 if (!uri->server || strcmp(uri->server, "") == 0) {
199 error_setg(errp, "missing hostname in URI");
200 goto err;
203 if (!uri->path || strcmp(uri->path, "") == 0) {
204 error_setg(errp, "missing remote path in URI");
205 goto err;
208 qp = query_params_parse(uri->query);
209 if (!qp) {
210 error_setg(errp, "could not parse query parameters");
211 goto err;
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);
222 g_free(port_str);
224 qdict_put_str(options, "path", uri->path);
226 /* Pick out any query parameters that we understand, and ignore
227 * the rest.
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);
236 uri_free(uri);
237 return 0;
239 err:
240 if (uri) {
241 uri_free(uri);
243 return -EINVAL;
246 static bool ssh_has_filename_options_conflict(QDict *options, Error **errp)
248 const QDictEntry *qe;
250 for (qe = qdict_first(options); qe; qe = qdict_next(options, qe)) {
251 if (!strcmp(qe->key, "host") ||
252 !strcmp(qe->key, "port") ||
253 !strcmp(qe->key, "path") ||
254 !strcmp(qe->key, "user") ||
255 !strcmp(qe->key, "host_key_check") ||
256 strstart(qe->key, "server.", NULL))
258 error_setg(errp, "Option '%s' cannot be used with a file name",
259 qe->key);
260 return true;
264 return false;
267 static void ssh_parse_filename(const char *filename, QDict *options,
268 Error **errp)
270 if (ssh_has_filename_options_conflict(options, errp)) {
271 return;
274 parse_uri(filename, options, errp);
277 static int check_host_key_knownhosts(BDRVSSHState *s, Error **errp)
279 int ret;
280 enum ssh_known_hosts_e state;
281 int r;
282 ssh_key pubkey;
283 enum ssh_keytypes_e pubkey_type;
284 unsigned char *server_hash = NULL;
285 size_t server_hash_len;
286 char *fingerprint = NULL;
288 state = ssh_session_is_known_server(s->session);
289 trace_ssh_server_status(state);
291 switch (state) {
292 case SSH_KNOWN_HOSTS_OK:
293 /* OK */
294 trace_ssh_check_host_key_knownhosts();
295 break;
296 case SSH_KNOWN_HOSTS_CHANGED:
297 ret = -EINVAL;
298 r = ssh_get_server_publickey(s->session, &pubkey);
299 if (r == 0) {
300 r = ssh_get_publickey_hash(pubkey, SSH_PUBLICKEY_HASH_SHA256,
301 &server_hash, &server_hash_len);
302 pubkey_type = ssh_key_type(pubkey);
303 ssh_key_free(pubkey);
305 if (r == 0) {
306 fingerprint = ssh_get_fingerprint_hash(SSH_PUBLICKEY_HASH_SHA256,
307 server_hash,
308 server_hash_len);
309 ssh_clean_pubkey_hash(&server_hash);
311 if (fingerprint) {
312 error_setg(errp,
313 "host key (%s key with fingerprint %s) does not match "
314 "the one in known_hosts; this may be a possible attack",
315 ssh_key_type_to_char(pubkey_type), fingerprint);
316 ssh_string_free_char(fingerprint);
317 } else {
318 error_setg(errp,
319 "host key does not match the one in known_hosts; this "
320 "may be a possible attack");
322 goto out;
323 case SSH_KNOWN_HOSTS_OTHER:
324 ret = -EINVAL;
325 error_setg(errp,
326 "host key for this server not found, another type exists");
327 goto out;
328 case SSH_KNOWN_HOSTS_UNKNOWN:
329 ret = -EINVAL;
330 error_setg(errp, "no host key was found in known_hosts");
331 goto out;
332 case SSH_KNOWN_HOSTS_NOT_FOUND:
333 ret = -ENOENT;
334 error_setg(errp, "known_hosts file not found");
335 goto out;
336 case SSH_KNOWN_HOSTS_ERROR:
337 ret = -EINVAL;
338 error_setg(errp, "error while checking the host");
339 goto out;
340 default:
341 ret = -EINVAL;
342 error_setg(errp, "error while checking for known server (%d)", state);
343 goto out;
346 /* known_hosts checking successful. */
347 ret = 0;
349 out:
350 return ret;
353 static unsigned hex2decimal(char ch)
355 if (ch >= '0' && ch <= '9') {
356 return (ch - '0');
357 } else if (ch >= 'a' && ch <= 'f') {
358 return 10 + (ch - 'a');
359 } else if (ch >= 'A' && ch <= 'F') {
360 return 10 + (ch - 'A');
363 return -1;
366 /* Compare the binary fingerprint (hash of host key) with the
367 * host_key_check parameter.
369 static int compare_fingerprint(const unsigned char *fingerprint, size_t len,
370 const char *host_key_check)
372 unsigned c;
374 while (len > 0) {
375 while (*host_key_check == ':')
376 host_key_check++;
377 if (!qemu_isxdigit(host_key_check[0]) ||
378 !qemu_isxdigit(host_key_check[1]))
379 return 1;
380 c = hex2decimal(host_key_check[0]) * 16 +
381 hex2decimal(host_key_check[1]);
382 if (c - *fingerprint != 0)
383 return c - *fingerprint;
384 fingerprint++;
385 len--;
386 host_key_check += 2;
388 return *host_key_check - '\0';
391 static int
392 check_host_key_hash(BDRVSSHState *s, const char *hash,
393 enum ssh_publickey_hash_type type, Error **errp)
395 int r;
396 ssh_key pubkey;
397 unsigned char *server_hash;
398 size_t server_hash_len;
400 r = ssh_get_server_publickey(s->session, &pubkey);
401 if (r != SSH_OK) {
402 session_error_setg(errp, s, "failed to read remote host key");
403 return -EINVAL;
406 r = ssh_get_publickey_hash(pubkey, type, &server_hash, &server_hash_len);
407 ssh_key_free(pubkey);
408 if (r != 0) {
409 session_error_setg(errp, s,
410 "failed reading the hash of the server SSH key");
411 return -EINVAL;
414 r = compare_fingerprint(server_hash, server_hash_len, hash);
415 ssh_clean_pubkey_hash(&server_hash);
416 if (r != 0) {
417 error_setg(errp, "remote host key does not match host_key_check '%s'",
418 hash);
419 return -EPERM;
422 return 0;
425 static int check_host_key(BDRVSSHState *s, SshHostKeyCheck *hkc, Error **errp)
427 SshHostKeyCheckMode mode;
429 if (hkc) {
430 mode = hkc->mode;
431 } else {
432 mode = SSH_HOST_KEY_CHECK_MODE_KNOWN_HOSTS;
435 switch (mode) {
436 case SSH_HOST_KEY_CHECK_MODE_NONE:
437 return 0;
438 case SSH_HOST_KEY_CHECK_MODE_HASH:
439 if (hkc->u.hash.type == SSH_HOST_KEY_CHECK_HASH_TYPE_MD5) {
440 return check_host_key_hash(s, hkc->u.hash.hash,
441 SSH_PUBLICKEY_HASH_MD5, errp);
442 } else if (hkc->u.hash.type == SSH_HOST_KEY_CHECK_HASH_TYPE_SHA1) {
443 return check_host_key_hash(s, hkc->u.hash.hash,
444 SSH_PUBLICKEY_HASH_SHA1, errp);
445 } else if (hkc->u.hash.type == SSH_HOST_KEY_CHECK_HASH_TYPE_SHA256) {
446 return check_host_key_hash(s, hkc->u.hash.hash,
447 SSH_PUBLICKEY_HASH_SHA256, errp);
449 g_assert_not_reached();
450 break;
451 case SSH_HOST_KEY_CHECK_MODE_KNOWN_HOSTS:
452 return check_host_key_knownhosts(s, errp);
453 default:
454 g_assert_not_reached();
457 return -EINVAL;
460 static int authenticate(BDRVSSHState *s, Error **errp)
462 int r, ret;
463 int method;
465 /* Try to authenticate with the "none" method. */
466 r = ssh_userauth_none(s->session, NULL);
467 if (r == SSH_AUTH_ERROR) {
468 ret = -EPERM;
469 session_error_setg(errp, s, "failed to authenticate using none "
470 "authentication");
471 goto out;
472 } else if (r == SSH_AUTH_SUCCESS) {
473 /* Authenticated! */
474 ret = 0;
475 goto out;
478 method = ssh_userauth_list(s->session, NULL);
479 trace_ssh_auth_methods(method);
482 * Try to authenticate with publickey, using the ssh-agent
483 * if available.
485 if (method & SSH_AUTH_METHOD_PUBLICKEY) {
486 r = ssh_userauth_publickey_auto(s->session, NULL, NULL);
487 if (r == SSH_AUTH_ERROR) {
488 ret = -EINVAL;
489 session_error_setg(errp, s, "failed to authenticate using "
490 "publickey authentication");
491 goto out;
492 } else if (r == SSH_AUTH_SUCCESS) {
493 /* Authenticated! */
494 ret = 0;
495 goto out;
499 ret = -EPERM;
500 error_setg(errp, "failed to authenticate using publickey authentication "
501 "and the identities held by your ssh-agent");
503 out:
504 return ret;
507 static QemuOptsList ssh_runtime_opts = {
508 .name = "ssh",
509 .head = QTAILQ_HEAD_INITIALIZER(ssh_runtime_opts.head),
510 .desc = {
512 .name = "host",
513 .type = QEMU_OPT_STRING,
514 .help = "Host to connect to",
517 .name = "port",
518 .type = QEMU_OPT_NUMBER,
519 .help = "Port to connect to",
522 .name = "host_key_check",
523 .type = QEMU_OPT_STRING,
524 .help = "Defines how and what to check the host key against",
526 { /* end of list */ }
530 static bool ssh_process_legacy_options(QDict *output_opts,
531 QemuOpts *legacy_opts,
532 Error **errp)
534 const char *host = qemu_opt_get(legacy_opts, "host");
535 const char *port = qemu_opt_get(legacy_opts, "port");
536 const char *host_key_check = qemu_opt_get(legacy_opts, "host_key_check");
538 if (!host && port) {
539 error_setg(errp, "port may not be used without host");
540 return false;
543 if (host) {
544 qdict_put_str(output_opts, "server.host", host);
545 qdict_put_str(output_opts, "server.port", port ?: stringify(22));
548 if (host_key_check) {
549 if (strcmp(host_key_check, "no") == 0) {
550 qdict_put_str(output_opts, "host-key-check.mode", "none");
551 } else if (strncmp(host_key_check, "md5:", 4) == 0) {
552 qdict_put_str(output_opts, "host-key-check.mode", "hash");
553 qdict_put_str(output_opts, "host-key-check.type", "md5");
554 qdict_put_str(output_opts, "host-key-check.hash",
555 &host_key_check[4]);
556 } else if (strncmp(host_key_check, "sha1:", 5) == 0) {
557 qdict_put_str(output_opts, "host-key-check.mode", "hash");
558 qdict_put_str(output_opts, "host-key-check.type", "sha1");
559 qdict_put_str(output_opts, "host-key-check.hash",
560 &host_key_check[5]);
561 } else if (strcmp(host_key_check, "yes") == 0) {
562 qdict_put_str(output_opts, "host-key-check.mode", "known_hosts");
563 } else {
564 error_setg(errp, "unknown host_key_check setting (%s)",
565 host_key_check);
566 return false;
570 return true;
573 static BlockdevOptionsSsh *ssh_parse_options(QDict *options, Error **errp)
575 BlockdevOptionsSsh *result = NULL;
576 QemuOpts *opts = NULL;
577 const QDictEntry *e;
578 Visitor *v;
580 /* Translate legacy options */
581 opts = qemu_opts_create(&ssh_runtime_opts, NULL, 0, &error_abort);
582 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
583 goto fail;
586 if (!ssh_process_legacy_options(options, opts, errp)) {
587 goto fail;
590 /* Create the QAPI object */
591 v = qobject_input_visitor_new_flat_confused(options, errp);
592 if (!v) {
593 goto fail;
596 visit_type_BlockdevOptionsSsh(v, NULL, &result, errp);
597 visit_free(v);
598 if (!result) {
599 goto fail;
602 /* Remove the processed options from the QDict (the visitor processes
603 * _all_ options in the QDict) */
604 while ((e = qdict_first(options))) {
605 qdict_del(options, e->key);
608 fail:
609 qemu_opts_del(opts);
610 return result;
613 static int connect_to_ssh(BDRVSSHState *s, BlockdevOptionsSsh *opts,
614 int ssh_flags, int creat_mode, Error **errp)
616 int r, ret;
617 unsigned int port = 0;
618 int new_sock = -1;
620 if (opts->has_user) {
621 s->user = g_strdup(opts->user);
622 } else {
623 s->user = g_strdup(g_get_user_name());
624 if (!s->user) {
625 error_setg_errno(errp, errno, "Can't get user name");
626 ret = -errno;
627 goto err;
631 /* Pop the config into our state object, Exit if invalid */
632 s->inet = opts->server;
633 opts->server = NULL;
635 if (qemu_strtoui(s->inet->port, NULL, 10, &port) < 0) {
636 error_setg(errp, "Use only numeric port value");
637 ret = -EINVAL;
638 goto err;
641 /* Open the socket and connect. */
642 new_sock = inet_connect_saddr(s->inet, errp);
643 if (new_sock < 0) {
644 ret = -EIO;
645 goto err;
649 * Try to disable the Nagle algorithm on TCP sockets to reduce latency,
650 * but do not fail if it cannot be disabled.
652 r = socket_set_nodelay(new_sock);
653 if (r < 0) {
654 warn_report("can't set TCP_NODELAY for the ssh server %s: %s",
655 s->inet->host, strerror(errno));
658 /* Create SSH session. */
659 s->session = ssh_new();
660 if (!s->session) {
661 ret = -EINVAL;
662 session_error_setg(errp, s, "failed to initialize libssh session");
663 goto err;
667 * Make sure we are in blocking mode during the connection and
668 * authentication phases.
670 ssh_set_blocking(s->session, 1);
672 r = ssh_options_set(s->session, SSH_OPTIONS_USER, s->user);
673 if (r < 0) {
674 ret = -EINVAL;
675 session_error_setg(errp, s,
676 "failed to set the user in the libssh session");
677 goto err;
680 r = ssh_options_set(s->session, SSH_OPTIONS_HOST, s->inet->host);
681 if (r < 0) {
682 ret = -EINVAL;
683 session_error_setg(errp, s,
684 "failed to set the host in the libssh session");
685 goto err;
688 if (port > 0) {
689 r = ssh_options_set(s->session, SSH_OPTIONS_PORT, &port);
690 if (r < 0) {
691 ret = -EINVAL;
692 session_error_setg(errp, s,
693 "failed to set the port in the libssh session");
694 goto err;
698 r = ssh_options_set(s->session, SSH_OPTIONS_COMPRESSION, "none");
699 if (r < 0) {
700 ret = -EINVAL;
701 session_error_setg(errp, s,
702 "failed to disable the compression in the libssh "
703 "session");
704 goto err;
707 /* Read ~/.ssh/config. */
708 r = ssh_options_parse_config(s->session, NULL);
709 if (r < 0) {
710 ret = -EINVAL;
711 session_error_setg(errp, s, "failed to parse ~/.ssh/config");
712 goto err;
715 r = ssh_options_set(s->session, SSH_OPTIONS_FD, &new_sock);
716 if (r < 0) {
717 ret = -EINVAL;
718 session_error_setg(errp, s,
719 "failed to set the socket in the libssh session");
720 goto err;
722 /* libssh took ownership of the socket. */
723 s->sock = new_sock;
724 new_sock = -1;
726 /* Connect. */
727 r = ssh_connect(s->session);
728 if (r != SSH_OK) {
729 ret = -EINVAL;
730 session_error_setg(errp, s, "failed to establish SSH session");
731 goto err;
734 /* Check the remote host's key against known_hosts. */
735 ret = check_host_key(s, opts->host_key_check, errp);
736 if (ret < 0) {
737 goto err;
740 /* Authenticate. */
741 ret = authenticate(s, errp);
742 if (ret < 0) {
743 goto err;
746 /* Start SFTP. */
747 s->sftp = sftp_new(s->session);
748 if (!s->sftp) {
749 session_error_setg(errp, s, "failed to create sftp handle");
750 ret = -EINVAL;
751 goto err;
754 r = sftp_init(s->sftp);
755 if (r < 0) {
756 sftp_error_setg(errp, s, "failed to initialize sftp handle");
757 ret = -EINVAL;
758 goto err;
761 /* Open the remote file. */
762 trace_ssh_connect_to_ssh(opts->path, ssh_flags, creat_mode);
763 s->sftp_handle = sftp_open(s->sftp, opts->path, ssh_flags, creat_mode);
764 if (!s->sftp_handle) {
765 sftp_error_setg(errp, s, "failed to open remote file '%s'",
766 opts->path);
767 ret = -EINVAL;
768 goto err;
771 /* Make sure the SFTP file is handled in blocking mode. */
772 sftp_file_set_blocking(s->sftp_handle);
774 s->attrs = sftp_fstat(s->sftp_handle);
775 if (!s->attrs) {
776 sftp_error_setg(errp, s, "failed to read file attributes");
777 return -EINVAL;
780 return 0;
782 err:
783 if (s->attrs) {
784 sftp_attributes_free(s->attrs);
786 s->attrs = NULL;
787 if (s->sftp_handle) {
788 sftp_close(s->sftp_handle);
790 s->sftp_handle = NULL;
791 if (s->sftp) {
792 sftp_free(s->sftp);
794 s->sftp = NULL;
795 if (s->session) {
796 ssh_disconnect(s->session);
797 ssh_free(s->session);
799 s->session = NULL;
800 s->sock = -1;
801 if (new_sock >= 0) {
802 close(new_sock);
805 return ret;
808 static int ssh_file_open(BlockDriverState *bs, QDict *options, int bdrv_flags,
809 Error **errp)
811 BDRVSSHState *s = bs->opaque;
812 BlockdevOptionsSsh *opts;
813 int ret;
814 int ssh_flags;
816 ssh_state_init(s);
818 ssh_flags = 0;
819 if (bdrv_flags & BDRV_O_RDWR) {
820 ssh_flags |= O_RDWR;
821 } else {
822 ssh_flags |= O_RDONLY;
825 opts = ssh_parse_options(options, errp);
826 if (opts == NULL) {
827 return -EINVAL;
830 /* Start up SSH. */
831 ret = connect_to_ssh(s, opts, ssh_flags, 0, errp);
832 if (ret < 0) {
833 goto err;
836 /* Go non-blocking. */
837 ssh_set_blocking(s->session, 0);
839 if (s->attrs->type == SSH_FILEXFER_TYPE_REGULAR) {
840 bs->supported_truncate_flags = BDRV_REQ_ZERO_WRITE;
843 qapi_free_BlockdevOptionsSsh(opts);
845 return 0;
847 err:
848 qapi_free_BlockdevOptionsSsh(opts);
850 return ret;
853 /* Note: This is a blocking operation */
854 static int ssh_grow_file(BDRVSSHState *s, int64_t offset, Error **errp)
856 ssize_t ret;
857 char c[1] = { '\0' };
858 int was_blocking = ssh_is_blocking(s->session);
860 /* offset must be strictly greater than the current size so we do
861 * not overwrite anything */
862 assert(offset > 0 && offset > s->attrs->size);
864 ssh_set_blocking(s->session, 1);
866 sftp_seek64(s->sftp_handle, offset - 1);
867 ret = sftp_write(s->sftp_handle, c, 1);
869 ssh_set_blocking(s->session, was_blocking);
871 if (ret < 0) {
872 sftp_error_setg(errp, s, "Failed to grow file");
873 return -EIO;
876 s->attrs->size = offset;
877 return 0;
880 static QemuOptsList ssh_create_opts = {
881 .name = "ssh-create-opts",
882 .head = QTAILQ_HEAD_INITIALIZER(ssh_create_opts.head),
883 .desc = {
885 .name = BLOCK_OPT_SIZE,
886 .type = QEMU_OPT_SIZE,
887 .help = "Virtual disk size"
889 { /* end of list */ }
893 static int ssh_co_create(BlockdevCreateOptions *options, Error **errp)
895 BlockdevCreateOptionsSsh *opts = &options->u.ssh;
896 BDRVSSHState s;
897 int ret;
899 assert(options->driver == BLOCKDEV_DRIVER_SSH);
901 ssh_state_init(&s);
903 ret = connect_to_ssh(&s, opts->location,
904 O_RDWR | O_CREAT | O_TRUNC,
905 0644, errp);
906 if (ret < 0) {
907 goto fail;
910 if (opts->size > 0) {
911 ret = ssh_grow_file(&s, opts->size, errp);
912 if (ret < 0) {
913 goto fail;
917 ret = 0;
918 fail:
919 ssh_state_free(&s);
920 return ret;
923 static int coroutine_fn ssh_co_create_opts(BlockDriver *drv,
924 const char *filename,
925 QemuOpts *opts,
926 Error **errp)
928 BlockdevCreateOptions *create_options;
929 BlockdevCreateOptionsSsh *ssh_opts;
930 int ret;
931 QDict *uri_options = NULL;
933 create_options = g_new0(BlockdevCreateOptions, 1);
934 create_options->driver = BLOCKDEV_DRIVER_SSH;
935 ssh_opts = &create_options->u.ssh;
937 /* Get desired file size. */
938 ssh_opts->size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
939 BDRV_SECTOR_SIZE);
940 trace_ssh_co_create_opts(ssh_opts->size);
942 uri_options = qdict_new();
943 ret = parse_uri(filename, uri_options, errp);
944 if (ret < 0) {
945 goto out;
948 ssh_opts->location = ssh_parse_options(uri_options, errp);
949 if (ssh_opts->location == NULL) {
950 ret = -EINVAL;
951 goto out;
954 ret = ssh_co_create(create_options, errp);
956 out:
957 qobject_unref(uri_options);
958 qapi_free_BlockdevCreateOptions(create_options);
959 return ret;
962 static void ssh_close(BlockDriverState *bs)
964 BDRVSSHState *s = bs->opaque;
966 ssh_state_free(s);
969 static int ssh_has_zero_init(BlockDriverState *bs)
971 BDRVSSHState *s = bs->opaque;
972 /* Assume false, unless we can positively prove it's true. */
973 int has_zero_init = 0;
975 if (s->attrs->type == SSH_FILEXFER_TYPE_REGULAR) {
976 has_zero_init = 1;
979 return has_zero_init;
982 typedef struct BDRVSSHRestart {
983 BlockDriverState *bs;
984 Coroutine *co;
985 } BDRVSSHRestart;
987 static void restart_coroutine(void *opaque)
989 BDRVSSHRestart *restart = opaque;
990 BlockDriverState *bs = restart->bs;
991 BDRVSSHState *s = bs->opaque;
992 AioContext *ctx = bdrv_get_aio_context(bs);
994 trace_ssh_restart_coroutine(restart->co);
995 aio_set_fd_handler(ctx, s->sock, false, NULL, NULL, NULL, NULL);
997 aio_co_wake(restart->co);
1000 /* A non-blocking call returned EAGAIN, so yield, ensuring the
1001 * handlers are set up so that we'll be rescheduled when there is an
1002 * interesting event on the socket.
1004 static coroutine_fn void co_yield(BDRVSSHState *s, BlockDriverState *bs)
1006 int r;
1007 IOHandler *rd_handler = NULL, *wr_handler = NULL;
1008 BDRVSSHRestart restart = {
1009 .bs = bs,
1010 .co = qemu_coroutine_self()
1013 r = ssh_get_poll_flags(s->session);
1015 if (r & SSH_READ_PENDING) {
1016 rd_handler = restart_coroutine;
1018 if (r & SSH_WRITE_PENDING) {
1019 wr_handler = restart_coroutine;
1022 trace_ssh_co_yield(s->sock, rd_handler, wr_handler);
1024 aio_set_fd_handler(bdrv_get_aio_context(bs), s->sock,
1025 false, rd_handler, wr_handler, NULL, &restart);
1026 qemu_coroutine_yield();
1027 trace_ssh_co_yield_back(s->sock);
1030 static coroutine_fn int ssh_read(BDRVSSHState *s, BlockDriverState *bs,
1031 int64_t offset, size_t size,
1032 QEMUIOVector *qiov)
1034 ssize_t r;
1035 size_t got;
1036 char *buf, *end_of_vec;
1037 struct iovec *i;
1039 trace_ssh_read(offset, size);
1041 trace_ssh_seek(offset);
1042 sftp_seek64(s->sftp_handle, offset);
1044 /* This keeps track of the current iovec element ('i'), where we
1045 * will write to next ('buf'), and the end of the current iovec
1046 * ('end_of_vec').
1048 i = &qiov->iov[0];
1049 buf = i->iov_base;
1050 end_of_vec = i->iov_base + i->iov_len;
1052 for (got = 0; got < size; ) {
1053 size_t request_read_size;
1054 again:
1056 * The size of SFTP packets is limited to 32K bytes, so limit
1057 * the amount of data requested to 16K, as libssh currently
1058 * does not handle multiple requests on its own.
1060 request_read_size = MIN(end_of_vec - buf, 16384);
1061 trace_ssh_read_buf(buf, end_of_vec - buf, request_read_size);
1062 r = sftp_read(s->sftp_handle, buf, request_read_size);
1063 trace_ssh_read_return(r, sftp_get_error(s->sftp));
1065 if (r == SSH_AGAIN) {
1066 co_yield(s, bs);
1067 goto again;
1069 if (r == SSH_EOF || (r == 0 && sftp_get_error(s->sftp) == SSH_FX_EOF)) {
1070 /* EOF: Short read so pad the buffer with zeroes and return it. */
1071 qemu_iovec_memset(qiov, got, 0, size - got);
1072 return 0;
1074 if (r <= 0) {
1075 sftp_error_trace(s, "read");
1076 return -EIO;
1079 got += r;
1080 buf += r;
1081 if (buf >= end_of_vec && got < size) {
1082 i++;
1083 buf = i->iov_base;
1084 end_of_vec = i->iov_base + i->iov_len;
1088 return 0;
1091 static coroutine_fn int ssh_co_readv(BlockDriverState *bs,
1092 int64_t sector_num,
1093 int nb_sectors, QEMUIOVector *qiov)
1095 BDRVSSHState *s = bs->opaque;
1096 int ret;
1098 qemu_co_mutex_lock(&s->lock);
1099 ret = ssh_read(s, bs, sector_num * BDRV_SECTOR_SIZE,
1100 nb_sectors * BDRV_SECTOR_SIZE, qiov);
1101 qemu_co_mutex_unlock(&s->lock);
1103 return ret;
1106 static int ssh_write(BDRVSSHState *s, BlockDriverState *bs,
1107 int64_t offset, size_t size,
1108 QEMUIOVector *qiov)
1110 ssize_t r;
1111 size_t written;
1112 char *buf, *end_of_vec;
1113 struct iovec *i;
1115 trace_ssh_write(offset, size);
1117 trace_ssh_seek(offset);
1118 sftp_seek64(s->sftp_handle, offset);
1120 /* This keeps track of the current iovec element ('i'), where we
1121 * will read from next ('buf'), and the end of the current iovec
1122 * ('end_of_vec').
1124 i = &qiov->iov[0];
1125 buf = i->iov_base;
1126 end_of_vec = i->iov_base + i->iov_len;
1128 for (written = 0; written < size; ) {
1129 size_t request_write_size;
1130 again:
1132 * Avoid too large data packets, as libssh currently does not
1133 * handle multiple requests on its own.
1135 request_write_size = MIN(end_of_vec - buf, 131072);
1136 trace_ssh_write_buf(buf, end_of_vec - buf, request_write_size);
1137 r = sftp_write(s->sftp_handle, buf, request_write_size);
1138 trace_ssh_write_return(r, sftp_get_error(s->sftp));
1140 if (r == SSH_AGAIN) {
1141 co_yield(s, bs);
1142 goto again;
1144 if (r < 0) {
1145 sftp_error_trace(s, "write");
1146 return -EIO;
1149 written += r;
1150 buf += r;
1151 if (buf >= end_of_vec && written < size) {
1152 i++;
1153 buf = i->iov_base;
1154 end_of_vec = i->iov_base + i->iov_len;
1157 if (offset + written > s->attrs->size) {
1158 s->attrs->size = offset + written;
1162 return 0;
1165 static coroutine_fn int ssh_co_writev(BlockDriverState *bs,
1166 int64_t sector_num,
1167 int nb_sectors, QEMUIOVector *qiov,
1168 int flags)
1170 BDRVSSHState *s = bs->opaque;
1171 int ret;
1173 assert(!flags);
1174 qemu_co_mutex_lock(&s->lock);
1175 ret = ssh_write(s, bs, sector_num * BDRV_SECTOR_SIZE,
1176 nb_sectors * BDRV_SECTOR_SIZE, qiov);
1177 qemu_co_mutex_unlock(&s->lock);
1179 return ret;
1182 static void unsafe_flush_warning(BDRVSSHState *s, const char *what)
1184 if (!s->unsafe_flush_warning) {
1185 warn_report("ssh server %s does not support fsync",
1186 s->inet->host);
1187 if (what) {
1188 error_report("to support fsync, you need %s", what);
1190 s->unsafe_flush_warning = true;
1194 static coroutine_fn int ssh_flush(BDRVSSHState *s, BlockDriverState *bs)
1196 int r;
1198 trace_ssh_flush();
1200 if (!sftp_extension_supported(s->sftp, "fsync@openssh.com", "1")) {
1201 unsafe_flush_warning(s, "OpenSSH >= 6.3");
1202 return 0;
1204 again:
1205 r = sftp_fsync(s->sftp_handle);
1206 if (r == SSH_AGAIN) {
1207 co_yield(s, bs);
1208 goto again;
1210 if (r < 0) {
1211 sftp_error_trace(s, "fsync");
1212 return -EIO;
1215 return 0;
1218 static coroutine_fn int ssh_co_flush(BlockDriverState *bs)
1220 BDRVSSHState *s = bs->opaque;
1221 int ret;
1223 qemu_co_mutex_lock(&s->lock);
1224 ret = ssh_flush(s, bs);
1225 qemu_co_mutex_unlock(&s->lock);
1227 return ret;
1230 static int64_t ssh_getlength(BlockDriverState *bs)
1232 BDRVSSHState *s = bs->opaque;
1233 int64_t length;
1235 /* Note we cannot make a libssh call here. */
1236 length = (int64_t) s->attrs->size;
1237 trace_ssh_getlength(length);
1239 return length;
1242 static int coroutine_fn ssh_co_truncate(BlockDriverState *bs, int64_t offset,
1243 bool exact, PreallocMode prealloc,
1244 BdrvRequestFlags flags, Error **errp)
1246 BDRVSSHState *s = bs->opaque;
1248 if (prealloc != PREALLOC_MODE_OFF) {
1249 error_setg(errp, "Unsupported preallocation mode '%s'",
1250 PreallocMode_str(prealloc));
1251 return -ENOTSUP;
1254 if (offset < s->attrs->size) {
1255 error_setg(errp, "ssh driver does not support shrinking files");
1256 return -ENOTSUP;
1259 if (offset == s->attrs->size) {
1260 return 0;
1263 return ssh_grow_file(s, offset, errp);
1266 static void ssh_refresh_filename(BlockDriverState *bs)
1268 BDRVSSHState *s = bs->opaque;
1269 const char *path, *host_key_check;
1270 int ret;
1273 * None of these options can be represented in a plain "host:port"
1274 * format, so if any was given, we have to abort.
1276 if (s->inet->has_ipv4 || s->inet->has_ipv6 || s->inet->has_to ||
1277 s->inet->has_numeric)
1279 return;
1282 path = qdict_get_try_str(bs->full_open_options, "path");
1283 assert(path); /* mandatory option */
1285 host_key_check = qdict_get_try_str(bs->full_open_options, "host_key_check");
1287 ret = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
1288 "ssh://%s@%s:%s%s%s%s",
1289 s->user, s->inet->host, s->inet->port, path,
1290 host_key_check ? "?host_key_check=" : "",
1291 host_key_check ?: "");
1292 if (ret >= sizeof(bs->exact_filename)) {
1293 /* An overflow makes the filename unusable, so do not report any */
1294 bs->exact_filename[0] = '\0';
1298 static char *ssh_bdrv_dirname(BlockDriverState *bs, Error **errp)
1300 if (qdict_haskey(bs->full_open_options, "host_key_check")) {
1302 * We cannot generate a simple prefix if we would have to
1303 * append a query string.
1305 error_setg(errp,
1306 "Cannot generate a base directory with host_key_check set");
1307 return NULL;
1310 if (bs->exact_filename[0] == '\0') {
1311 error_setg(errp, "Cannot generate a base directory for this ssh node");
1312 return NULL;
1315 return path_combine(bs->exact_filename, "");
1318 static const char *const ssh_strong_runtime_opts[] = {
1319 "host",
1320 "port",
1321 "path",
1322 "user",
1323 "host_key_check",
1324 "server.",
1326 NULL
1329 static BlockDriver bdrv_ssh = {
1330 .format_name = "ssh",
1331 .protocol_name = "ssh",
1332 .instance_size = sizeof(BDRVSSHState),
1333 .bdrv_parse_filename = ssh_parse_filename,
1334 .bdrv_file_open = ssh_file_open,
1335 .bdrv_co_create = ssh_co_create,
1336 .bdrv_co_create_opts = ssh_co_create_opts,
1337 .bdrv_close = ssh_close,
1338 .bdrv_has_zero_init = ssh_has_zero_init,
1339 .bdrv_co_readv = ssh_co_readv,
1340 .bdrv_co_writev = ssh_co_writev,
1341 .bdrv_getlength = ssh_getlength,
1342 .bdrv_co_truncate = ssh_co_truncate,
1343 .bdrv_co_flush_to_disk = ssh_co_flush,
1344 .bdrv_refresh_filename = ssh_refresh_filename,
1345 .bdrv_dirname = ssh_bdrv_dirname,
1346 .create_opts = &ssh_create_opts,
1347 .strong_runtime_opts = ssh_strong_runtime_opts,
1350 static void bdrv_ssh_init(void)
1352 int r;
1354 r = ssh_init();
1355 if (r != 0) {
1356 fprintf(stderr, "libssh initialization failed, %d\n", r);
1357 exit(EXIT_FAILURE);
1360 #if TRACE_LIBSSH != 0
1361 ssh_set_log_level(TRACE_LIBSSH);
1362 #endif
1364 bdrv_register(&bdrv_ssh);
1367 block_init(bdrv_ssh_init);