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