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