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