]> git.proxmox.com Git - mirror_qemu.git/blame - block/ssh.c
Merge tag 'block-pull-request' of https://gitlab.com/stefanha/qemu into staging
[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
80c71a24 25#include "qemu/osdep.h"
0a12ec87 26
b10d49d7
PT
27#include <libssh/libssh.h>
28#include <libssh/sftp.h>
0a12ec87 29
e2c1c34f 30#include "block/block-io.h"
0a12ec87 31#include "block/block_int.h"
609f45ea 32#include "block/qdict.h"
da34e65c 33#include "qapi/error.h"
d49b6836 34#include "qemu/error-report.h"
0b8fa32f 35#include "qemu/module.h"
922a01a0 36#include "qemu/option.h"
856dfd8a 37#include "qemu/ctype.h"
0da5b8ef 38#include "qemu/cutils.h"
0a12ec87
RJ
39#include "qemu/sockets.h"
40#include "qemu/uri.h"
9af23989 41#include "qapi/qapi-visit-sockets.h"
16e4bdb1 42#include "qapi/qapi-visit-block-core.h"
452fcdbc 43#include "qapi/qmp/qdict.h"
d49b6836 44#include "qapi/qmp/qstring.h"
0da5b8ef
AA
45#include "qapi/qobject-input-visitor.h"
46#include "qapi/qobject-output-visitor.h"
023908a2 47#include "trace.h"
0a12ec87 48
023908a2 49/*
b10d49d7
PT
50 * TRACE_LIBSSH=<level> enables tracing in libssh itself.
51 * The meaning of <level> is described here:
52 * http://api.libssh.org/master/group__libssh__log.html
0a12ec87 53 */
b10d49d7 54#define TRACE_LIBSSH 0 /* see: SSH_LOG_* */
0a12ec87 55
0a12ec87
RJ
56typedef struct BDRVSSHState {
57 /* Coroutine. */
58 CoMutex lock;
59
60 /* SSH connection. */
61 int sock; /* socket */
b10d49d7
PT
62 ssh_session session; /* ssh session */
63 sftp_session sftp; /* sftp session */
64 sftp_file sftp_handle; /* sftp remote file handle */
0a12ec87 65
b10d49d7
PT
66 /*
67 * File attributes at open. We try to keep the .size field
0a12ec87
RJ
68 * updated if it changes (eg by writing at the end of the file).
69 */
b10d49d7 70 sftp_attributes attrs;
9a2d462e 71
0da5b8ef
AA
72 InetSocketAddress *inet;
73
9a2d462e 74 /* Used to warn if 'flush' is not supported. */
9a2d462e 75 bool unsafe_flush_warning;
b8c1f901
HR
76
77 /*
78 * Store the user name for ssh_refresh_filename() because the
79 * default depends on the system you are on -- therefore, when we
80 * generate a filename, it should always contain the user name we
81 * are actually using.
82 */
83 char *user;
0a12ec87
RJ
84} BDRVSSHState;
85
86static void ssh_state_init(BDRVSSHState *s)
87{
88 memset(s, 0, sizeof *s);
89 s->sock = -1;
0a12ec87
RJ
90 qemu_co_mutex_init(&s->lock);
91}
92
93static void ssh_state_free(BDRVSSHState *s)
94{
b8c1f901
HR
95 g_free(s->user);
96
b10d49d7
PT
97 if (s->attrs) {
98 sftp_attributes_free(s->attrs);
99 }
0a12ec87 100 if (s->sftp_handle) {
b10d49d7 101 sftp_close(s->sftp_handle);
0a12ec87
RJ
102 }
103 if (s->sftp) {
b10d49d7 104 sftp_free(s->sftp);
0a12ec87
RJ
105 }
106 if (s->session) {
b10d49d7
PT
107 ssh_disconnect(s->session);
108 ssh_free(s->session); /* This frees s->sock */
0a12ec87
RJ
109 }
110}
111
9edc6313 112static void G_GNUC_PRINTF(3, 4)
01c2b265
MA
113session_error_setg(Error **errp, BDRVSSHState *s, const char *fs, ...)
114{
115 va_list args;
116 char *msg;
117
118 va_start(args, fs);
119 msg = g_strdup_vprintf(fs, args);
120 va_end(args);
121
122 if (s->session) {
b10d49d7 123 const char *ssh_err;
01c2b265
MA
124 int ssh_err_code;
125
b10d49d7
PT
126 /* This is not an errno. See <libssh/libssh.h>. */
127 ssh_err = ssh_get_error(s->session);
128 ssh_err_code = ssh_get_error_code(s->session);
129 error_setg(errp, "%s: %s (libssh error code: %d)",
01c2b265
MA
130 msg, ssh_err, ssh_err_code);
131 } else {
132 error_setg(errp, "%s", msg);
133 }
134 g_free(msg);
135}
136
9edc6313 137static void G_GNUC_PRINTF(3, 4)
5496fb1a 138sftp_error_setg(Error **errp, BDRVSSHState *s, const char *fs, ...)
0a12ec87
RJ
139{
140 va_list args;
5496fb1a 141 char *msg;
0a12ec87
RJ
142
143 va_start(args, fs);
5496fb1a
MA
144 msg = g_strdup_vprintf(fs, args);
145 va_end(args);
0a12ec87 146
5496fb1a 147 if (s->sftp) {
b10d49d7 148 const char *ssh_err;
0a12ec87 149 int ssh_err_code;
b10d49d7 150 int sftp_err_code;
0a12ec87 151
b10d49d7
PT
152 /* This is not an errno. See <libssh/libssh.h>. */
153 ssh_err = ssh_get_error(s->session);
154 ssh_err_code = ssh_get_error_code(s->session);
155 /* See <libssh/sftp.h>. */
156 sftp_err_code = sftp_get_error(s->sftp);
0a12ec87 157
5496fb1a 158 error_setg(errp,
b10d49d7 159 "%s: %s (libssh error code: %d, sftp error code: %d)",
5496fb1a
MA
160 msg, ssh_err, ssh_err_code, sftp_err_code);
161 } else {
162 error_setg(errp, "%s", msg);
163 }
164 g_free(msg);
0a12ec87
RJ
165}
166
6b3048ce 167static void sftp_error_trace(BDRVSSHState *s, const char *op)
0a12ec87 168{
b10d49d7 169 const char *ssh_err;
6b3048ce 170 int ssh_err_code;
b10d49d7 171 int sftp_err_code;
0a12ec87 172
b10d49d7
PT
173 /* This is not an errno. See <libssh/libssh.h>. */
174 ssh_err = ssh_get_error(s->session);
175 ssh_err_code = ssh_get_error_code(s->session);
176 /* See <libssh/sftp.h>. */
177 sftp_err_code = sftp_get_error(s->sftp);
0a12ec87 178
6b3048ce 179 trace_sftp_error(op, ssh_err, ssh_err_code, sftp_err_code);
0a12ec87
RJ
180}
181
182static int parse_uri(const char *filename, QDict *options, Error **errp)
183{
184 URI *uri = NULL;
eab2ac9d 185 QueryParams *qp;
1059f1bb 186 char *port_str;
0a12ec87
RJ
187 int i;
188
189 uri = uri_parse(filename);
190 if (!uri) {
191 return -EINVAL;
192 }
193
f69165a8 194 if (g_strcmp0(uri->scheme, "ssh") != 0) {
0a12ec87
RJ
195 error_setg(errp, "URI scheme must be 'ssh'");
196 goto err;
197 }
198
199 if (!uri->server || strcmp(uri->server, "") == 0) {
200 error_setg(errp, "missing hostname in URI");
201 goto err;
202 }
203
204 if (!uri->path || strcmp(uri->path, "") == 0) {
205 error_setg(errp, "missing remote path in URI");
206 goto err;
207 }
208
209 qp = query_params_parse(uri->query);
210 if (!qp) {
211 error_setg(errp, "could not parse query parameters");
212 goto err;
213 }
214
215 if(uri->user && strcmp(uri->user, "") != 0) {
46f5ac20 216 qdict_put_str(options, "user", uri->user);
0a12ec87
RJ
217 }
218
46f5ac20 219 qdict_put_str(options, "server.host", uri->server);
0a12ec87 220
1059f1bb 221 port_str = g_strdup_printf("%d", uri->port ?: 22);
46f5ac20 222 qdict_put_str(options, "server.port", port_str);
1059f1bb 223 g_free(port_str);
0a12ec87 224
46f5ac20 225 qdict_put_str(options, "path", uri->path);
0a12ec87
RJ
226
227 /* Pick out any query parameters that we understand, and ignore
228 * the rest.
229 */
230 for (i = 0; i < qp->n; ++i) {
231 if (strcmp(qp->p[i].name, "host_key_check") == 0) {
46f5ac20 232 qdict_put_str(options, "host_key_check", qp->p[i].value);
0a12ec87
RJ
233 }
234 }
235
236 query_params_free(qp);
237 uri_free(uri);
238 return 0;
239
240 err:
c2615bdf 241 uri_free(uri);
0a12ec87
RJ
242 return -EINVAL;
243}
244
89dbe180
AA
245static bool ssh_has_filename_options_conflict(QDict *options, Error **errp)
246{
247 const QDictEntry *qe;
248
249 for (qe = qdict_first(options); qe; qe = qdict_next(options, qe)) {
250 if (!strcmp(qe->key, "host") ||
251 !strcmp(qe->key, "port") ||
252 !strcmp(qe->key, "path") ||
253 !strcmp(qe->key, "user") ||
0da5b8ef
AA
254 !strcmp(qe->key, "host_key_check") ||
255 strstart(qe->key, "server.", NULL))
89dbe180
AA
256 {
257 error_setg(errp, "Option '%s' cannot be used with a file name",
258 qe->key);
259 return true;
260 }
261 }
262
263 return false;
264}
265
0a12ec87
RJ
266static void ssh_parse_filename(const char *filename, QDict *options,
267 Error **errp)
268{
89dbe180 269 if (ssh_has_filename_options_conflict(options, errp)) {
0a12ec87
RJ
270 return;
271 }
272
273 parse_uri(filename, options, errp);
274}
275
b10d49d7 276static int check_host_key_knownhosts(BDRVSSHState *s, Error **errp)
0a12ec87 277{
b10d49d7 278 int ret;
b10d49d7
PT
279 enum ssh_known_hosts_e state;
280 int r;
281 ssh_key pubkey;
282 enum ssh_keytypes_e pubkey_type;
283 unsigned char *server_hash = NULL;
284 size_t server_hash_len;
285 char *fingerprint = NULL;
286
287 state = ssh_session_is_known_server(s->session);
288 trace_ssh_server_status(state);
289
290 switch (state) {
291 case SSH_KNOWN_HOSTS_OK:
292 /* OK */
293 trace_ssh_check_host_key_knownhosts();
294 break;
295 case SSH_KNOWN_HOSTS_CHANGED:
0a12ec87 296 ret = -EINVAL;
b10d49d7
PT
297 r = ssh_get_server_publickey(s->session, &pubkey);
298 if (r == 0) {
299 r = ssh_get_publickey_hash(pubkey, SSH_PUBLICKEY_HASH_SHA256,
300 &server_hash, &server_hash_len);
301 pubkey_type = ssh_key_type(pubkey);
302 ssh_key_free(pubkey);
303 }
304 if (r == 0) {
305 fingerprint = ssh_get_fingerprint_hash(SSH_PUBLICKEY_HASH_SHA256,
306 server_hash,
307 server_hash_len);
308 ssh_clean_pubkey_hash(&server_hash);
309 }
310 if (fingerprint) {
311 error_setg(errp,
312 "host key (%s key with fingerprint %s) does not match "
313 "the one in known_hosts; this may be a possible attack",
314 ssh_key_type_to_char(pubkey_type), fingerprint);
315 ssh_string_free_char(fingerprint);
316 } else {
317 error_setg(errp,
318 "host key does not match the one in known_hosts; this "
319 "may be a possible attack");
320 }
0a12ec87 321 goto out;
b10d49d7 322 case SSH_KNOWN_HOSTS_OTHER:
0a12ec87 323 ret = -EINVAL;
b10d49d7
PT
324 error_setg(errp,
325 "host key for this server not found, another type exists");
326 goto out;
327 case SSH_KNOWN_HOSTS_UNKNOWN:
328 ret = -EINVAL;
329 error_setg(errp, "no host key was found in known_hosts");
330 goto out;
331 case SSH_KNOWN_HOSTS_NOT_FOUND:
332 ret = -ENOENT;
333 error_setg(errp, "known_hosts file not found");
334 goto out;
335 case SSH_KNOWN_HOSTS_ERROR:
336 ret = -EINVAL;
337 error_setg(errp, "error while checking the host");
338 goto out;
339 default:
340 ret = -EINVAL;
341 error_setg(errp, "error while checking for known server (%d)", state);
0a12ec87
RJ
342 goto out;
343 }
0a12ec87
RJ
344
345 /* known_hosts checking successful. */
346 ret = 0;
347
348 out:
0a12ec87
RJ
349 return ret;
350}
351
352static unsigned hex2decimal(char ch)
353{
354 if (ch >= '0' && ch <= '9') {
355 return (ch - '0');
356 } else if (ch >= 'a' && ch <= 'f') {
357 return 10 + (ch - 'a');
358 } else if (ch >= 'A' && ch <= 'F') {
359 return 10 + (ch - 'A');
360 }
361
362 return -1;
363}
364
365/* Compare the binary fingerprint (hash of host key) with the
366 * host_key_check parameter.
367 */
368static int compare_fingerprint(const unsigned char *fingerprint, size_t len,
369 const char *host_key_check)
370{
371 unsigned c;
372
373 while (len > 0) {
374 while (*host_key_check == ':')
375 host_key_check++;
376 if (!qemu_isxdigit(host_key_check[0]) ||
377 !qemu_isxdigit(host_key_check[1]))
378 return 1;
379 c = hex2decimal(host_key_check[0]) * 16 +
380 hex2decimal(host_key_check[1]);
381 if (c - *fingerprint != 0)
382 return c - *fingerprint;
383 fingerprint++;
384 len--;
385 host_key_check += 2;
386 }
387 return *host_key_check - '\0';
388}
389
e3296cc7
DB
390static char *format_fingerprint(const unsigned char *fingerprint, size_t len)
391{
392 static const char *hex = "0123456789abcdef";
393 char *ret = g_new0(char, (len * 2) + 1);
394 for (size_t i = 0; i < len; i++) {
395 ret[i * 2] = hex[((fingerprint[i] >> 4) & 0xf)];
396 ret[(i * 2) + 1] = hex[(fingerprint[i] & 0xf)];
397 }
398 ret[len * 2] = '\0';
399 return ret;
400}
401
0a12ec87
RJ
402static int
403check_host_key_hash(BDRVSSHState *s, const char *hash,
e3296cc7
DB
404 enum ssh_publickey_hash_type type, const char *typestr,
405 Error **errp)
0a12ec87 406{
b10d49d7
PT
407 int r;
408 ssh_key pubkey;
409 unsigned char *server_hash;
410 size_t server_hash_len;
e3296cc7 411 const char *keytype;
b10d49d7 412
b10d49d7 413 r = ssh_get_server_publickey(s->session, &pubkey);
b10d49d7 414 if (r != SSH_OK) {
01c2b265 415 session_error_setg(errp, s, "failed to read remote host key");
0a12ec87
RJ
416 return -EINVAL;
417 }
418
e3296cc7
DB
419 keytype = ssh_key_type_to_char(ssh_key_type(pubkey));
420
b10d49d7
PT
421 r = ssh_get_publickey_hash(pubkey, type, &server_hash, &server_hash_len);
422 ssh_key_free(pubkey);
423 if (r != 0) {
424 session_error_setg(errp, s,
425 "failed reading the hash of the server SSH key");
426 return -EINVAL;
427 }
428
429 r = compare_fingerprint(server_hash, server_hash_len, hash);
b10d49d7 430 if (r != 0) {
e3296cc7
DB
431 g_autofree char *server_fp = format_fingerprint(server_hash,
432 server_hash_len);
433 error_setg(errp, "remote host %s key fingerprint '%s:%s' "
434 "does not match host_key_check '%s:%s'",
435 keytype, typestr, server_fp, typestr, hash);
436 ssh_clean_pubkey_hash(&server_hash);
0a12ec87
RJ
437 return -EPERM;
438 }
e3296cc7 439 ssh_clean_pubkey_hash(&server_hash);
0a12ec87
RJ
440
441 return 0;
442}
443
b10d49d7 444static int check_host_key(BDRVSSHState *s, SshHostKeyCheck *hkc, Error **errp)
0a12ec87 445{
ec2f5418 446 SshHostKeyCheckMode mode;
0a12ec87 447
ec2f5418
KW
448 if (hkc) {
449 mode = hkc->mode;
450 } else {
451 mode = SSH_HOST_KEY_CHECK_MODE_KNOWN_HOSTS;
0a12ec87
RJ
452 }
453
ec2f5418
KW
454 switch (mode) {
455 case SSH_HOST_KEY_CHECK_MODE_NONE:
456 return 0;
457 case SSH_HOST_KEY_CHECK_MODE_HASH:
458 if (hkc->u.hash.type == SSH_HOST_KEY_CHECK_HASH_TYPE_MD5) {
459 return check_host_key_hash(s, hkc->u.hash.hash,
e3296cc7
DB
460 SSH_PUBLICKEY_HASH_MD5, "md5",
461 errp);
ec2f5418
KW
462 } else if (hkc->u.hash.type == SSH_HOST_KEY_CHECK_HASH_TYPE_SHA1) {
463 return check_host_key_hash(s, hkc->u.hash.hash,
e3296cc7
DB
464 SSH_PUBLICKEY_HASH_SHA1, "sha1",
465 errp);
bf783261
DB
466 } else if (hkc->u.hash.type == SSH_HOST_KEY_CHECK_HASH_TYPE_SHA256) {
467 return check_host_key_hash(s, hkc->u.hash.hash,
e3296cc7
DB
468 SSH_PUBLICKEY_HASH_SHA256, "sha256",
469 errp);
ec2f5418
KW
470 }
471 g_assert_not_reached();
472 break;
473 case SSH_HOST_KEY_CHECK_MODE_KNOWN_HOSTS:
b10d49d7 474 return check_host_key_knownhosts(s, errp);
ec2f5418
KW
475 default:
476 g_assert_not_reached();
0a12ec87
RJ
477 }
478
0a12ec87
RJ
479 return -EINVAL;
480}
481
b10d49d7 482static int authenticate(BDRVSSHState *s, Error **errp)
0a12ec87
RJ
483{
484 int r, ret;
b10d49d7 485 int method;
0a12ec87 486
b10d49d7
PT
487 /* Try to authenticate with the "none" method. */
488 r = ssh_userauth_none(s->session, NULL);
489 if (r == SSH_AUTH_ERROR) {
0a12ec87 490 ret = -EPERM;
b10d49d7
PT
491 session_error_setg(errp, s, "failed to authenticate using none "
492 "authentication");
0a12ec87 493 goto out;
b10d49d7
PT
494 } else if (r == SSH_AUTH_SUCCESS) {
495 /* Authenticated! */
496 ret = 0;
0a12ec87
RJ
497 goto out;
498 }
499
b10d49d7
PT
500 method = ssh_userauth_list(s->session, NULL);
501 trace_ssh_auth_methods(method);
502
503 /*
504 * Try to authenticate with publickey, using the ssh-agent
505 * if available.
506 */
507 if (method & SSH_AUTH_METHOD_PUBLICKEY) {
508 r = ssh_userauth_publickey_auto(s->session, NULL, NULL);
509 if (r == SSH_AUTH_ERROR) {
0a12ec87 510 ret = -EINVAL;
b10d49d7
PT
511 session_error_setg(errp, s, "failed to authenticate using "
512 "publickey authentication");
0a12ec87 513 goto out;
b10d49d7 514 } else if (r == SSH_AUTH_SUCCESS) {
0a12ec87
RJ
515 /* Authenticated! */
516 ret = 0;
517 goto out;
518 }
0a12ec87
RJ
519 }
520
521 ret = -EPERM;
4618e658
MA
522 error_setg(errp, "failed to authenticate using publickey authentication "
523 "and the identities held by your ssh-agent");
0a12ec87
RJ
524
525 out:
0a12ec87
RJ
526 return ret;
527}
528
8a6a8089
HR
529static QemuOptsList ssh_runtime_opts = {
530 .name = "ssh",
531 .head = QTAILQ_HEAD_INITIALIZER(ssh_runtime_opts.head),
532 .desc = {
533 {
534 .name = "host",
535 .type = QEMU_OPT_STRING,
536 .help = "Host to connect to",
537 },
538 {
539 .name = "port",
540 .type = QEMU_OPT_NUMBER,
541 .help = "Port to connect to",
542 },
ec2f5418
KW
543 {
544 .name = "host_key_check",
545 .type = QEMU_OPT_STRING,
546 .help = "Defines how and what to check the host key against",
547 },
fbd5c4c0 548 { /* end of list */ }
8a6a8089
HR
549 },
550};
551
ec2f5418
KW
552static bool ssh_process_legacy_options(QDict *output_opts,
553 QemuOpts *legacy_opts,
554 Error **errp)
0da5b8ef
AA
555{
556 const char *host = qemu_opt_get(legacy_opts, "host");
557 const char *port = qemu_opt_get(legacy_opts, "port");
ec2f5418 558 const char *host_key_check = qemu_opt_get(legacy_opts, "host_key_check");
0da5b8ef
AA
559
560 if (!host && port) {
561 error_setg(errp, "port may not be used without host");
562 return false;
563 }
564
565 if (host) {
46f5ac20
EB
566 qdict_put_str(output_opts, "server.host", host);
567 qdict_put_str(output_opts, "server.port", port ?: stringify(22));
0da5b8ef
AA
568 }
569
ec2f5418
KW
570 if (host_key_check) {
571 if (strcmp(host_key_check, "no") == 0) {
572 qdict_put_str(output_opts, "host-key-check.mode", "none");
573 } else if (strncmp(host_key_check, "md5:", 4) == 0) {
574 qdict_put_str(output_opts, "host-key-check.mode", "hash");
575 qdict_put_str(output_opts, "host-key-check.type", "md5");
576 qdict_put_str(output_opts, "host-key-check.hash",
577 &host_key_check[4]);
578 } else if (strncmp(host_key_check, "sha1:", 5) == 0) {
579 qdict_put_str(output_opts, "host-key-check.mode", "hash");
580 qdict_put_str(output_opts, "host-key-check.type", "sha1");
581 qdict_put_str(output_opts, "host-key-check.hash",
582 &host_key_check[5]);
ea0f60e6
DB
583 } else if (strncmp(host_key_check, "sha256:", 7) == 0) {
584 qdict_put_str(output_opts, "host-key-check.mode", "hash");
585 qdict_put_str(output_opts, "host-key-check.type", "sha256");
586 qdict_put_str(output_opts, "host-key-check.hash",
587 &host_key_check[7]);
ec2f5418
KW
588 } else if (strcmp(host_key_check, "yes") == 0) {
589 qdict_put_str(output_opts, "host-key-check.mode", "known_hosts");
590 } else {
591 error_setg(errp, "unknown host_key_check setting (%s)",
592 host_key_check);
593 return false;
594 }
595 }
596
0da5b8ef
AA
597 return true;
598}
599
16e4bdb1 600static BlockdevOptionsSsh *ssh_parse_options(QDict *options, Error **errp)
0da5b8ef 601{
16e4bdb1
KW
602 BlockdevOptionsSsh *result = NULL;
603 QemuOpts *opts = NULL;
16e4bdb1
KW
604 const QDictEntry *e;
605 Visitor *v;
606
607 /* Translate legacy options */
608 opts = qemu_opts_create(&ssh_runtime_opts, NULL, 0, &error_abort);
af175e85 609 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
16e4bdb1 610 goto fail;
0da5b8ef
AA
611 }
612
ec2f5418 613 if (!ssh_process_legacy_options(options, opts, errp)) {
16e4bdb1
KW
614 goto fail;
615 }
616
617 /* Create the QAPI object */
af91062e
MA
618 v = qobject_input_visitor_new_flat_confused(options, errp);
619 if (!v) {
16e4bdb1 620 goto fail;
0da5b8ef
AA
621 }
622
b11a093c 623 visit_type_BlockdevOptionsSsh(v, NULL, &result, errp);
16e4bdb1 624 visit_free(v);
b11a093c 625 if (!result) {
16e4bdb1 626 goto fail;
0da5b8ef
AA
627 }
628
16e4bdb1
KW
629 /* Remove the processed options from the QDict (the visitor processes
630 * _all_ options in the QDict) */
631 while ((e = qdict_first(options))) {
632 qdict_del(options, e->key);
633 }
634
635fail:
636 qemu_opts_del(opts);
637 return result;
0da5b8ef
AA
638}
639
375f0b92 640static int connect_to_ssh(BDRVSSHState *s, BlockdevOptionsSsh *opts,
5f0c39e5 641 int ssh_flags, int creat_mode, Error **errp)
0a12ec87
RJ
642{
643 int r, ret;
b10d49d7
PT
644 unsigned int port = 0;
645 int new_sock = -1;
0a12ec87 646
54fde4ff 647 if (opts->user) {
b8c1f901 648 s->user = g_strdup(opts->user);
16e4bdb1 649 } else {
b8c1f901
HR
650 s->user = g_strdup(g_get_user_name());
651 if (!s->user) {
5f0c39e5 652 error_setg_errno(errp, errno, "Can't get user name");
0a12ec87
RJ
653 ret = -errno;
654 goto err;
655 }
656 }
657
0da5b8ef 658 /* Pop the config into our state object, Exit if invalid */
16e4bdb1
KW
659 s->inet = opts->server;
660 opts->server = NULL;
0da5b8ef 661
b10d49d7 662 if (qemu_strtoui(s->inet->port, NULL, 10, &port) < 0) {
0da5b8ef
AA
663 error_setg(errp, "Use only numeric port value");
664 ret = -EINVAL;
665 goto err;
666 }
9a2d462e 667
0a12ec87 668 /* Open the socket and connect. */
b10d49d7
PT
669 new_sock = inet_connect_saddr(s->inet, errp);
670 if (new_sock < 0) {
325e3904 671 ret = -EIO;
0a12ec87
RJ
672 goto err;
673 }
674
b10d49d7
PT
675 /*
676 * Try to disable the Nagle algorithm on TCP sockets to reduce latency,
677 * but do not fail if it cannot be disabled.
678 */
679 r = socket_set_nodelay(new_sock);
680 if (r < 0) {
681 warn_report("can't set TCP_NODELAY for the ssh server %s: %s",
682 s->inet->host, strerror(errno));
683 }
684
0a12ec87 685 /* Create SSH session. */
b10d49d7 686 s->session = ssh_new();
0a12ec87
RJ
687 if (!s->session) {
688 ret = -EINVAL;
b10d49d7 689 session_error_setg(errp, s, "failed to initialize libssh session");
0a12ec87
RJ
690 goto err;
691 }
692
b10d49d7
PT
693 /*
694 * Make sure we are in blocking mode during the connection and
695 * authentication phases.
696 */
697 ssh_set_blocking(s->session, 1);
0a12ec87 698
b10d49d7
PT
699 r = ssh_options_set(s->session, SSH_OPTIONS_USER, s->user);
700 if (r < 0) {
701 ret = -EINVAL;
702 session_error_setg(errp, s,
703 "failed to set the user in the libssh session");
704 goto err;
705 }
706
707 r = ssh_options_set(s->session, SSH_OPTIONS_HOST, s->inet->host);
708 if (r < 0) {
709 ret = -EINVAL;
710 session_error_setg(errp, s,
711 "failed to set the host in the libssh session");
712 goto err;
713 }
714
715 if (port > 0) {
716 r = ssh_options_set(s->session, SSH_OPTIONS_PORT, &port);
717 if (r < 0) {
718 ret = -EINVAL;
719 session_error_setg(errp, s,
720 "failed to set the port in the libssh session");
721 goto err;
722 }
723 }
724
725 r = ssh_options_set(s->session, SSH_OPTIONS_COMPRESSION, "none");
726 if (r < 0) {
727 ret = -EINVAL;
728 session_error_setg(errp, s,
729 "failed to disable the compression in the libssh "
730 "session");
731 goto err;
732 }
733
734 /* Read ~/.ssh/config. */
735 r = ssh_options_parse_config(s->session, NULL);
736 if (r < 0) {
737 ret = -EINVAL;
738 session_error_setg(errp, s, "failed to parse ~/.ssh/config");
739 goto err;
740 }
741
742 r = ssh_options_set(s->session, SSH_OPTIONS_FD, &new_sock);
743 if (r < 0) {
744 ret = -EINVAL;
745 session_error_setg(errp, s,
746 "failed to set the socket in the libssh session");
747 goto err;
748 }
749 /* libssh took ownership of the socket. */
750 s->sock = new_sock;
751 new_sock = -1;
752
753 /* Connect. */
754 r = ssh_connect(s->session);
755 if (r != SSH_OK) {
0a12ec87 756 ret = -EINVAL;
5f0c39e5 757 session_error_setg(errp, s, "failed to establish SSH session");
0a12ec87
RJ
758 goto err;
759 }
760
761 /* Check the remote host's key against known_hosts. */
b10d49d7 762 ret = check_host_key(s, opts->host_key_check, errp);
0a12ec87
RJ
763 if (ret < 0) {
764 goto err;
765 }
766
767 /* Authenticate. */
b10d49d7 768 ret = authenticate(s, errp);
0a12ec87
RJ
769 if (ret < 0) {
770 goto err;
771 }
772
773 /* Start SFTP. */
b10d49d7 774 s->sftp = sftp_new(s->session);
0a12ec87 775 if (!s->sftp) {
b10d49d7
PT
776 session_error_setg(errp, s, "failed to create sftp handle");
777 ret = -EINVAL;
778 goto err;
779 }
780
781 r = sftp_init(s->sftp);
782 if (r < 0) {
783 sftp_error_setg(errp, s, "failed to initialize sftp handle");
0a12ec87
RJ
784 ret = -EINVAL;
785 goto err;
786 }
787
788 /* Open the remote file. */
023908a2 789 trace_ssh_connect_to_ssh(opts->path, ssh_flags, creat_mode);
b10d49d7 790 s->sftp_handle = sftp_open(s->sftp, opts->path, ssh_flags, creat_mode);
0a12ec87 791 if (!s->sftp_handle) {
b10d49d7
PT
792 sftp_error_setg(errp, s, "failed to open remote file '%s'",
793 opts->path);
0a12ec87
RJ
794 ret = -EINVAL;
795 goto err;
796 }
797
b10d49d7
PT
798 /* Make sure the SFTP file is handled in blocking mode. */
799 sftp_file_set_blocking(s->sftp_handle);
800
801 s->attrs = sftp_fstat(s->sftp_handle);
802 if (!s->attrs) {
5496fb1a 803 sftp_error_setg(errp, s, "failed to read file attributes");
0a12ec87
RJ
804 return -EINVAL;
805 }
806
0a12ec87
RJ
807 return 0;
808
809 err:
b10d49d7
PT
810 if (s->attrs) {
811 sftp_attributes_free(s->attrs);
812 }
813 s->attrs = NULL;
0a12ec87 814 if (s->sftp_handle) {
b10d49d7 815 sftp_close(s->sftp_handle);
0a12ec87
RJ
816 }
817 s->sftp_handle = NULL;
818 if (s->sftp) {
b10d49d7 819 sftp_free(s->sftp);
0a12ec87
RJ
820 }
821 s->sftp = NULL;
822 if (s->session) {
b10d49d7
PT
823 ssh_disconnect(s->session);
824 ssh_free(s->session);
0a12ec87
RJ
825 }
826 s->session = NULL;
b10d49d7
PT
827 s->sock = -1;
828 if (new_sock >= 0) {
829 close(new_sock);
830 }
0a12ec87
RJ
831
832 return ret;
833}
834
015a1036
HR
835static int ssh_file_open(BlockDriverState *bs, QDict *options, int bdrv_flags,
836 Error **errp)
0a12ec87
RJ
837{
838 BDRVSSHState *s = bs->opaque;
375f0b92 839 BlockdevOptionsSsh *opts;
0a12ec87
RJ
840 int ret;
841 int ssh_flags;
842
843 ssh_state_init(s);
844
b10d49d7 845 ssh_flags = 0;
0a12ec87 846 if (bdrv_flags & BDRV_O_RDWR) {
b10d49d7
PT
847 ssh_flags |= O_RDWR;
848 } else {
849 ssh_flags |= O_RDONLY;
0a12ec87
RJ
850 }
851
375f0b92
KW
852 opts = ssh_parse_options(options, errp);
853 if (opts == NULL) {
854 return -EINVAL;
855 }
856
0a12ec87 857 /* Start up SSH. */
375f0b92 858 ret = connect_to_ssh(s, opts, ssh_flags, 0, errp);
0a12ec87
RJ
859 if (ret < 0) {
860 goto err;
861 }
862
863 /* Go non-blocking. */
b10d49d7 864 ssh_set_blocking(s->session, 0);
0a12ec87 865
be9c9404
EB
866 if (s->attrs->type == SSH_FILEXFER_TYPE_REGULAR) {
867 bs->supported_truncate_flags = BDRV_REQ_ZERO_WRITE;
868 }
869
375f0b92
KW
870 qapi_free_BlockdevOptionsSsh(opts);
871
0a12ec87
RJ
872 return 0;
873
874 err:
375f0b92
KW
875 qapi_free_BlockdevOptionsSsh(opts);
876
0a12ec87
RJ
877 return ret;
878}
879
bd8e0e32 880/* Note: This is a blocking operation */
2b12a756
HR
881static int ssh_grow_file(BDRVSSHState *s, int64_t offset, Error **errp)
882{
883 ssize_t ret;
884 char c[1] = { '\0' };
b10d49d7 885 int was_blocking = ssh_is_blocking(s->session);
2b12a756
HR
886
887 /* offset must be strictly greater than the current size so we do
888 * not overwrite anything */
b10d49d7 889 assert(offset > 0 && offset > s->attrs->size);
2b12a756 890
b10d49d7 891 ssh_set_blocking(s->session, 1);
bd8e0e32 892
b10d49d7
PT
893 sftp_seek64(s->sftp_handle, offset - 1);
894 ret = sftp_write(s->sftp_handle, c, 1);
bd8e0e32 895
b10d49d7 896 ssh_set_blocking(s->session, was_blocking);
bd8e0e32 897
2b12a756
HR
898 if (ret < 0) {
899 sftp_error_setg(errp, s, "Failed to grow file");
900 return -EIO;
901 }
902
b10d49d7 903 s->attrs->size = offset;
2b12a756
HR
904 return 0;
905}
906
766181fe
CL
907static QemuOptsList ssh_create_opts = {
908 .name = "ssh-create-opts",
909 .head = QTAILQ_HEAD_INITIALIZER(ssh_create_opts.head),
910 .desc = {
911 {
912 .name = BLOCK_OPT_SIZE,
913 .type = QEMU_OPT_SIZE,
914 .help = "Virtual disk size"
915 },
916 { /* end of list */ }
917 }
0a12ec87
RJ
918};
919
4906da7e
KW
920static int ssh_co_create(BlockdevCreateOptions *options, Error **errp)
921{
922 BlockdevCreateOptionsSsh *opts = &options->u.ssh;
923 BDRVSSHState s;
924 int ret;
925
926 assert(options->driver == BLOCKDEV_DRIVER_SSH);
927
928 ssh_state_init(&s);
929
930 ret = connect_to_ssh(&s, opts->location,
b10d49d7 931 O_RDWR | O_CREAT | O_TRUNC,
4906da7e
KW
932 0644, errp);
933 if (ret < 0) {
934 goto fail;
935 }
936
937 if (opts->size > 0) {
938 ret = ssh_grow_file(&s, opts->size, errp);
939 if (ret < 0) {
940 goto fail;
941 }
942 }
943
944 ret = 0;
945fail:
946 ssh_state_free(&s);
947 return ret;
948}
949
b92902df
ML
950static int coroutine_fn ssh_co_create_opts(BlockDriver *drv,
951 const char *filename,
952 QemuOpts *opts,
efc75e2a 953 Error **errp)
0a12ec87 954{
4906da7e
KW
955 BlockdevCreateOptions *create_options;
956 BlockdevCreateOptionsSsh *ssh_opts;
957 int ret;
0a12ec87 958 QDict *uri_options = NULL;
0a12ec87 959
4906da7e
KW
960 create_options = g_new0(BlockdevCreateOptions, 1);
961 create_options->driver = BLOCKDEV_DRIVER_SSH;
962 ssh_opts = &create_options->u.ssh;
0a12ec87
RJ
963
964 /* Get desired file size. */
4906da7e
KW
965 ssh_opts->size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
966 BDRV_SECTOR_SIZE);
023908a2 967 trace_ssh_co_create_opts(ssh_opts->size);
0a12ec87
RJ
968
969 uri_options = qdict_new();
4906da7e
KW
970 ret = parse_uri(filename, uri_options, errp);
971 if (ret < 0) {
0a12ec87
RJ
972 goto out;
973 }
974
4906da7e
KW
975 ssh_opts->location = ssh_parse_options(uri_options, errp);
976 if (ssh_opts->location == NULL) {
375f0b92
KW
977 ret = -EINVAL;
978 goto out;
979 }
980
4906da7e 981 ret = ssh_co_create(create_options, errp);
0a12ec87
RJ
982
983 out:
cb3e7f08 984 qobject_unref(uri_options);
4906da7e 985 qapi_free_BlockdevCreateOptions(create_options);
0a12ec87
RJ
986 return ret;
987}
988
989static void ssh_close(BlockDriverState *bs)
990{
991 BDRVSSHState *s = bs->opaque;
992
993 ssh_state_free(s);
994}
995
0b3f21e6
RJ
996static int ssh_has_zero_init(BlockDriverState *bs)
997{
998 BDRVSSHState *s = bs->opaque;
999 /* Assume false, unless we can positively prove it's true. */
1000 int has_zero_init = 0;
1001
b10d49d7
PT
1002 if (s->attrs->type == SSH_FILEXFER_TYPE_REGULAR) {
1003 has_zero_init = 1;
0b3f21e6
RJ
1004 }
1005
1006 return has_zero_init;
1007}
1008
5aca18a4
PB
1009typedef struct BDRVSSHRestart {
1010 BlockDriverState *bs;
1011 Coroutine *co;
1012} BDRVSSHRestart;
1013
0a12ec87
RJ
1014static void restart_coroutine(void *opaque)
1015{
5aca18a4
PB
1016 BDRVSSHRestart *restart = opaque;
1017 BlockDriverState *bs = restart->bs;
1018 BDRVSSHState *s = bs->opaque;
1019 AioContext *ctx = bdrv_get_aio_context(bs);
0a12ec87 1020
023908a2 1021 trace_ssh_restart_coroutine(restart->co);
60f782b6 1022 aio_set_fd_handler(ctx, s->sock, NULL, NULL, NULL, NULL, NULL);
0a12ec87 1023
5aca18a4 1024 aio_co_wake(restart->co);
0a12ec87
RJ
1025}
1026
9d456654
PB
1027/* A non-blocking call returned EAGAIN, so yield, ensuring the
1028 * handlers are set up so that we'll be rescheduled when there is an
1029 * interesting event on the socket.
1030 */
1031static coroutine_fn void co_yield(BDRVSSHState *s, BlockDriverState *bs)
0a12ec87
RJ
1032{
1033 int r;
1034 IOHandler *rd_handler = NULL, *wr_handler = NULL;
5aca18a4
PB
1035 BDRVSSHRestart restart = {
1036 .bs = bs,
1037 .co = qemu_coroutine_self()
1038 };
0a12ec87 1039
b10d49d7 1040 r = ssh_get_poll_flags(s->session);
0a12ec87 1041
b10d49d7 1042 if (r & SSH_READ_PENDING) {
0a12ec87
RJ
1043 rd_handler = restart_coroutine;
1044 }
b10d49d7 1045 if (r & SSH_WRITE_PENDING) {
0a12ec87
RJ
1046 wr_handler = restart_coroutine;
1047 }
1048
023908a2 1049 trace_ssh_co_yield(s->sock, rd_handler, wr_handler);
0a12ec87 1050
2af0b200 1051 aio_set_fd_handler(bdrv_get_aio_context(bs), s->sock,
60f782b6 1052 rd_handler, wr_handler, NULL, NULL, &restart);
0a12ec87 1053 qemu_coroutine_yield();
023908a2 1054 trace_ssh_co_yield_back(s->sock);
0a12ec87
RJ
1055}
1056
2af0b200 1057static coroutine_fn int ssh_read(BDRVSSHState *s, BlockDriverState *bs,
0a12ec87
RJ
1058 int64_t offset, size_t size,
1059 QEMUIOVector *qiov)
1060{
1061 ssize_t r;
1062 size_t got;
1063 char *buf, *end_of_vec;
1064 struct iovec *i;
1065
023908a2 1066 trace_ssh_read(offset, size);
0a12ec87 1067
b10d49d7
PT
1068 trace_ssh_seek(offset);
1069 sftp_seek64(s->sftp_handle, offset);
0a12ec87
RJ
1070
1071 /* This keeps track of the current iovec element ('i'), where we
1072 * will write to next ('buf'), and the end of the current iovec
1073 * ('end_of_vec').
1074 */
1075 i = &qiov->iov[0];
1076 buf = i->iov_base;
1077 end_of_vec = i->iov_base + i->iov_len;
1078
0a12ec87 1079 for (got = 0; got < size; ) {
b10d49d7 1080 size_t request_read_size;
0a12ec87 1081 again:
b10d49d7
PT
1082 /*
1083 * The size of SFTP packets is limited to 32K bytes, so limit
1084 * the amount of data requested to 16K, as libssh currently
1085 * does not handle multiple requests on its own.
1086 */
1087 request_read_size = MIN(end_of_vec - buf, 16384);
1088 trace_ssh_read_buf(buf, end_of_vec - buf, request_read_size);
1089 r = sftp_read(s->sftp_handle, buf, request_read_size);
1090 trace_ssh_read_return(r, sftp_get_error(s->sftp));
0a12ec87 1091
b10d49d7 1092 if (r == SSH_AGAIN) {
2af0b200 1093 co_yield(s, bs);
0a12ec87
RJ
1094 goto again;
1095 }
b10d49d7 1096 if (r == SSH_EOF || (r == 0 && sftp_get_error(s->sftp) == SSH_FX_EOF)) {
0a12ec87
RJ
1097 /* EOF: Short read so pad the buffer with zeroes and return it. */
1098 qemu_iovec_memset(qiov, got, 0, size - got);
1099 return 0;
1100 }
b10d49d7
PT
1101 if (r <= 0) {
1102 sftp_error_trace(s, "read");
1103 return -EIO;
1104 }
0a12ec87
RJ
1105
1106 got += r;
1107 buf += r;
0a12ec87
RJ
1108 if (buf >= end_of_vec && got < size) {
1109 i++;
1110 buf = i->iov_base;
1111 end_of_vec = i->iov_base + i->iov_len;
1112 }
1113 }
1114
1115 return 0;
1116}
1117
1118static coroutine_fn int ssh_co_readv(BlockDriverState *bs,
1119 int64_t sector_num,
1120 int nb_sectors, QEMUIOVector *qiov)
1121{
1122 BDRVSSHState *s = bs->opaque;
1123 int ret;
1124
1125 qemu_co_mutex_lock(&s->lock);
2af0b200 1126 ret = ssh_read(s, bs, sector_num * BDRV_SECTOR_SIZE,
0a12ec87
RJ
1127 nb_sectors * BDRV_SECTOR_SIZE, qiov);
1128 qemu_co_mutex_unlock(&s->lock);
1129
1130 return ret;
1131}
1132
42f6ad79
AF
1133static coroutine_fn int ssh_write(BDRVSSHState *s, BlockDriverState *bs,
1134 int64_t offset, size_t size,
1135 QEMUIOVector *qiov)
0a12ec87
RJ
1136{
1137 ssize_t r;
1138 size_t written;
1139 char *buf, *end_of_vec;
1140 struct iovec *i;
1141
023908a2 1142 trace_ssh_write(offset, size);
0a12ec87 1143
b10d49d7
PT
1144 trace_ssh_seek(offset);
1145 sftp_seek64(s->sftp_handle, offset);
0a12ec87
RJ
1146
1147 /* This keeps track of the current iovec element ('i'), where we
1148 * will read from next ('buf'), and the end of the current iovec
1149 * ('end_of_vec').
1150 */
1151 i = &qiov->iov[0];
1152 buf = i->iov_base;
1153 end_of_vec = i->iov_base + i->iov_len;
1154
1155 for (written = 0; written < size; ) {
b10d49d7 1156 size_t request_write_size;
0a12ec87 1157 again:
b10d49d7
PT
1158 /*
1159 * Avoid too large data packets, as libssh currently does not
1160 * handle multiple requests on its own.
1161 */
1162 request_write_size = MIN(end_of_vec - buf, 131072);
1163 trace_ssh_write_buf(buf, end_of_vec - buf, request_write_size);
1164 r = sftp_write(s->sftp_handle, buf, request_write_size);
1165 trace_ssh_write_return(r, sftp_get_error(s->sftp));
0a12ec87 1166
b10d49d7 1167 if (r == SSH_AGAIN) {
2af0b200 1168 co_yield(s, bs);
0a12ec87
RJ
1169 goto again;
1170 }
1171 if (r < 0) {
6b3048ce 1172 sftp_error_trace(s, "write");
0a12ec87
RJ
1173 return -EIO;
1174 }
0a12ec87
RJ
1175
1176 written += r;
1177 buf += r;
0a12ec87
RJ
1178 if (buf >= end_of_vec && written < size) {
1179 i++;
1180 buf = i->iov_base;
1181 end_of_vec = i->iov_base + i->iov_len;
1182 }
1183
b10d49d7
PT
1184 if (offset + written > s->attrs->size) {
1185 s->attrs->size = offset + written;
1186 }
0a12ec87
RJ
1187 }
1188
1189 return 0;
1190}
1191
1192static coroutine_fn int ssh_co_writev(BlockDriverState *bs,
1193 int64_t sector_num,
e18a58b4
EB
1194 int nb_sectors, QEMUIOVector *qiov,
1195 int flags)
0a12ec87
RJ
1196{
1197 BDRVSSHState *s = bs->opaque;
1198 int ret;
1199
1200 qemu_co_mutex_lock(&s->lock);
2af0b200 1201 ret = ssh_write(s, bs, sector_num * BDRV_SECTOR_SIZE,
0a12ec87
RJ
1202 nb_sectors * BDRV_SECTOR_SIZE, qiov);
1203 qemu_co_mutex_unlock(&s->lock);
1204
1205 return ret;
1206}
1207
9a2d462e
RJ
1208static void unsafe_flush_warning(BDRVSSHState *s, const char *what)
1209{
1210 if (!s->unsafe_flush_warning) {
3dc6f869
AF
1211 warn_report("ssh server %s does not support fsync",
1212 s->inet->host);
9a2d462e
RJ
1213 if (what) {
1214 error_report("to support fsync, you need %s", what);
1215 }
1216 s->unsafe_flush_warning = true;
1217 }
1218}
1219
2af0b200 1220static coroutine_fn int ssh_flush(BDRVSSHState *s, BlockDriverState *bs)
9a2d462e
RJ
1221{
1222 int r;
1223
023908a2 1224 trace_ssh_flush();
b10d49d7
PT
1225
1226 if (!sftp_extension_supported(s->sftp, "fsync@openssh.com", "1")) {
1227 unsafe_flush_warning(s, "OpenSSH >= 6.3");
1228 return 0;
1229 }
9a2d462e 1230 again:
b10d49d7
PT
1231 r = sftp_fsync(s->sftp_handle);
1232 if (r == SSH_AGAIN) {
2af0b200 1233 co_yield(s, bs);
9a2d462e
RJ
1234 goto again;
1235 }
9a2d462e 1236 if (r < 0) {
6b3048ce 1237 sftp_error_trace(s, "fsync");
9a2d462e
RJ
1238 return -EIO;
1239 }
1240
1241 return 0;
1242}
1243
1244static coroutine_fn int ssh_co_flush(BlockDriverState *bs)
1245{
1246 BDRVSSHState *s = bs->opaque;
1247 int ret;
1248
1249 qemu_co_mutex_lock(&s->lock);
2af0b200 1250 ret = ssh_flush(s, bs);
9a2d462e
RJ
1251 qemu_co_mutex_unlock(&s->lock);
1252
1253 return ret;
1254}
1255
c86422c5 1256static int64_t coroutine_fn ssh_co_getlength(BlockDriverState *bs)
0a12ec87
RJ
1257{
1258 BDRVSSHState *s = bs->opaque;
1259 int64_t length;
1260
b10d49d7
PT
1261 /* Note we cannot make a libssh call here. */
1262 length = (int64_t) s->attrs->size;
023908a2 1263 trace_ssh_getlength(length);
0a12ec87
RJ
1264
1265 return length;
1266}
1267
061ca8a3 1268static int coroutine_fn ssh_co_truncate(BlockDriverState *bs, int64_t offset,
c80d8b06 1269 bool exact, PreallocMode prealloc,
92b92799 1270 BdrvRequestFlags flags, Error **errp)
624f3006
HR
1271{
1272 BDRVSSHState *s = bs->opaque;
1273
1274 if (prealloc != PREALLOC_MODE_OFF) {
1275 error_setg(errp, "Unsupported preallocation mode '%s'",
1276 PreallocMode_str(prealloc));
1277 return -ENOTSUP;
1278 }
1279
b10d49d7 1280 if (offset < s->attrs->size) {
624f3006
HR
1281 error_setg(errp, "ssh driver does not support shrinking files");
1282 return -ENOTSUP;
1283 }
1284
b10d49d7 1285 if (offset == s->attrs->size) {
624f3006
HR
1286 return 0;
1287 }
1288
1289 return ssh_grow_file(s, offset, errp);
1290}
1291
b8c1f901
HR
1292static void ssh_refresh_filename(BlockDriverState *bs)
1293{
1294 BDRVSSHState *s = bs->opaque;
1295 const char *path, *host_key_check;
1296 int ret;
1297
1298 /*
1299 * None of these options can be represented in a plain "host:port"
1300 * format, so if any was given, we have to abort.
1301 */
1302 if (s->inet->has_ipv4 || s->inet->has_ipv6 || s->inet->has_to ||
1303 s->inet->has_numeric)
1304 {
1305 return;
1306 }
1307
1308 path = qdict_get_try_str(bs->full_open_options, "path");
1309 assert(path); /* mandatory option */
1310
1311 host_key_check = qdict_get_try_str(bs->full_open_options, "host_key_check");
1312
1313 ret = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
1314 "ssh://%s@%s:%s%s%s%s",
1315 s->user, s->inet->host, s->inet->port, path,
1316 host_key_check ? "?host_key_check=" : "",
1317 host_key_check ?: "");
1318 if (ret >= sizeof(bs->exact_filename)) {
1319 /* An overflow makes the filename unusable, so do not report any */
1320 bs->exact_filename[0] = '\0';
1321 }
1322}
1323
21205c7c
HR
1324static char *ssh_bdrv_dirname(BlockDriverState *bs, Error **errp)
1325{
1326 if (qdict_haskey(bs->full_open_options, "host_key_check")) {
1327 /*
1328 * We cannot generate a simple prefix if we would have to
1329 * append a query string.
1330 */
1331 error_setg(errp,
1332 "Cannot generate a base directory with host_key_check set");
1333 return NULL;
1334 }
1335
1336 if (bs->exact_filename[0] == '\0') {
1337 error_setg(errp, "Cannot generate a base directory for this ssh node");
1338 return NULL;
1339 }
1340
1341 return path_combine(bs->exact_filename, "");
1342}
1343
2654267c
HR
1344static const char *const ssh_strong_runtime_opts[] = {
1345 "host",
1346 "port",
1347 "path",
1348 "user",
1349 "host_key_check",
1350 "server.",
1351
1352 NULL
1353};
1354
0a12ec87
RJ
1355static BlockDriver bdrv_ssh = {
1356 .format_name = "ssh",
1357 .protocol_name = "ssh",
1358 .instance_size = sizeof(BDRVSSHState),
1359 .bdrv_parse_filename = ssh_parse_filename,
1360 .bdrv_file_open = ssh_file_open,
4906da7e 1361 .bdrv_co_create = ssh_co_create,
efc75e2a 1362 .bdrv_co_create_opts = ssh_co_create_opts,
0a12ec87 1363 .bdrv_close = ssh_close,
0b3f21e6 1364 .bdrv_has_zero_init = ssh_has_zero_init,
0a12ec87
RJ
1365 .bdrv_co_readv = ssh_co_readv,
1366 .bdrv_co_writev = ssh_co_writev,
c86422c5 1367 .bdrv_co_getlength = ssh_co_getlength,
061ca8a3 1368 .bdrv_co_truncate = ssh_co_truncate,
9a2d462e 1369 .bdrv_co_flush_to_disk = ssh_co_flush,
b8c1f901 1370 .bdrv_refresh_filename = ssh_refresh_filename,
21205c7c 1371 .bdrv_dirname = ssh_bdrv_dirname,
766181fe 1372 .create_opts = &ssh_create_opts,
2654267c 1373 .strong_runtime_opts = ssh_strong_runtime_opts,
0a12ec87
RJ
1374};
1375
1376static void bdrv_ssh_init(void)
1377{
1378 int r;
1379
b10d49d7 1380 r = ssh_init();
0a12ec87 1381 if (r != 0) {
b10d49d7 1382 fprintf(stderr, "libssh initialization failed, %d\n", r);
0a12ec87
RJ
1383 exit(EXIT_FAILURE);
1384 }
1385
b10d49d7
PT
1386#if TRACE_LIBSSH != 0
1387 ssh_set_log_level(TRACE_LIBSSH);
1388#endif
1389
0a12ec87
RJ
1390 bdrv_register(&bdrv_ssh);
1391}
1392
1393block_init(bdrv_ssh_init);