]> git.proxmox.com Git - mirror_qemu.git/blame - block/ssh.c
block/ssh: Propagate errors through connect_to_ssh()
[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
4618e658 437static int authenticate(BDRVSSHState *s, const char *user, Error **errp)
0a12ec87
RJ
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;
4618e658
MA
448 error_setg(errp,
449 "remote server does not support \"publickey\" authentication");
0a12ec87
RJ
450 goto out;
451 }
452
453 /* Connect to ssh-agent and try each identity in turn. */
454 agent = libssh2_agent_init(s->session);
455 if (!agent) {
456 ret = -EINVAL;
4618e658 457 session_error_setg(errp, s, "failed to initialize ssh-agent support");
0a12ec87
RJ
458 goto out;
459 }
460 if (libssh2_agent_connect(agent)) {
461 ret = -ECONNREFUSED;
4618e658 462 session_error_setg(errp, s, "failed to connect to ssh-agent");
0a12ec87
RJ
463 goto out;
464 }
465 if (libssh2_agent_list_identities(agent)) {
466 ret = -EINVAL;
4618e658
MA
467 session_error_setg(errp, s,
468 "failed requesting identities from ssh-agent");
0a12ec87
RJ
469 goto out;
470 }
471
472 for(;;) {
473 r = libssh2_agent_get_identity(agent, &identity, prev_identity);
474 if (r == 1) { /* end of list */
475 break;
476 }
477 if (r < 0) {
478 ret = -EINVAL;
4618e658
MA
479 session_error_setg(errp, s,
480 "failed to obtain identity from ssh-agent");
0a12ec87
RJ
481 goto out;
482 }
483 r = libssh2_agent_userauth(agent, user, identity);
484 if (r == 0) {
485 /* Authenticated! */
486 ret = 0;
487 goto out;
488 }
489 /* Failed to authenticate with this identity, try the next one. */
490 prev_identity = identity;
491 }
492
493 ret = -EPERM;
4618e658
MA
494 error_setg(errp, "failed to authenticate using publickey authentication "
495 "and the identities held by your ssh-agent");
0a12ec87
RJ
496
497 out:
498 if (agent != NULL) {
499 /* Note: libssh2 implementation implicitly calls
500 * libssh2_agent_disconnect if necessary.
501 */
502 libssh2_agent_free(agent);
503 }
504
505 return ret;
506}
507
508static int connect_to_ssh(BDRVSSHState *s, QDict *options,
5f0c39e5 509 int ssh_flags, int creat_mode, Error **errp)
0a12ec87
RJ
510{
511 int r, ret;
0a12ec87
RJ
512 const char *host, *user, *path, *host_key_check;
513 int port;
0a12ec87
RJ
514
515 host = qdict_get_str(options, "host");
516
517 if (qdict_haskey(options, "port")) {
518 port = qdict_get_int(options, "port");
519 } else {
520 port = 22;
521 }
522
523 path = qdict_get_str(options, "path");
524
525 if (qdict_haskey(options, "user")) {
526 user = qdict_get_str(options, "user");
527 } else {
528 user = g_get_user_name();
529 if (!user) {
5f0c39e5 530 error_setg_errno(errp, errno, "Can't get user name");
0a12ec87
RJ
531 ret = -errno;
532 goto err;
533 }
534 }
535
536 if (qdict_haskey(options, "host_key_check")) {
537 host_key_check = qdict_get_str(options, "host_key_check");
538 } else {
539 host_key_check = "yes";
540 }
541
9a2d462e
RJ
542 /* Construct the host:port name for inet_connect. */
543 g_free(s->hostport);
544 s->hostport = g_strdup_printf("%s:%d", host, port);
545
0a12ec87 546 /* Open the socket and connect. */
5f0c39e5
MA
547 s->sock = inet_connect(s->hostport, errp);
548 if (s->sock < 0) {
0a12ec87 549 ret = -errno;
0a12ec87
RJ
550 goto err;
551 }
552
553 /* Create SSH session. */
554 s->session = libssh2_session_init();
555 if (!s->session) {
556 ret = -EINVAL;
5f0c39e5 557 session_error_setg(errp, s, "failed to initialize libssh2 session");
0a12ec87
RJ
558 goto err;
559 }
560
561#if TRACE_LIBSSH2 != 0
562 libssh2_trace(s->session, TRACE_LIBSSH2);
563#endif
564
565 r = libssh2_session_handshake(s->session, s->sock);
566 if (r != 0) {
567 ret = -EINVAL;
5f0c39e5 568 session_error_setg(errp, s, "failed to establish SSH session");
0a12ec87
RJ
569 goto err;
570 }
571
572 /* Check the remote host's key against known_hosts. */
5f0c39e5 573 ret = check_host_key(s, host, port, host_key_check, errp);
0a12ec87
RJ
574 if (ret < 0) {
575 goto err;
576 }
577
578 /* Authenticate. */
5f0c39e5 579 ret = authenticate(s, user, errp);
0a12ec87
RJ
580 if (ret < 0) {
581 goto err;
582 }
583
584 /* Start SFTP. */
585 s->sftp = libssh2_sftp_init(s->session);
586 if (!s->sftp) {
5f0c39e5 587 session_error_setg(errp, s, "failed to initialize sftp handle");
0a12ec87
RJ
588 ret = -EINVAL;
589 goto err;
590 }
591
592 /* Open the remote file. */
593 DPRINTF("opening file %s flags=0x%x creat_mode=0%o",
594 path, ssh_flags, creat_mode);
595 s->sftp_handle = libssh2_sftp_open(s->sftp, path, ssh_flags, creat_mode);
596 if (!s->sftp_handle) {
597 session_error_report(s, "failed to open remote file '%s'", path);
598 ret = -EINVAL;
599 goto err;
600 }
601
602 r = libssh2_sftp_fstat(s->sftp_handle, &s->attrs);
603 if (r < 0) {
604 sftp_error_report(s, "failed to read file attributes");
605 return -EINVAL;
606 }
607
608 /* Delete the options we've used; any not deleted will cause the
609 * block layer to give an error about unused options.
610 */
611 qdict_del(options, "host");
612 qdict_del(options, "port");
613 qdict_del(options, "user");
614 qdict_del(options, "path");
615 qdict_del(options, "host_key_check");
616
0a12ec87
RJ
617 return 0;
618
619 err:
620 if (s->sftp_handle) {
621 libssh2_sftp_close(s->sftp_handle);
622 }
623 s->sftp_handle = NULL;
624 if (s->sftp) {
625 libssh2_sftp_shutdown(s->sftp);
626 }
627 s->sftp = NULL;
628 if (s->session) {
629 libssh2_session_disconnect(s->session,
630 "from qemu ssh client: "
631 "error opening connection");
632 libssh2_session_free(s->session);
633 }
634 s->session = NULL;
0a12ec87
RJ
635
636 return ret;
637}
638
015a1036
HR
639static int ssh_file_open(BlockDriverState *bs, QDict *options, int bdrv_flags,
640 Error **errp)
0a12ec87 641{
5f0c39e5 642 Error *local_err = NULL;
0a12ec87
RJ
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. */
5f0c39e5 655 ret = connect_to_ssh(s, options, ssh_flags, 0, &local_err);
0a12ec87 656 if (ret < 0) {
5f0c39e5
MA
657 qerror_report_err(local_err);
658 error_free(local_err);
0a12ec87
RJ
659 goto err;
660 }
661
662 /* Go non-blocking. */
663 libssh2_session_set_blocking(s->session, 0);
664
665 return 0;
666
667 err:
668 if (s->sock >= 0) {
669 close(s->sock);
670 }
671 s->sock = -1;
672
673 return ret;
674}
675
676static QEMUOptionParameter ssh_create_options[] = {
677 {
678 .name = BLOCK_OPT_SIZE,
679 .type = OPT_SIZE,
680 .help = "Virtual disk size"
681 },
682 { NULL }
683};
684
d5124c00
HR
685static int ssh_create(const char *filename, QEMUOptionParameter *options,
686 Error **errp)
0a12ec87
RJ
687{
688 int r, ret;
689 Error *local_err = NULL;
690 int64_t total_size = 0;
691 QDict *uri_options = NULL;
692 BDRVSSHState s;
693 ssize_t r2;
694 char c[1] = { '\0' };
695
696 ssh_state_init(&s);
697
698 /* Get desired file size. */
699 while (options && options->name) {
700 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
701 total_size = options->value.n;
702 }
703 options++;
704 }
705 DPRINTF("total_size=%" PRIi64, total_size);
706
707 uri_options = qdict_new();
708 r = parse_uri(filename, uri_options, &local_err);
709 if (r < 0) {
710 qerror_report_err(local_err);
711 error_free(local_err);
712 ret = r;
713 goto out;
714 }
715
716 r = connect_to_ssh(&s, uri_options,
717 LIBSSH2_FXF_READ|LIBSSH2_FXF_WRITE|
5f0c39e5
MA
718 LIBSSH2_FXF_CREAT|LIBSSH2_FXF_TRUNC,
719 0644, &local_err);
0a12ec87 720 if (r < 0) {
5f0c39e5
MA
721 qerror_report_err(local_err);
722 error_free(local_err);
0a12ec87
RJ
723 ret = r;
724 goto out;
725 }
726
727 if (total_size > 0) {
728 libssh2_sftp_seek64(s.sftp_handle, total_size-1);
729 r2 = libssh2_sftp_write(s.sftp_handle, c, 1);
730 if (r2 < 0) {
731 sftp_error_report(&s, "truncate failed");
732 ret = -EINVAL;
733 goto out;
734 }
735 s.attrs.filesize = total_size;
736 }
737
738 ret = 0;
739
740 out:
741 ssh_state_free(&s);
742 if (uri_options != NULL) {
743 QDECREF(uri_options);
744 }
745 return ret;
746}
747
748static void ssh_close(BlockDriverState *bs)
749{
750 BDRVSSHState *s = bs->opaque;
751
752 ssh_state_free(s);
753}
754
0b3f21e6
RJ
755static int ssh_has_zero_init(BlockDriverState *bs)
756{
757 BDRVSSHState *s = bs->opaque;
758 /* Assume false, unless we can positively prove it's true. */
759 int has_zero_init = 0;
760
761 if (s->attrs.flags & LIBSSH2_SFTP_ATTR_PERMISSIONS) {
762 if (s->attrs.permissions & LIBSSH2_SFTP_S_IFREG) {
763 has_zero_init = 1;
764 }
765 }
766
767 return has_zero_init;
768}
769
0a12ec87
RJ
770static void restart_coroutine(void *opaque)
771{
772 Coroutine *co = opaque;
773
774 DPRINTF("co=%p", co);
775
776 qemu_coroutine_enter(co, NULL);
777}
778
0a12ec87
RJ
779static coroutine_fn void set_fd_handler(BDRVSSHState *s)
780{
781 int r;
782 IOHandler *rd_handler = NULL, *wr_handler = NULL;
783 Coroutine *co = qemu_coroutine_self();
784
785 r = libssh2_session_block_directions(s->session);
786
787 if (r & LIBSSH2_SESSION_BLOCK_INBOUND) {
788 rd_handler = restart_coroutine;
789 }
790 if (r & LIBSSH2_SESSION_BLOCK_OUTBOUND) {
791 wr_handler = restart_coroutine;
792 }
793
794 DPRINTF("s->sock=%d rd_handler=%p wr_handler=%p", s->sock,
795 rd_handler, wr_handler);
796
f2e5dca4 797 qemu_aio_set_fd_handler(s->sock, rd_handler, wr_handler, co);
0a12ec87
RJ
798}
799
800static coroutine_fn void clear_fd_handler(BDRVSSHState *s)
801{
802 DPRINTF("s->sock=%d", s->sock);
f2e5dca4 803 qemu_aio_set_fd_handler(s->sock, NULL, NULL, NULL);
0a12ec87
RJ
804}
805
806/* A non-blocking call returned EAGAIN, so yield, ensuring the
807 * handlers are set up so that we'll be rescheduled when there is an
808 * interesting event on the socket.
809 */
810static coroutine_fn void co_yield(BDRVSSHState *s)
811{
812 set_fd_handler(s);
813 qemu_coroutine_yield();
814 clear_fd_handler(s);
815}
816
817/* SFTP has a function `libssh2_sftp_seek64' which seeks to a position
818 * in the remote file. Notice that it just updates a field in the
819 * sftp_handle structure, so there is no network traffic and it cannot
820 * fail.
821 *
822 * However, `libssh2_sftp_seek64' does have a catastrophic effect on
823 * performance since it causes the handle to throw away all in-flight
824 * reads and buffered readahead data. Therefore this function tries
825 * to be intelligent about when to call the underlying libssh2 function.
826 */
827#define SSH_SEEK_WRITE 0
828#define SSH_SEEK_READ 1
829#define SSH_SEEK_FORCE 2
830
831static void ssh_seek(BDRVSSHState *s, int64_t offset, int flags)
832{
833 bool op_read = (flags & SSH_SEEK_READ) != 0;
834 bool force = (flags & SSH_SEEK_FORCE) != 0;
835
836 if (force || op_read != s->offset_op_read || offset != s->offset) {
837 DPRINTF("seeking to offset=%" PRIi64, offset);
838 libssh2_sftp_seek64(s->sftp_handle, offset);
839 s->offset = offset;
840 s->offset_op_read = op_read;
841 }
842}
843
844static coroutine_fn int ssh_read(BDRVSSHState *s,
845 int64_t offset, size_t size,
846 QEMUIOVector *qiov)
847{
848 ssize_t r;
849 size_t got;
850 char *buf, *end_of_vec;
851 struct iovec *i;
852
853 DPRINTF("offset=%" PRIi64 " size=%zu", offset, size);
854
855 ssh_seek(s, offset, SSH_SEEK_READ);
856
857 /* This keeps track of the current iovec element ('i'), where we
858 * will write to next ('buf'), and the end of the current iovec
859 * ('end_of_vec').
860 */
861 i = &qiov->iov[0];
862 buf = i->iov_base;
863 end_of_vec = i->iov_base + i->iov_len;
864
865 /* libssh2 has a hard-coded limit of 2000 bytes per request,
866 * although it will also do readahead behind our backs. Therefore
867 * we may have to do repeated reads here until we have read 'size'
868 * bytes.
869 */
870 for (got = 0; got < size; ) {
871 again:
872 DPRINTF("sftp_read buf=%p size=%zu", buf, end_of_vec - buf);
873 r = libssh2_sftp_read(s->sftp_handle, buf, end_of_vec - buf);
874 DPRINTF("sftp_read returned %zd", r);
875
876 if (r == LIBSSH2_ERROR_EAGAIN || r == LIBSSH2_ERROR_TIMEOUT) {
877 co_yield(s);
878 goto again;
879 }
880 if (r < 0) {
881 sftp_error_report(s, "read failed");
882 s->offset = -1;
883 return -EIO;
884 }
885 if (r == 0) {
886 /* EOF: Short read so pad the buffer with zeroes and return it. */
887 qemu_iovec_memset(qiov, got, 0, size - got);
888 return 0;
889 }
890
891 got += r;
892 buf += r;
893 s->offset += r;
894 if (buf >= end_of_vec && got < size) {
895 i++;
896 buf = i->iov_base;
897 end_of_vec = i->iov_base + i->iov_len;
898 }
899 }
900
901 return 0;
902}
903
904static coroutine_fn int ssh_co_readv(BlockDriverState *bs,
905 int64_t sector_num,
906 int nb_sectors, QEMUIOVector *qiov)
907{
908 BDRVSSHState *s = bs->opaque;
909 int ret;
910
911 qemu_co_mutex_lock(&s->lock);
912 ret = ssh_read(s, sector_num * BDRV_SECTOR_SIZE,
913 nb_sectors * BDRV_SECTOR_SIZE, qiov);
914 qemu_co_mutex_unlock(&s->lock);
915
916 return ret;
917}
918
919static int ssh_write(BDRVSSHState *s,
920 int64_t offset, size_t size,
921 QEMUIOVector *qiov)
922{
923 ssize_t r;
924 size_t written;
925 char *buf, *end_of_vec;
926 struct iovec *i;
927
928 DPRINTF("offset=%" PRIi64 " size=%zu", offset, size);
929
930 ssh_seek(s, offset, SSH_SEEK_WRITE);
931
932 /* This keeps track of the current iovec element ('i'), where we
933 * will read from next ('buf'), and the end of the current iovec
934 * ('end_of_vec').
935 */
936 i = &qiov->iov[0];
937 buf = i->iov_base;
938 end_of_vec = i->iov_base + i->iov_len;
939
940 for (written = 0; written < size; ) {
941 again:
942 DPRINTF("sftp_write buf=%p size=%zu", buf, end_of_vec - buf);
943 r = libssh2_sftp_write(s->sftp_handle, buf, end_of_vec - buf);
944 DPRINTF("sftp_write returned %zd", r);
945
946 if (r == LIBSSH2_ERROR_EAGAIN || r == LIBSSH2_ERROR_TIMEOUT) {
947 co_yield(s);
948 goto again;
949 }
950 if (r < 0) {
951 sftp_error_report(s, "write failed");
952 s->offset = -1;
953 return -EIO;
954 }
955 /* The libssh2 API is very unclear about this. A comment in
956 * the code says "nothing was acked, and no EAGAIN was
957 * received!" which apparently means that no data got sent
958 * out, and the underlying channel didn't return any EAGAIN
959 * indication. I think this is a bug in either libssh2 or
960 * OpenSSH (server-side). In any case, forcing a seek (to
961 * discard libssh2 internal buffers), and then trying again
962 * works for me.
963 */
964 if (r == 0) {
965 ssh_seek(s, offset + written, SSH_SEEK_WRITE|SSH_SEEK_FORCE);
966 co_yield(s);
967 goto again;
968 }
969
970 written += r;
971 buf += r;
972 s->offset += r;
973 if (buf >= end_of_vec && written < size) {
974 i++;
975 buf = i->iov_base;
976 end_of_vec = i->iov_base + i->iov_len;
977 }
978
979 if (offset + written > s->attrs.filesize)
980 s->attrs.filesize = offset + written;
981 }
982
983 return 0;
984}
985
986static coroutine_fn int ssh_co_writev(BlockDriverState *bs,
987 int64_t sector_num,
988 int nb_sectors, QEMUIOVector *qiov)
989{
990 BDRVSSHState *s = bs->opaque;
991 int ret;
992
993 qemu_co_mutex_lock(&s->lock);
994 ret = ssh_write(s, sector_num * BDRV_SECTOR_SIZE,
995 nb_sectors * BDRV_SECTOR_SIZE, qiov);
996 qemu_co_mutex_unlock(&s->lock);
997
998 return ret;
999}
1000
9a2d462e
RJ
1001static void unsafe_flush_warning(BDRVSSHState *s, const char *what)
1002{
1003 if (!s->unsafe_flush_warning) {
1004 error_report("warning: ssh server %s does not support fsync",
1005 s->hostport);
1006 if (what) {
1007 error_report("to support fsync, you need %s", what);
1008 }
1009 s->unsafe_flush_warning = true;
1010 }
1011}
1012
1013#ifdef HAS_LIBSSH2_SFTP_FSYNC
1014
1015static coroutine_fn int ssh_flush(BDRVSSHState *s)
1016{
1017 int r;
1018
1019 DPRINTF("fsync");
1020 again:
1021 r = libssh2_sftp_fsync(s->sftp_handle);
1022 if (r == LIBSSH2_ERROR_EAGAIN || r == LIBSSH2_ERROR_TIMEOUT) {
1023 co_yield(s);
1024 goto again;
1025 }
1026 if (r == LIBSSH2_ERROR_SFTP_PROTOCOL &&
1027 libssh2_sftp_last_error(s->sftp) == LIBSSH2_FX_OP_UNSUPPORTED) {
1028 unsafe_flush_warning(s, "OpenSSH >= 6.3");
1029 return 0;
1030 }
1031 if (r < 0) {
1032 sftp_error_report(s, "fsync failed");
1033 return -EIO;
1034 }
1035
1036 return 0;
1037}
1038
1039static coroutine_fn int ssh_co_flush(BlockDriverState *bs)
1040{
1041 BDRVSSHState *s = bs->opaque;
1042 int ret;
1043
1044 qemu_co_mutex_lock(&s->lock);
1045 ret = ssh_flush(s);
1046 qemu_co_mutex_unlock(&s->lock);
1047
1048 return ret;
1049}
1050
1051#else /* !HAS_LIBSSH2_SFTP_FSYNC */
1052
1053static coroutine_fn int ssh_co_flush(BlockDriverState *bs)
1054{
1055 BDRVSSHState *s = bs->opaque;
1056
1057 unsafe_flush_warning(s, "libssh2 >= 1.4.4");
1058 return 0;
1059}
1060
1061#endif /* !HAS_LIBSSH2_SFTP_FSYNC */
1062
0a12ec87
RJ
1063static int64_t ssh_getlength(BlockDriverState *bs)
1064{
1065 BDRVSSHState *s = bs->opaque;
1066 int64_t length;
1067
1068 /* Note we cannot make a libssh2 call here. */
1069 length = (int64_t) s->attrs.filesize;
1070 DPRINTF("length=%" PRIi64, length);
1071
1072 return length;
1073}
1074
1075static BlockDriver bdrv_ssh = {
1076 .format_name = "ssh",
1077 .protocol_name = "ssh",
1078 .instance_size = sizeof(BDRVSSHState),
1079 .bdrv_parse_filename = ssh_parse_filename,
1080 .bdrv_file_open = ssh_file_open,
1081 .bdrv_create = ssh_create,
1082 .bdrv_close = ssh_close,
0b3f21e6 1083 .bdrv_has_zero_init = ssh_has_zero_init,
0a12ec87
RJ
1084 .bdrv_co_readv = ssh_co_readv,
1085 .bdrv_co_writev = ssh_co_writev,
1086 .bdrv_getlength = ssh_getlength,
9a2d462e 1087 .bdrv_co_flush_to_disk = ssh_co_flush,
0a12ec87
RJ
1088 .create_options = ssh_create_options,
1089};
1090
1091static void bdrv_ssh_init(void)
1092{
1093 int r;
1094
1095 r = libssh2_init(0);
1096 if (r != 0) {
1097 fprintf(stderr, "libssh2 initialization failed, %d\n", r);
1098 exit(EXIT_FAILURE);
1099 }
1100
1101 bdrv_register(&bdrv_ssh);
1102}
1103
1104block_init(bdrv_ssh_init);