xref: /openbmc/qemu/block/ssh.c (revision 99d46107)
1 /*
2  * Secure Shell (ssh) backend for QEMU.
3  *
4  * Copyright (C) 2013 Red Hat Inc., Richard W.M. Jones <rjones@redhat.com>
5  *
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:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
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.
23  */
24 
25 #include "qemu/osdep.h"
26 
27 #include <libssh2.h>
28 #include <libssh2_sftp.h>
29 
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"
45 
46 /*
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
52  */
53 #define TRACE_LIBSSH2 0 /* or try: LIBSSH2_TRACE_SFTP */
54 
55 typedef struct BDRVSSHState {
56     /* Coroutine. */
57     CoMutex lock;
58 
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 */
64 
65     /* See ssh_seek() function below. */
66     int64_t offset;
67     bool offset_op_read;
68 
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).
71      */
72     LIBSSH2_SFTP_ATTRIBUTES attrs;
73 
74     InetSocketAddress *inet;
75 
76     /* Used to warn if 'flush' is not supported. */
77     bool unsafe_flush_warning;
78 } BDRVSSHState;
79 
80 static void ssh_state_init(BDRVSSHState *s)
81 {
82     memset(s, 0, sizeof *s);
83     s->sock = -1;
84     s->offset = -1;
85     qemu_co_mutex_init(&s->lock);
86 }
87 
88 static void ssh_state_free(BDRVSSHState *s)
89 {
90     if (s->sftp_handle) {
91         libssh2_sftp_close(s->sftp_handle);
92     }
93     if (s->sftp) {
94         libssh2_sftp_shutdown(s->sftp);
95     }
96     if (s->session) {
97         libssh2_session_disconnect(s->session,
98                                    "from qemu ssh client: "
99                                    "user closed the connection");
100         libssh2_session_free(s->session);
101     }
102     if (s->sock >= 0) {
103         close(s->sock);
104     }
105 }
106 
107 static void GCC_FMT_ATTR(3, 4)
108 session_error_setg(Error **errp, BDRVSSHState *s, const char *fs, ...)
109 {
110     va_list args;
111     char *msg;
112 
113     va_start(args, fs);
114     msg = g_strdup_vprintf(fs, args);
115     va_end(args);
116 
117     if (s->session) {
118         char *ssh_err;
119         int ssh_err_code;
120 
121         /* This is not an errno.  See <libssh2.h>. */
122         ssh_err_code = libssh2_session_last_error(s->session,
123                                                   &ssh_err, NULL, 0);
124         error_setg(errp, "%s: %s (libssh2 error code: %d)",
125                    msg, ssh_err, ssh_err_code);
126     } else {
127         error_setg(errp, "%s", msg);
128     }
129     g_free(msg);
130 }
131 
132 static void GCC_FMT_ATTR(3, 4)
133 sftp_error_setg(Error **errp, BDRVSSHState *s, const char *fs, ...)
134 {
135     va_list args;
136     char *msg;
137 
138     va_start(args, fs);
139     msg = g_strdup_vprintf(fs, args);
140     va_end(args);
141 
142     if (s->sftp) {
143         char *ssh_err;
144         int ssh_err_code;
145         unsigned long sftp_err_code;
146 
147         /* This is not an errno.  See <libssh2.h>. */
148         ssh_err_code = libssh2_session_last_error(s->session,
149                                                   &ssh_err, NULL, 0);
150         /* See <libssh2_sftp.h>. */
151         sftp_err_code = libssh2_sftp_last_error((s)->sftp);
152 
153         error_setg(errp,
154                    "%s: %s (libssh2 error code: %d, sftp error code: %lu)",
155                    msg, ssh_err, ssh_err_code, sftp_err_code);
156     } else {
157         error_setg(errp, "%s", msg);
158     }
159     g_free(msg);
160 }
161 
162 static void GCC_FMT_ATTR(2, 3)
163 sftp_error_report(BDRVSSHState *s, const char *fs, ...)
164 {
165     va_list args;
166 
167     va_start(args, fs);
168     error_vprintf(fs, args);
169 
170     if ((s)->sftp) {
171         char *ssh_err;
172         int ssh_err_code;
173         unsigned long sftp_err_code;
174 
175         /* This is not an errno.  See <libssh2.h>. */
176         ssh_err_code = libssh2_session_last_error(s->session,
177                                                   &ssh_err, NULL, 0);
178         /* See <libssh2_sftp.h>. */
179         sftp_err_code = libssh2_sftp_last_error((s)->sftp);
180 
181         error_printf(": %s (libssh2 error code: %d, sftp error code: %lu)",
182                      ssh_err, ssh_err_code, sftp_err_code);
183     }
184 
185     va_end(args);
186     error_printf("\n");
187 }
188 
189 static int parse_uri(const char *filename, QDict *options, Error **errp)
190 {
191     URI *uri = NULL;
192     QueryParams *qp;
193     char *port_str;
194     int i;
195 
196     uri = uri_parse(filename);
197     if (!uri) {
198         return -EINVAL;
199     }
200 
201     if (g_strcmp0(uri->scheme, "ssh") != 0) {
202         error_setg(errp, "URI scheme must be 'ssh'");
203         goto err;
204     }
205 
206     if (!uri->server || strcmp(uri->server, "") == 0) {
207         error_setg(errp, "missing hostname in URI");
208         goto err;
209     }
210 
211     if (!uri->path || strcmp(uri->path, "") == 0) {
212         error_setg(errp, "missing remote path in URI");
213         goto err;
214     }
215 
216     qp = query_params_parse(uri->query);
217     if (!qp) {
218         error_setg(errp, "could not parse query parameters");
219         goto err;
220     }
221 
222     if(uri->user && strcmp(uri->user, "") != 0) {
223         qdict_put_str(options, "user", uri->user);
224     }
225 
226     qdict_put_str(options, "server.host", uri->server);
227 
228     port_str = g_strdup_printf("%d", uri->port ?: 22);
229     qdict_put_str(options, "server.port", port_str);
230     g_free(port_str);
231 
232     qdict_put_str(options, "path", uri->path);
233 
234     /* Pick out any query parameters that we understand, and ignore
235      * the rest.
236      */
237     for (i = 0; i < qp->n; ++i) {
238         if (strcmp(qp->p[i].name, "host_key_check") == 0) {
239             qdict_put_str(options, "host_key_check", qp->p[i].value);
240         }
241     }
242 
243     query_params_free(qp);
244     uri_free(uri);
245     return 0;
246 
247  err:
248     if (uri) {
249       uri_free(uri);
250     }
251     return -EINVAL;
252 }
253 
254 static bool ssh_has_filename_options_conflict(QDict *options, Error **errp)
255 {
256     const QDictEntry *qe;
257 
258     for (qe = qdict_first(options); qe; qe = qdict_next(options, qe)) {
259         if (!strcmp(qe->key, "host") ||
260             !strcmp(qe->key, "port") ||
261             !strcmp(qe->key, "path") ||
262             !strcmp(qe->key, "user") ||
263             !strcmp(qe->key, "host_key_check") ||
264             strstart(qe->key, "server.", NULL))
265         {
266             error_setg(errp, "Option '%s' cannot be used with a file name",
267                        qe->key);
268             return true;
269         }
270     }
271 
272     return false;
273 }
274 
275 static void ssh_parse_filename(const char *filename, QDict *options,
276                                Error **errp)
277 {
278     if (ssh_has_filename_options_conflict(options, errp)) {
279         return;
280     }
281 
282     parse_uri(filename, options, errp);
283 }
284 
285 static int check_host_key_knownhosts(BDRVSSHState *s,
286                                      const char *host, int port, Error **errp)
287 {
288     const char *home;
289     char *knh_file = NULL;
290     LIBSSH2_KNOWNHOSTS *knh = NULL;
291     struct libssh2_knownhost *found;
292     int ret, r;
293     const char *hostkey;
294     size_t len;
295     int type;
296 
297     hostkey = libssh2_session_hostkey(s->session, &len, &type);
298     if (!hostkey) {
299         ret = -EINVAL;
300         session_error_setg(errp, s, "failed to read remote host key");
301         goto out;
302     }
303 
304     knh = libssh2_knownhost_init(s->session);
305     if (!knh) {
306         ret = -EINVAL;
307         session_error_setg(errp, s,
308                            "failed to initialize known hosts support");
309         goto out;
310     }
311 
312     home = getenv("HOME");
313     if (home) {
314         knh_file = g_strdup_printf("%s/.ssh/known_hosts", home);
315     } else {
316         knh_file = g_strdup_printf("/root/.ssh/known_hosts");
317     }
318 
319     /* Read all known hosts from OpenSSH-style known_hosts file. */
320     libssh2_knownhost_readfile(knh, knh_file, LIBSSH2_KNOWNHOST_FILE_OPENSSH);
321 
322     r = libssh2_knownhost_checkp(knh, host, port, hostkey, len,
323                                  LIBSSH2_KNOWNHOST_TYPE_PLAIN|
324                                  LIBSSH2_KNOWNHOST_KEYENC_RAW,
325                                  &found);
326     switch (r) {
327     case LIBSSH2_KNOWNHOST_CHECK_MATCH:
328         /* OK */
329         trace_ssh_check_host_key_knownhosts(found->key);
330         break;
331     case LIBSSH2_KNOWNHOST_CHECK_MISMATCH:
332         ret = -EINVAL;
333         session_error_setg(errp, s,
334                       "host key does not match the one in known_hosts"
335                       " (found key %s)", found->key);
336         goto out;
337     case LIBSSH2_KNOWNHOST_CHECK_NOTFOUND:
338         ret = -EINVAL;
339         session_error_setg(errp, s, "no host key was found in known_hosts");
340         goto out;
341     case LIBSSH2_KNOWNHOST_CHECK_FAILURE:
342         ret = -EINVAL;
343         session_error_setg(errp, s,
344                       "failure matching the host key with known_hosts");
345         goto out;
346     default:
347         ret = -EINVAL;
348         session_error_setg(errp, s, "unknown error matching the host key"
349                       " with known_hosts (%d)", r);
350         goto out;
351     }
352 
353     /* known_hosts checking successful. */
354     ret = 0;
355 
356  out:
357     if (knh != NULL) {
358         libssh2_knownhost_free(knh);
359     }
360     g_free(knh_file);
361     return ret;
362 }
363 
364 static unsigned hex2decimal(char ch)
365 {
366     if (ch >= '0' && ch <= '9') {
367         return (ch - '0');
368     } else if (ch >= 'a' && ch <= 'f') {
369         return 10 + (ch - 'a');
370     } else if (ch >= 'A' && ch <= 'F') {
371         return 10 + (ch - 'A');
372     }
373 
374     return -1;
375 }
376 
377 /* Compare the binary fingerprint (hash of host key) with the
378  * host_key_check parameter.
379  */
380 static int compare_fingerprint(const unsigned char *fingerprint, size_t len,
381                                const char *host_key_check)
382 {
383     unsigned c;
384 
385     while (len > 0) {
386         while (*host_key_check == ':')
387             host_key_check++;
388         if (!qemu_isxdigit(host_key_check[0]) ||
389             !qemu_isxdigit(host_key_check[1]))
390             return 1;
391         c = hex2decimal(host_key_check[0]) * 16 +
392             hex2decimal(host_key_check[1]);
393         if (c - *fingerprint != 0)
394             return c - *fingerprint;
395         fingerprint++;
396         len--;
397         host_key_check += 2;
398     }
399     return *host_key_check - '\0';
400 }
401 
402 static int
403 check_host_key_hash(BDRVSSHState *s, const char *hash,
404                     int hash_type, size_t fingerprint_len, Error **errp)
405 {
406     const char *fingerprint;
407 
408     fingerprint = libssh2_hostkey_hash(s->session, hash_type);
409     if (!fingerprint) {
410         session_error_setg(errp, s, "failed to read remote host key");
411         return -EINVAL;
412     }
413 
414     if(compare_fingerprint((unsigned char *) fingerprint, fingerprint_len,
415                            hash) != 0) {
416         error_setg(errp, "remote host key does not match host_key_check '%s'",
417                    hash);
418         return -EPERM;
419     }
420 
421     return 0;
422 }
423 
424 static int check_host_key(BDRVSSHState *s, const char *host, int port,
425                           SshHostKeyCheck *hkc, Error **errp)
426 {
427     SshHostKeyCheckMode mode;
428 
429     if (hkc) {
430         mode = hkc->mode;
431     } else {
432         mode = SSH_HOST_KEY_CHECK_MODE_KNOWN_HOSTS;
433     }
434 
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                                        LIBSSH2_HOSTKEY_HASH_MD5, 16, 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                                        LIBSSH2_HOSTKEY_HASH_SHA1, 20, errp);
445         }
446         g_assert_not_reached();
447         break;
448     case SSH_HOST_KEY_CHECK_MODE_KNOWN_HOSTS:
449         return check_host_key_knownhosts(s, host, port, errp);
450     default:
451         g_assert_not_reached();
452     }
453 
454     return -EINVAL;
455 }
456 
457 static int authenticate(BDRVSSHState *s, const char *user, Error **errp)
458 {
459     int r, ret;
460     const char *userauthlist;
461     LIBSSH2_AGENT *agent = NULL;
462     struct libssh2_agent_publickey *identity;
463     struct libssh2_agent_publickey *prev_identity = NULL;
464 
465     userauthlist = libssh2_userauth_list(s->session, user, strlen(user));
466     if (strstr(userauthlist, "publickey") == NULL) {
467         ret = -EPERM;
468         error_setg(errp,
469                 "remote server does not support \"publickey\" authentication");
470         goto out;
471     }
472 
473     /* Connect to ssh-agent and try each identity in turn. */
474     agent = libssh2_agent_init(s->session);
475     if (!agent) {
476         ret = -EINVAL;
477         session_error_setg(errp, s, "failed to initialize ssh-agent support");
478         goto out;
479     }
480     if (libssh2_agent_connect(agent)) {
481         ret = -ECONNREFUSED;
482         session_error_setg(errp, s, "failed to connect to ssh-agent");
483         goto out;
484     }
485     if (libssh2_agent_list_identities(agent)) {
486         ret = -EINVAL;
487         session_error_setg(errp, s,
488                            "failed requesting identities from ssh-agent");
489         goto out;
490     }
491 
492     for(;;) {
493         r = libssh2_agent_get_identity(agent, &identity, prev_identity);
494         if (r == 1) {           /* end of list */
495             break;
496         }
497         if (r < 0) {
498             ret = -EINVAL;
499             session_error_setg(errp, s,
500                                "failed to obtain identity from ssh-agent");
501             goto out;
502         }
503         r = libssh2_agent_userauth(agent, user, identity);
504         if (r == 0) {
505             /* Authenticated! */
506             ret = 0;
507             goto out;
508         }
509         /* Failed to authenticate with this identity, try the next one. */
510         prev_identity = identity;
511     }
512 
513     ret = -EPERM;
514     error_setg(errp, "failed to authenticate using publickey authentication "
515                "and the identities held by your ssh-agent");
516 
517  out:
518     if (agent != NULL) {
519         /* Note: libssh2 implementation implicitly calls
520          * libssh2_agent_disconnect if necessary.
521          */
522         libssh2_agent_free(agent);
523     }
524 
525     return ret;
526 }
527 
528 static QemuOptsList ssh_runtime_opts = {
529     .name = "ssh",
530     .head = QTAILQ_HEAD_INITIALIZER(ssh_runtime_opts.head),
531     .desc = {
532         {
533             .name = "host",
534             .type = QEMU_OPT_STRING,
535             .help = "Host to connect to",
536         },
537         {
538             .name = "port",
539             .type = QEMU_OPT_NUMBER,
540             .help = "Port to connect to",
541         },
542         {
543             .name = "host_key_check",
544             .type = QEMU_OPT_STRING,
545             .help = "Defines how and what to check the host key against",
546         },
547         { /* end of list */ }
548     },
549 };
550 
551 static bool ssh_process_legacy_options(QDict *output_opts,
552                                        QemuOpts *legacy_opts,
553                                        Error **errp)
554 {
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");
558 
559     if (!host && port) {
560         error_setg(errp, "port may not be used without host");
561         return false;
562     }
563 
564     if (host) {
565         qdict_put_str(output_opts, "server.host", host);
566         qdict_put_str(output_opts, "server.port", port ?: stringify(22));
567     }
568 
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",
576                           &host_key_check[4]);
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",
581                           &host_key_check[5]);
582         } else if (strcmp(host_key_check, "yes") == 0) {
583             qdict_put_str(output_opts, "host-key-check.mode", "known_hosts");
584         } else {
585             error_setg(errp, "unknown host_key_check setting (%s)",
586                        host_key_check);
587             return false;
588         }
589     }
590 
591     return true;
592 }
593 
594 static BlockdevOptionsSsh *ssh_parse_options(QDict *options, Error **errp)
595 {
596     BlockdevOptionsSsh *result = NULL;
597     QemuOpts *opts = NULL;
598     Error *local_err = NULL;
599     const QDictEntry *e;
600     Visitor *v;
601 
602     /* Translate legacy options */
603     opts = qemu_opts_create(&ssh_runtime_opts, NULL, 0, &error_abort);
604     qemu_opts_absorb_qdict(opts, options, &local_err);
605     if (local_err) {
606         error_propagate(errp, local_err);
607         goto fail;
608     }
609 
610     if (!ssh_process_legacy_options(options, opts, errp)) {
611         goto fail;
612     }
613 
614     /* Create the QAPI object */
615     v = qobject_input_visitor_new_flat_confused(options, errp);
616     if (!v) {
617         goto fail;
618     }
619 
620     visit_type_BlockdevOptionsSsh(v, NULL, &result, &local_err);
621     visit_free(v);
622 
623     if (local_err) {
624         error_propagate(errp, local_err);
625         goto fail;
626     }
627 
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);
632     }
633 
634 fail:
635     qemu_opts_del(opts);
636     return result;
637 }
638 
639 static int connect_to_ssh(BDRVSSHState *s, BlockdevOptionsSsh *opts,
640                           int ssh_flags, int creat_mode, Error **errp)
641 {
642     int r, ret;
643     const char *user;
644     long port = 0;
645 
646     if (opts->has_user) {
647         user = opts->user;
648     } else {
649         user = g_get_user_name();
650         if (!user) {
651             error_setg_errno(errp, errno, "Can't get user name");
652             ret = -errno;
653             goto err;
654         }
655     }
656 
657     /* Pop the config into our state object, Exit if invalid */
658     s->inet = opts->server;
659     opts->server = NULL;
660 
661     if (qemu_strtol(s->inet->port, NULL, 10, &port) < 0) {
662         error_setg(errp, "Use only numeric port value");
663         ret = -EINVAL;
664         goto err;
665     }
666 
667     /* Open the socket and connect. */
668     s->sock = inet_connect_saddr(s->inet, errp);
669     if (s->sock < 0) {
670         ret = -EIO;
671         goto err;
672     }
673 
674     /* Create SSH session. */
675     s->session = libssh2_session_init();
676     if (!s->session) {
677         ret = -EINVAL;
678         session_error_setg(errp, s, "failed to initialize libssh2 session");
679         goto err;
680     }
681 
682 #if TRACE_LIBSSH2 != 0
683     libssh2_trace(s->session, TRACE_LIBSSH2);
684 #endif
685 
686     r = libssh2_session_handshake(s->session, s->sock);
687     if (r != 0) {
688         ret = -EINVAL;
689         session_error_setg(errp, s, "failed to establish SSH session");
690         goto err;
691     }
692 
693     /* Check the remote host's key against known_hosts. */
694     ret = check_host_key(s, s->inet->host, port, opts->host_key_check, errp);
695     if (ret < 0) {
696         goto err;
697     }
698 
699     /* Authenticate. */
700     ret = authenticate(s, user, errp);
701     if (ret < 0) {
702         goto err;
703     }
704 
705     /* Start SFTP. */
706     s->sftp = libssh2_sftp_init(s->session);
707     if (!s->sftp) {
708         session_error_setg(errp, s, "failed to initialize sftp handle");
709         ret = -EINVAL;
710         goto err;
711     }
712 
713     /* Open the remote file. */
714     trace_ssh_connect_to_ssh(opts->path, ssh_flags, creat_mode);
715     s->sftp_handle = libssh2_sftp_open(s->sftp, opts->path, ssh_flags,
716                                        creat_mode);
717     if (!s->sftp_handle) {
718         session_error_setg(errp, s, "failed to open remote file '%s'",
719                            opts->path);
720         ret = -EINVAL;
721         goto err;
722     }
723 
724     r = libssh2_sftp_fstat(s->sftp_handle, &s->attrs);
725     if (r < 0) {
726         sftp_error_setg(errp, s, "failed to read file attributes");
727         return -EINVAL;
728     }
729 
730     return 0;
731 
732  err:
733     if (s->sftp_handle) {
734         libssh2_sftp_close(s->sftp_handle);
735     }
736     s->sftp_handle = NULL;
737     if (s->sftp) {
738         libssh2_sftp_shutdown(s->sftp);
739     }
740     s->sftp = NULL;
741     if (s->session) {
742         libssh2_session_disconnect(s->session,
743                                    "from qemu ssh client: "
744                                    "error opening connection");
745         libssh2_session_free(s->session);
746     }
747     s->session = NULL;
748 
749     return ret;
750 }
751 
752 static int ssh_file_open(BlockDriverState *bs, QDict *options, int bdrv_flags,
753                          Error **errp)
754 {
755     BDRVSSHState *s = bs->opaque;
756     BlockdevOptionsSsh *opts;
757     int ret;
758     int ssh_flags;
759 
760     ssh_state_init(s);
761 
762     ssh_flags = LIBSSH2_FXF_READ;
763     if (bdrv_flags & BDRV_O_RDWR) {
764         ssh_flags |= LIBSSH2_FXF_WRITE;
765     }
766 
767     opts = ssh_parse_options(options, errp);
768     if (opts == NULL) {
769         return -EINVAL;
770     }
771 
772     /* Start up SSH. */
773     ret = connect_to_ssh(s, opts, ssh_flags, 0, errp);
774     if (ret < 0) {
775         goto err;
776     }
777 
778     /* Go non-blocking. */
779     libssh2_session_set_blocking(s->session, 0);
780 
781     qapi_free_BlockdevOptionsSsh(opts);
782 
783     return 0;
784 
785  err:
786     if (s->sock >= 0) {
787         close(s->sock);
788     }
789     s->sock = -1;
790 
791     qapi_free_BlockdevOptionsSsh(opts);
792 
793     return ret;
794 }
795 
796 /* Note: This is a blocking operation */
797 static int ssh_grow_file(BDRVSSHState *s, int64_t offset, Error **errp)
798 {
799     ssize_t ret;
800     char c[1] = { '\0' };
801     int was_blocking = libssh2_session_get_blocking(s->session);
802 
803     /* offset must be strictly greater than the current size so we do
804      * not overwrite anything */
805     assert(offset > 0 && offset > s->attrs.filesize);
806 
807     libssh2_session_set_blocking(s->session, 1);
808 
809     libssh2_sftp_seek64(s->sftp_handle, offset - 1);
810     ret = libssh2_sftp_write(s->sftp_handle, c, 1);
811 
812     libssh2_session_set_blocking(s->session, was_blocking);
813 
814     if (ret < 0) {
815         sftp_error_setg(errp, s, "Failed to grow file");
816         return -EIO;
817     }
818 
819     s->attrs.filesize = offset;
820     return 0;
821 }
822 
823 static QemuOptsList ssh_create_opts = {
824     .name = "ssh-create-opts",
825     .head = QTAILQ_HEAD_INITIALIZER(ssh_create_opts.head),
826     .desc = {
827         {
828             .name = BLOCK_OPT_SIZE,
829             .type = QEMU_OPT_SIZE,
830             .help = "Virtual disk size"
831         },
832         { /* end of list */ }
833     }
834 };
835 
836 static int ssh_co_create(BlockdevCreateOptions *options, Error **errp)
837 {
838     BlockdevCreateOptionsSsh *opts = &options->u.ssh;
839     BDRVSSHState s;
840     int ret;
841 
842     assert(options->driver == BLOCKDEV_DRIVER_SSH);
843 
844     ssh_state_init(&s);
845 
846     ret = connect_to_ssh(&s, opts->location,
847                          LIBSSH2_FXF_READ|LIBSSH2_FXF_WRITE|
848                          LIBSSH2_FXF_CREAT|LIBSSH2_FXF_TRUNC,
849                          0644, errp);
850     if (ret < 0) {
851         goto fail;
852     }
853 
854     if (opts->size > 0) {
855         ret = ssh_grow_file(&s, opts->size, errp);
856         if (ret < 0) {
857             goto fail;
858         }
859     }
860 
861     ret = 0;
862 fail:
863     ssh_state_free(&s);
864     return ret;
865 }
866 
867 static int coroutine_fn ssh_co_create_opts(const char *filename, QemuOpts *opts,
868                                            Error **errp)
869 {
870     BlockdevCreateOptions *create_options;
871     BlockdevCreateOptionsSsh *ssh_opts;
872     int ret;
873     QDict *uri_options = NULL;
874 
875     create_options = g_new0(BlockdevCreateOptions, 1);
876     create_options->driver = BLOCKDEV_DRIVER_SSH;
877     ssh_opts = &create_options->u.ssh;
878 
879     /* Get desired file size. */
880     ssh_opts->size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
881                               BDRV_SECTOR_SIZE);
882     trace_ssh_co_create_opts(ssh_opts->size);
883 
884     uri_options = qdict_new();
885     ret = parse_uri(filename, uri_options, errp);
886     if (ret < 0) {
887         goto out;
888     }
889 
890     ssh_opts->location = ssh_parse_options(uri_options, errp);
891     if (ssh_opts->location == NULL) {
892         ret = -EINVAL;
893         goto out;
894     }
895 
896     ret = ssh_co_create(create_options, errp);
897 
898  out:
899     qobject_unref(uri_options);
900     qapi_free_BlockdevCreateOptions(create_options);
901     return ret;
902 }
903 
904 static void ssh_close(BlockDriverState *bs)
905 {
906     BDRVSSHState *s = bs->opaque;
907 
908     ssh_state_free(s);
909 }
910 
911 static int ssh_has_zero_init(BlockDriverState *bs)
912 {
913     BDRVSSHState *s = bs->opaque;
914     /* Assume false, unless we can positively prove it's true. */
915     int has_zero_init = 0;
916 
917     if (s->attrs.flags & LIBSSH2_SFTP_ATTR_PERMISSIONS) {
918         if (s->attrs.permissions & LIBSSH2_SFTP_S_IFREG) {
919             has_zero_init = 1;
920         }
921     }
922 
923     return has_zero_init;
924 }
925 
926 typedef struct BDRVSSHRestart {
927     BlockDriverState *bs;
928     Coroutine *co;
929 } BDRVSSHRestart;
930 
931 static void restart_coroutine(void *opaque)
932 {
933     BDRVSSHRestart *restart = opaque;
934     BlockDriverState *bs = restart->bs;
935     BDRVSSHState *s = bs->opaque;
936     AioContext *ctx = bdrv_get_aio_context(bs);
937 
938     trace_ssh_restart_coroutine(restart->co);
939     aio_set_fd_handler(ctx, s->sock, false, NULL, NULL, NULL, NULL);
940 
941     aio_co_wake(restart->co);
942 }
943 
944 /* A non-blocking call returned EAGAIN, so yield, ensuring the
945  * handlers are set up so that we'll be rescheduled when there is an
946  * interesting event on the socket.
947  */
948 static coroutine_fn void co_yield(BDRVSSHState *s, BlockDriverState *bs)
949 {
950     int r;
951     IOHandler *rd_handler = NULL, *wr_handler = NULL;
952     BDRVSSHRestart restart = {
953         .bs = bs,
954         .co = qemu_coroutine_self()
955     };
956 
957     r = libssh2_session_block_directions(s->session);
958 
959     if (r & LIBSSH2_SESSION_BLOCK_INBOUND) {
960         rd_handler = restart_coroutine;
961     }
962     if (r & LIBSSH2_SESSION_BLOCK_OUTBOUND) {
963         wr_handler = restart_coroutine;
964     }
965 
966     trace_ssh_co_yield(s->sock, rd_handler, wr_handler);
967 
968     aio_set_fd_handler(bdrv_get_aio_context(bs), s->sock,
969                        false, rd_handler, wr_handler, NULL, &restart);
970     qemu_coroutine_yield();
971     trace_ssh_co_yield_back(s->sock);
972 }
973 
974 /* SFTP has a function `libssh2_sftp_seek64' which seeks to a position
975  * in the remote file.  Notice that it just updates a field in the
976  * sftp_handle structure, so there is no network traffic and it cannot
977  * fail.
978  *
979  * However, `libssh2_sftp_seek64' does have a catastrophic effect on
980  * performance since it causes the handle to throw away all in-flight
981  * reads and buffered readahead data.  Therefore this function tries
982  * to be intelligent about when to call the underlying libssh2 function.
983  */
984 #define SSH_SEEK_WRITE 0
985 #define SSH_SEEK_READ  1
986 #define SSH_SEEK_FORCE 2
987 
988 static void ssh_seek(BDRVSSHState *s, int64_t offset, int flags)
989 {
990     bool op_read = (flags & SSH_SEEK_READ) != 0;
991     bool force = (flags & SSH_SEEK_FORCE) != 0;
992 
993     if (force || op_read != s->offset_op_read || offset != s->offset) {
994         trace_ssh_seek(offset);
995         libssh2_sftp_seek64(s->sftp_handle, offset);
996         s->offset = offset;
997         s->offset_op_read = op_read;
998     }
999 }
1000 
1001 static coroutine_fn int ssh_read(BDRVSSHState *s, BlockDriverState *bs,
1002                                  int64_t offset, size_t size,
1003                                  QEMUIOVector *qiov)
1004 {
1005     ssize_t r;
1006     size_t got;
1007     char *buf, *end_of_vec;
1008     struct iovec *i;
1009 
1010     trace_ssh_read(offset, size);
1011 
1012     ssh_seek(s, offset, SSH_SEEK_READ);
1013 
1014     /* This keeps track of the current iovec element ('i'), where we
1015      * will write to next ('buf'), and the end of the current iovec
1016      * ('end_of_vec').
1017      */
1018     i = &qiov->iov[0];
1019     buf = i->iov_base;
1020     end_of_vec = i->iov_base + i->iov_len;
1021 
1022     /* libssh2 has a hard-coded limit of 2000 bytes per request,
1023      * although it will also do readahead behind our backs.  Therefore
1024      * we may have to do repeated reads here until we have read 'size'
1025      * bytes.
1026      */
1027     for (got = 0; got < size; ) {
1028     again:
1029         trace_ssh_read_buf(buf, end_of_vec - buf);
1030         r = libssh2_sftp_read(s->sftp_handle, buf, end_of_vec - buf);
1031         trace_ssh_read_return(r);
1032 
1033         if (r == LIBSSH2_ERROR_EAGAIN || r == LIBSSH2_ERROR_TIMEOUT) {
1034             co_yield(s, bs);
1035             goto again;
1036         }
1037         if (r < 0) {
1038             sftp_error_report(s, "read failed");
1039             s->offset = -1;
1040             return -EIO;
1041         }
1042         if (r == 0) {
1043             /* EOF: Short read so pad the buffer with zeroes and return it. */
1044             qemu_iovec_memset(qiov, got, 0, size - got);
1045             return 0;
1046         }
1047 
1048         got += r;
1049         buf += r;
1050         s->offset += r;
1051         if (buf >= end_of_vec && got < size) {
1052             i++;
1053             buf = i->iov_base;
1054             end_of_vec = i->iov_base + i->iov_len;
1055         }
1056     }
1057 
1058     return 0;
1059 }
1060 
1061 static coroutine_fn int ssh_co_readv(BlockDriverState *bs,
1062                                      int64_t sector_num,
1063                                      int nb_sectors, QEMUIOVector *qiov)
1064 {
1065     BDRVSSHState *s = bs->opaque;
1066     int ret;
1067 
1068     qemu_co_mutex_lock(&s->lock);
1069     ret = ssh_read(s, bs, sector_num * BDRV_SECTOR_SIZE,
1070                    nb_sectors * BDRV_SECTOR_SIZE, qiov);
1071     qemu_co_mutex_unlock(&s->lock);
1072 
1073     return ret;
1074 }
1075 
1076 static int ssh_write(BDRVSSHState *s, BlockDriverState *bs,
1077                      int64_t offset, size_t size,
1078                      QEMUIOVector *qiov)
1079 {
1080     ssize_t r;
1081     size_t written;
1082     char *buf, *end_of_vec;
1083     struct iovec *i;
1084 
1085     trace_ssh_write(offset, size);
1086 
1087     ssh_seek(s, offset, SSH_SEEK_WRITE);
1088 
1089     /* This keeps track of the current iovec element ('i'), where we
1090      * will read from next ('buf'), and the end of the current iovec
1091      * ('end_of_vec').
1092      */
1093     i = &qiov->iov[0];
1094     buf = i->iov_base;
1095     end_of_vec = i->iov_base + i->iov_len;
1096 
1097     for (written = 0; written < size; ) {
1098     again:
1099         trace_ssh_write_buf(buf, end_of_vec - buf);
1100         r = libssh2_sftp_write(s->sftp_handle, buf, end_of_vec - buf);
1101         trace_ssh_write_return(r);
1102 
1103         if (r == LIBSSH2_ERROR_EAGAIN || r == LIBSSH2_ERROR_TIMEOUT) {
1104             co_yield(s, bs);
1105             goto again;
1106         }
1107         if (r < 0) {
1108             sftp_error_report(s, "write failed");
1109             s->offset = -1;
1110             return -EIO;
1111         }
1112         /* The libssh2 API is very unclear about this.  A comment in
1113          * the code says "nothing was acked, and no EAGAIN was
1114          * received!" which apparently means that no data got sent
1115          * out, and the underlying channel didn't return any EAGAIN
1116          * indication.  I think this is a bug in either libssh2 or
1117          * OpenSSH (server-side).  In any case, forcing a seek (to
1118          * discard libssh2 internal buffers), and then trying again
1119          * works for me.
1120          */
1121         if (r == 0) {
1122             ssh_seek(s, offset + written, SSH_SEEK_WRITE|SSH_SEEK_FORCE);
1123             co_yield(s, bs);
1124             goto again;
1125         }
1126 
1127         written += r;
1128         buf += r;
1129         s->offset += r;
1130         if (buf >= end_of_vec && written < size) {
1131             i++;
1132             buf = i->iov_base;
1133             end_of_vec = i->iov_base + i->iov_len;
1134         }
1135 
1136         if (offset + written > s->attrs.filesize)
1137             s->attrs.filesize = offset + written;
1138     }
1139 
1140     return 0;
1141 }
1142 
1143 static coroutine_fn int ssh_co_writev(BlockDriverState *bs,
1144                                       int64_t sector_num,
1145                                       int nb_sectors, QEMUIOVector *qiov,
1146                                       int flags)
1147 {
1148     BDRVSSHState *s = bs->opaque;
1149     int ret;
1150 
1151     assert(!flags);
1152     qemu_co_mutex_lock(&s->lock);
1153     ret = ssh_write(s, bs, sector_num * BDRV_SECTOR_SIZE,
1154                     nb_sectors * BDRV_SECTOR_SIZE, qiov);
1155     qemu_co_mutex_unlock(&s->lock);
1156 
1157     return ret;
1158 }
1159 
1160 static void unsafe_flush_warning(BDRVSSHState *s, const char *what)
1161 {
1162     if (!s->unsafe_flush_warning) {
1163         warn_report("ssh server %s does not support fsync",
1164                     s->inet->host);
1165         if (what) {
1166             error_report("to support fsync, you need %s", what);
1167         }
1168         s->unsafe_flush_warning = true;
1169     }
1170 }
1171 
1172 #ifdef HAS_LIBSSH2_SFTP_FSYNC
1173 
1174 static coroutine_fn int ssh_flush(BDRVSSHState *s, BlockDriverState *bs)
1175 {
1176     int r;
1177 
1178     trace_ssh_flush();
1179  again:
1180     r = libssh2_sftp_fsync(s->sftp_handle);
1181     if (r == LIBSSH2_ERROR_EAGAIN || r == LIBSSH2_ERROR_TIMEOUT) {
1182         co_yield(s, bs);
1183         goto again;
1184     }
1185     if (r == LIBSSH2_ERROR_SFTP_PROTOCOL &&
1186         libssh2_sftp_last_error(s->sftp) == LIBSSH2_FX_OP_UNSUPPORTED) {
1187         unsafe_flush_warning(s, "OpenSSH >= 6.3");
1188         return 0;
1189     }
1190     if (r < 0) {
1191         sftp_error_report(s, "fsync failed");
1192         return -EIO;
1193     }
1194 
1195     return 0;
1196 }
1197 
1198 static coroutine_fn int ssh_co_flush(BlockDriverState *bs)
1199 {
1200     BDRVSSHState *s = bs->opaque;
1201     int ret;
1202 
1203     qemu_co_mutex_lock(&s->lock);
1204     ret = ssh_flush(s, bs);
1205     qemu_co_mutex_unlock(&s->lock);
1206 
1207     return ret;
1208 }
1209 
1210 #else /* !HAS_LIBSSH2_SFTP_FSYNC */
1211 
1212 static coroutine_fn int ssh_co_flush(BlockDriverState *bs)
1213 {
1214     BDRVSSHState *s = bs->opaque;
1215 
1216     unsafe_flush_warning(s, "libssh2 >= 1.4.4");
1217     return 0;
1218 }
1219 
1220 #endif /* !HAS_LIBSSH2_SFTP_FSYNC */
1221 
1222 static int64_t ssh_getlength(BlockDriverState *bs)
1223 {
1224     BDRVSSHState *s = bs->opaque;
1225     int64_t length;
1226 
1227     /* Note we cannot make a libssh2 call here. */
1228     length = (int64_t) s->attrs.filesize;
1229     trace_ssh_getlength(length);
1230 
1231     return length;
1232 }
1233 
1234 static int coroutine_fn ssh_co_truncate(BlockDriverState *bs, int64_t offset,
1235                                         PreallocMode prealloc, Error **errp)
1236 {
1237     BDRVSSHState *s = bs->opaque;
1238 
1239     if (prealloc != PREALLOC_MODE_OFF) {
1240         error_setg(errp, "Unsupported preallocation mode '%s'",
1241                    PreallocMode_str(prealloc));
1242         return -ENOTSUP;
1243     }
1244 
1245     if (offset < s->attrs.filesize) {
1246         error_setg(errp, "ssh driver does not support shrinking files");
1247         return -ENOTSUP;
1248     }
1249 
1250     if (offset == s->attrs.filesize) {
1251         return 0;
1252     }
1253 
1254     return ssh_grow_file(s, offset, errp);
1255 }
1256 
1257 static const char *const ssh_strong_runtime_opts[] = {
1258     "host",
1259     "port",
1260     "path",
1261     "user",
1262     "host_key_check",
1263     "server.",
1264 
1265     NULL
1266 };
1267 
1268 static BlockDriver bdrv_ssh = {
1269     .format_name                  = "ssh",
1270     .protocol_name                = "ssh",
1271     .instance_size                = sizeof(BDRVSSHState),
1272     .bdrv_parse_filename          = ssh_parse_filename,
1273     .bdrv_file_open               = ssh_file_open,
1274     .bdrv_co_create               = ssh_co_create,
1275     .bdrv_co_create_opts          = ssh_co_create_opts,
1276     .bdrv_close                   = ssh_close,
1277     .bdrv_has_zero_init           = ssh_has_zero_init,
1278     .bdrv_co_readv                = ssh_co_readv,
1279     .bdrv_co_writev               = ssh_co_writev,
1280     .bdrv_getlength               = ssh_getlength,
1281     .bdrv_co_truncate             = ssh_co_truncate,
1282     .bdrv_co_flush_to_disk        = ssh_co_flush,
1283     .create_opts                  = &ssh_create_opts,
1284     .strong_runtime_opts          = ssh_strong_runtime_opts,
1285 };
1286 
1287 static void bdrv_ssh_init(void)
1288 {
1289     int r;
1290 
1291     r = libssh2_init(0);
1292     if (r != 0) {
1293         fprintf(stderr, "libssh2 initialization failed, %d\n", r);
1294         exit(EXIT_FAILURE);
1295     }
1296 
1297     bdrv_register(&bdrv_ssh);
1298 }
1299 
1300 block_init(bdrv_ssh_init);
1301