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