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