]> git.proxmox.com Git - mirror_qemu.git/blame - qemu-nbd.c
tests/9pfs: add local Tlink test
[mirror_qemu.git] / qemu-nbd.c
CommitLineData
cd831bd7 1/*
7a5ca864
FB
2 * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws>
3 *
4 * Network Block Device
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; under version 2 of the License.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
8167ee88 16 * along with this program; if not, see <http://www.gnu.org/licenses/>.
7a5ca864
FB
17 */
18
d38ea87a 19#include "qemu/osdep.h"
c2a3d7da
EB
20#include <getopt.h>
21#include <libgen.h>
22#include <pthread.h>
23
a8d25326 24#include "qemu-common.h"
da34e65c 25#include "qapi/error.h"
f348b6d1 26#include "qemu/cutils.h"
26f54e9a 27#include "sysemu/block-backend.h"
cbc20bfb 28#include "sysemu/runstate.h" /* for qemu_system_killed() prototype */
b3838a40 29#include "block/block_int.h"
737e150e 30#include "block/nbd.h"
6a1751b7 31#include "qemu/main-loop.h"
0b8fa32f 32#include "qemu/module.h"
922a01a0 33#include "qemu/option.h"
537b41f5 34#include "qemu/error-report.h"
0ab3b337 35#include "qemu/config-file.h"
58369e22 36#include "qemu/bswap.h"
39ca463e 37#include "qemu/log.h"
53fabd4b 38#include "qemu/systemd.h"
8c116b0e 39#include "block/snapshot.h"
452fcdbc 40#include "qapi/qmp/qdict.h"
d49b6836 41#include "qapi/qmp/qstring.h"
0ab3b337 42#include "qom/object_interfaces.h"
d0d6ff58 43#include "io/channel-socket.h"
e4849c1d 44#include "io/net-listener.h"
c2297088 45#include "crypto/init.h"
39ca463e 46#include "trace/control.h"
be377133 47#include "qemu-version.h"
7a5ca864 48
3c1fa35d
EB
49#ifdef __linux__
50#define HAVE_NBD_DEVICE 1
51#else
52#define HAVE_NBD_DEVICE 0
53#endif
54
713cc671 55#define SOCKET_PATH "/var/lock/qemu-nbd-%s"
fa8b7ce2
DB
56#define QEMU_NBD_OPT_CACHE 256
57#define QEMU_NBD_OPT_AIO 257
58#define QEMU_NBD_OPT_DISCARD 258
59#define QEMU_NBD_OPT_DETECT_ZEROES 259
60#define QEMU_NBD_OPT_OBJECT 260
61#define QEMU_NBD_OPT_TLSCREDS 261
62#define QEMU_NBD_OPT_IMAGE_OPTS 262
ffb31e1d 63#define QEMU_NBD_OPT_FORK 263
b25e12da 64#define QEMU_NBD_OPT_TLSAUTHZ 264
637bc5a5 65#define QEMU_NBD_OPT_PID_FILE 265
7a5ca864 66
bd31c214
EB
67#define MBR_SIZE 512
68
b1d8e52e 69static int verbose;
a517e88b 70static char *srcpath;
bd269ebc 71static SocketAddress *saddr;
7860a380 72static int persistent = 0;
d794f7f3 73static enum { RUNNING, TERMINATE, TERMINATED } state;
a61c6782
PB
74static int shared = 1;
75static int nb_fds;
e4849c1d 76static QIONetListener *server;
145614a1 77static QCryptoTLSCreds *tlscreds;
b25e12da 78static const char *tlsauthz;
7a5ca864
FB
79
80static void usage(const char *name)
81{
b033cd86 82 (printf) (
7a5ca864 83"Usage: %s [OPTIONS] FILE\n"
68b96f15
EB
84" or: %s -L [OPTIONS]\n"
85"QEMU Disk Network Block Device Utility\n"
7a5ca864 86"\n"
713cc671
PL
87" -h, --help display this help and exit\n"
88" -V, --version output version information and exit\n"
b033cd86
PB
89"\n"
90"Connection properties:\n"
713cc671
PL
91" -p, --port=PORT port to listen on (default `%d')\n"
92" -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
93" -k, --socket=PATH path to the unix socket\n"
94" (default '"SOCKET_PATH"')\n"
95" -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
96" -t, --persistent don't exit on the last connection\n"
97" -v, --verbose display extra debugging information\n"
f5cd0bb5
VSO
98" -x, --export-name=NAME expose export by name (default is empty string)\n"
99" -D, --description=TEXT export a human-readable description\n"
7a5ca864 100"\n"
b033cd86 101"Exposing part of the image:\n"
713cc671 102" -o, --offset=OFFSET offset into the image\n"
636192c4 103" -B, --bitmap=NAME expose a persistent dirty bitmap\n"
b033cd86 104"\n"
0ab3b337 105"General purpose options:\n"
68b96f15 106" -L, --list list exports available from another NBD server\n"
0ab3b337
DB
107" --object type,id=ID,... define an object such as 'secret' for providing\n"
108" passwords and/or encryption keys\n"
f7812df7 109" --tls-creds=ID use id of an earlier --object to provide TLS\n"
b25e12da
DB
110" --tls-authz=ID use id of an earlier --object to provide\n"
111" authorization\n"
39ca463e
DL
112" -T, --trace [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
113" specify tracing options\n"
ffb31e1d
HR
114" --fork fork off the server process and exit the parent\n"
115" once the server is running\n"
637bc5a5 116" --pid-file=PATH store the server's process ID in the given file\n"
3c1fa35d
EB
117#if HAVE_NBD_DEVICE
118"\n"
b033cd86 119"Kernel NBD client support:\n"
713cc671
PL
120" -c, --connect=DEV connect FILE to the local NBD device DEV\n"
121" -d, --disconnect disconnect the specified device\n"
b033cd86
PB
122#endif
123"\n"
124"Block device options:\n"
713cc671
PL
125" -f, --format=FORMAT set image format (raw, qcow2, ...)\n"
126" -r, --read-only export read-only\n"
127" -s, --snapshot use FILE as an external snapshot, create a temporary\n"
128" file with backing_file=FILE, redirect the write to\n"
129" the temporary one\n"
8c116b0e 130" -l, --load-snapshot=SNAPSHOT_PARAM\n"
713cc671
PL
131" load an internal snapshot inside FILE and export it\n"
132" as an read-only device, SNAPSHOT_PARAM format is\n"
133" 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
134" '[ID_OR_NAME]'\n"
135" -n, --nocache disable host cache\n"
136" --cache=MODE set cache mode (none, writeback, ...)\n"
7680274d 137" --aio=MODE set AIO mode (native, io_uring or threads)\n"
b3838a40 138" --discard=MODE set discard mode (ignore, unmap)\n"
6883de6c 139" --detect-zeroes=MODE set detect-zeroes mode (off, on, unmap)\n"
77c9aaef 140" --image-opts treat FILE as a full set of image options\n"
b033cd86 141"\n"
f5048cb7 142QEMU_HELP_BOTTOM "\n"
68b96f15 143 , name, name, NBD_DEFAULT_PORT, "DEVICE");
7a5ca864
FB
144}
145
146static void version(const char *name)
147{
148 printf(
7e563bfb 149"%s " QEMU_FULL_VERSION "\n"
7a5ca864
FB
150"Written by Anthony Liguori.\n"
151"\n"
be377133 152QEMU_COPYRIGHT "\n"
7a5ca864
FB
153"This is free software; see the source for copying conditions. There is NO\n"
154"warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
315bc7aa 155 , name);
7a5ca864
FB
156}
157
029a88c9 158#ifdef CONFIG_POSIX
cbc20bfb
SH
159/*
160 * The client thread uses SIGTERM to interrupt the server. A signal
161 * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
162 */
163void qemu_system_killed(int signum, pid_t pid)
bb345110 164{
d73415a3 165 qatomic_cmpxchg(&state, RUNNING, TERMINATE);
a61c6782 166 qemu_notify_event();
bb345110 167}
029a88c9 168#endif /* CONFIG_POSIX */
537b41f5 169
68b96f15
EB
170static int qemu_nbd_client_list(SocketAddress *saddr, QCryptoTLSCreds *tls,
171 const char *hostname)
172{
173 int ret = EXIT_FAILURE;
174 int rc;
175 Error *err = NULL;
176 QIOChannelSocket *sioc;
177 NBDExportInfo *list;
178 int i, j;
179
180 sioc = qio_channel_socket_new();
181 if (qio_channel_socket_connect_sync(sioc, saddr, &err) < 0) {
182 error_report_err(err);
183 return EXIT_FAILURE;
184 }
185 rc = nbd_receive_export_list(QIO_CHANNEL(sioc), tls, hostname, &list,
186 &err);
187 if (rc < 0) {
188 if (err) {
189 error_report_err(err);
190 }
191 goto out;
192 }
193 printf("exports available: %d\n", rc);
194 for (i = 0; i < rc; i++) {
195 printf(" export: '%s'\n", list[i].name);
196 if (list[i].description && *list[i].description) {
197 printf(" description: %s\n", list[i].description);
198 }
199 if (list[i].flags & NBD_FLAG_HAS_FLAGS) {
c4e2aff8
HR
200 static const char *const flag_names[] = {
201 [NBD_FLAG_READ_ONLY_BIT] = "readonly",
202 [NBD_FLAG_SEND_FLUSH_BIT] = "flush",
203 [NBD_FLAG_SEND_FUA_BIT] = "fua",
204 [NBD_FLAG_ROTATIONAL_BIT] = "rotational",
205 [NBD_FLAG_SEND_TRIM_BIT] = "trim",
206 [NBD_FLAG_SEND_WRITE_ZEROES_BIT] = "zeroes",
207 [NBD_FLAG_SEND_DF_BIT] = "df",
208 [NBD_FLAG_CAN_MULTI_CONN_BIT] = "multi",
209 [NBD_FLAG_SEND_RESIZE_BIT] = "resize",
210 [NBD_FLAG_SEND_CACHE_BIT] = "cache",
0a479545 211 [NBD_FLAG_SEND_FAST_ZERO_BIT] = "fast-zero",
c4e2aff8
HR
212 };
213
68b96f15
EB
214 printf(" size: %" PRIu64 "\n", list[i].size);
215 printf(" flags: 0x%x (", list[i].flags);
c4e2aff8
HR
216 for (size_t bit = 0; bit < ARRAY_SIZE(flag_names); bit++) {
217 if (flag_names[bit] && (list[i].flags & (1 << bit))) {
218 printf(" %s", flag_names[bit]);
219 }
68b96f15
EB
220 }
221 printf(" )\n");
222 }
223 if (list[i].min_block) {
224 printf(" min block: %u\n", list[i].min_block);
225 printf(" opt block: %u\n", list[i].opt_block);
226 printf(" max block: %u\n", list[i].max_block);
227 }
228 if (list[i].n_contexts) {
229 printf(" available meta contexts: %d\n", list[i].n_contexts);
230 for (j = 0; j < list[i].n_contexts; j++) {
231 printf(" %s\n", list[i].contexts[j]);
232 }
233 }
234 }
235 nbd_free_export_list(list, rc);
236
237 ret = EXIT_SUCCESS;
238 out:
239 object_unref(OBJECT(sioc));
240 return ret;
241}
242
243
3c1fa35d 244#if HAVE_NBD_DEVICE
a517e88b 245static void *show_parts(void *arg)
cd831bd7 246{
a6ac2313 247 char *device = arg;
a517e88b
PB
248 int nbd;
249
250 /* linux just needs an open() to trigger
251 * the partition table update
252 * but remember to load the module with max_part != 0 :
253 * modprobe nbd max_part=63
254 */
255 nbd = open(device, O_RDWR);
fc19f8a0 256 if (nbd >= 0) {
a517e88b
PB
257 close(nbd);
258 }
259 return NULL;
260}
cd831bd7 261
a517e88b
PB
262static void *nbd_client_thread(void *arg)
263{
a6ac2313 264 char *device = arg;
6dc1667d 265 NBDExportInfo info = { .request_sizes = false, .name = g_strdup("") };
d0d6ff58
DB
266 QIOChannelSocket *sioc;
267 int fd;
a517e88b
PB
268 int ret;
269 pthread_t show_parts_thread;
1ce52846 270 Error *local_error = NULL;
a517e88b 271
d0d6ff58
DB
272 sioc = qio_channel_socket_new();
273 if (qio_channel_socket_connect_sync(sioc,
274 saddr,
275 &local_error) < 0) {
48bec07e 276 error_report_err(local_error);
dc10e8b3
SH
277 goto out;
278 }
a517e88b 279
a8e2bb6a 280 ret = nbd_receive_negotiate(NULL, QIO_CHANNEL(sioc),
004a89fc 281 NULL, NULL, NULL, &info, &local_error);
fc19f8a0 282 if (ret < 0) {
1ce52846 283 if (local_error) {
78288671 284 error_report_err(local_error);
1ce52846 285 }
0c544d73 286 goto out_socket;
a517e88b
PB
287 }
288
a6ac2313 289 fd = open(device, O_RDWR);
fc19f8a0 290 if (fd < 0) {
a6ac2313 291 /* Linux-only, we can use %m in printf. */
b9884681 292 error_report("Failed to open %s: %m", device);
0c544d73 293 goto out_socket;
a6ac2313
PB
294 }
295
004a89fc 296 ret = nbd_init(fd, sioc, &info, &local_error);
fc19f8a0 297 if (ret < 0) {
be41c100 298 error_report_err(local_error);
0c544d73 299 goto out_fd;
a517e88b
PB
300 }
301
302 /* update partition table */
a6ac2313 303 pthread_create(&show_parts_thread, NULL, show_parts, device);
a517e88b 304
c1f8fdc3
PB
305 if (verbose) {
306 fprintf(stderr, "NBD device %s is now connected to %s\n",
307 device, srcpath);
308 } else {
309 /* Close stderr so that the qemu-nbd process exits. */
310 dup2(STDOUT_FILENO, STDERR_FILENO);
311 }
a517e88b
PB
312
313 ret = nbd_client(fd);
314 if (ret) {
0c544d73 315 goto out_fd;
cd831bd7 316 }
a517e88b 317 close(fd);
d0d6ff58 318 object_unref(OBJECT(sioc));
6dc1667d 319 g_free(info.name);
a517e88b
PB
320 kill(getpid(), SIGTERM);
321 return (void *) EXIT_SUCCESS;
322
0c544d73
PB
323out_fd:
324 close(fd);
325out_socket:
d0d6ff58 326 object_unref(OBJECT(sioc));
a517e88b 327out:
6dc1667d 328 g_free(info.name);
a517e88b
PB
329 kill(getpid(), SIGTERM);
330 return (void *) EXIT_FAILURE;
cd831bd7 331}
3c1fa35d 332#endif /* HAVE_NBD_DEVICE */
cd831bd7 333
e4afbf4f 334static int nbd_can_accept(void)
a61c6782 335{
df8ad9f1 336 return state == RUNNING && nb_fds < shared;
a61c6782
PB
337}
338
d0d6ff58 339static void nbd_update_server_watch(void);
e4afbf4f 340
0c9390d9 341static void nbd_client_closed(NBDClient *client, bool negotiated)
a61c6782 342{
1743b515 343 nb_fds--;
0c9390d9 344 if (negotiated && nb_fds == 0 && !persistent && state == RUNNING) {
7860a380
PB
345 state = TERMINATE;
346 }
d0d6ff58 347 nbd_update_server_watch();
7860a380 348 nbd_client_put(client);
a61c6782
PB
349}
350
e4849c1d
DB
351static void nbd_accept(QIONetListener *listener, QIOChannelSocket *cioc,
352 gpointer opaque)
a61c6782 353{
7860a380 354 if (state >= TERMINATE) {
e4849c1d 355 return;
7860a380
PB
356 }
357
ee7d7aab 358 nb_fds++;
d0d6ff58 359 nbd_update_server_watch();
b25e12da 360 nbd_client_new(cioc, tlscreds, tlsauthz, nbd_client_closed);
a61c6782
PB
361}
362
d0d6ff58 363static void nbd_update_server_watch(void)
e4afbf4f
FZ
364{
365 if (nbd_can_accept()) {
e4849c1d 366 qio_net_listener_set_client_func(server, nbd_accept, NULL, NULL);
e4afbf4f 367 } else {
e4849c1d 368 qio_net_listener_set_client_func(server, NULL, NULL, NULL);
e4afbf4f
FZ
369 }
370}
371
48bec07e 372
bd269ebc 373static SocketAddress *nbd_build_socket_address(const char *sockpath,
48bec07e
DB
374 const char *bindto,
375 const char *port)
376{
bd269ebc 377 SocketAddress *saddr;
48bec07e 378
bd269ebc 379 saddr = g_new0(SocketAddress, 1);
48bec07e 380 if (sockpath) {
bd269ebc
MA
381 saddr->type = SOCKET_ADDRESS_TYPE_UNIX;
382 saddr->u.q_unix.path = g_strdup(sockpath);
48bec07e 383 } else {
0399293e 384 InetSocketAddress *inet;
bd269ebc
MA
385 saddr->type = SOCKET_ADDRESS_TYPE_INET;
386 inet = &saddr->u.inet;
0399293e 387 inet->host = g_strdup(bindto);
48bec07e 388 if (port) {
0399293e 389 inet->port = g_strdup(port);
48bec07e 390 } else {
0399293e 391 inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
48bec07e
DB
392 }
393 }
394
395 return saddr;
396}
397
398
77c9aaef
DB
399static QemuOptsList file_opts = {
400 .name = "file",
401 .implied_opt_name = "file",
402 .head = QTAILQ_HEAD_INITIALIZER(file_opts.head),
403 .desc = {
404 /* no elements => accept any params */
405 { /* end of list */ }
406 },
407};
408
0ab3b337
DB
409static QemuOptsList qemu_object_opts = {
410 .name = "object",
411 .implied_opt_name = "qom-type",
412 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
413 .desc = {
414 { }
415 },
416};
417
495bf893
KW
418static bool qemu_nbd_object_print_help(const char *type, QemuOpts *opts)
419{
420 if (user_creatable_print_help(type, opts)) {
421 exit(0);
422 }
423 return true;
424}
0ab3b337 425
145614a1 426
68b96f15
EB
427static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, bool list,
428 Error **errp)
145614a1
DB
429{
430 Object *obj;
431 QCryptoTLSCreds *creds;
432
433 obj = object_resolve_path_component(
434 object_get_objects_root(), id);
435 if (!obj) {
436 error_setg(errp, "No TLS credentials with id '%s'",
437 id);
438 return NULL;
439 }
440 creds = (QCryptoTLSCreds *)
441 object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
442 if (!creds) {
443 error_setg(errp, "Object with id '%s' is not TLS credentials",
444 id);
445 return NULL;
446 }
447
68b96f15
EB
448 if (list) {
449 if (creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
450 error_setg(errp,
451 "Expecting TLS credentials with a client endpoint");
452 return NULL;
453 }
454 } else {
455 if (creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
456 error_setg(errp,
457 "Expecting TLS credentials with a server endpoint");
458 return NULL;
459 }
145614a1
DB
460 }
461 object_ref(obj);
462 return creds;
463}
464
a721f53b
RJ
465static void setup_address_and_port(const char **address, const char **port)
466{
467 if (*address == NULL) {
468 *address = "0.0.0.0";
469 }
470
471 if (*port == NULL) {
472 *port = stringify(NBD_DEFAULT_PORT);
473 }
474}
475
a721f53b
RJ
476/*
477 * Check socket parameters compatibility when socket activation is used.
478 */
479static const char *socket_activation_validate_opts(const char *device,
480 const char *sockpath,
481 const char *address,
68b96f15
EB
482 const char *port,
483 bool list)
a721f53b
RJ
484{
485 if (device != NULL) {
486 return "NBD device can't be set when using socket activation";
487 }
488
489 if (sockpath != NULL) {
490 return "Unix socket can't be set when using socket activation";
491 }
492
493 if (address != NULL) {
494 return "The interface can't be set when using socket activation";
495 }
496
497 if (port != NULL) {
498 return "TCP port number can't be set when using socket activation";
499 }
500
68b96f15
EB
501 if (list) {
502 return "List mode is incompatible with socket activation";
503 }
504
a721f53b
RJ
505 return NULL;
506}
145614a1 507
b3b5299d
KW
508static void qemu_nbd_shutdown(void)
509{
510 job_cancel_sync_all();
511 bdrv_close_all();
512}
513
7a5ca864
FB
514int main(int argc, char **argv)
515{
26f54e9a 516 BlockBackend *blk;
7a5ca864 517 BlockDriverState *bs;
9d26dfcb 518 uint64_t dev_offset = 0;
dbb38caa 519 bool readonly = false;
cd831bd7 520 bool disconnect = false;
a721f53b 521 const char *bindto = NULL;
48bec07e
DB
522 const char *port = NULL;
523 char *sockpath = NULL;
a6ac2313 524 char *device = NULL;
8c116b0e
WX
525 QemuOpts *sn_opts = NULL;
526 const char *sn_id_or_name = NULL;
0bc16997 527 const char *sopt = "hVb:o:p:rsnc:dvk:e:f:tl:x:T:D:B:L";
7a5ca864 528 struct option lopt[] = {
aa6e546c
DB
529 { "help", no_argument, NULL, 'h' },
530 { "version", no_argument, NULL, 'V' },
531 { "bind", required_argument, NULL, 'b' },
532 { "port", required_argument, NULL, 'p' },
533 { "socket", required_argument, NULL, 'k' },
534 { "offset", required_argument, NULL, 'o' },
535 { "read-only", no_argument, NULL, 'r' },
636192c4 536 { "bitmap", required_argument, NULL, 'B' },
aa6e546c
DB
537 { "connect", required_argument, NULL, 'c' },
538 { "disconnect", no_argument, NULL, 'd' },
68b96f15 539 { "list", no_argument, NULL, 'L' },
aa6e546c
DB
540 { "snapshot", no_argument, NULL, 's' },
541 { "load-snapshot", required_argument, NULL, 'l' },
542 { "nocache", no_argument, NULL, 'n' },
543 { "cache", required_argument, NULL, QEMU_NBD_OPT_CACHE },
544 { "aio", required_argument, NULL, QEMU_NBD_OPT_AIO },
545 { "discard", required_argument, NULL, QEMU_NBD_OPT_DISCARD },
546 { "detect-zeroes", required_argument, NULL,
547 QEMU_NBD_OPT_DETECT_ZEROES },
548 { "shared", required_argument, NULL, 'e' },
549 { "format", required_argument, NULL, 'f' },
550 { "persistent", no_argument, NULL, 't' },
551 { "verbose", no_argument, NULL, 'v' },
552 { "object", required_argument, NULL, QEMU_NBD_OPT_OBJECT },
553 { "export-name", required_argument, NULL, 'x' },
b1a75b33 554 { "description", required_argument, NULL, 'D' },
aa6e546c 555 { "tls-creds", required_argument, NULL, QEMU_NBD_OPT_TLSCREDS },
b25e12da 556 { "tls-authz", required_argument, NULL, QEMU_NBD_OPT_TLSAUTHZ },
aa6e546c 557 { "image-opts", no_argument, NULL, QEMU_NBD_OPT_IMAGE_OPTS },
39ca463e 558 { "trace", required_argument, NULL, 'T' },
ffb31e1d 559 { "fork", no_argument, NULL, QEMU_NBD_OPT_FORK },
637bc5a5 560 { "pid-file", required_argument, NULL, QEMU_NBD_OPT_PID_FILE },
660f11be 561 { NULL, 0, NULL, 0 }
7a5ca864
FB
562 };
563 int ch;
564 int opt_ind = 0;
f5edb014 565 int flags = BDRV_O_RDWR;
4fbec260 566 int ret = 0;
39a5235c 567 bool seen_cache = false;
ded9d2d5 568 bool seen_discard = false;
39a5235c 569 bool seen_aio = false;
a517e88b 570 pthread_t client_thread;
e6b63677 571 const char *fmt = NULL;
34b5d2c6 572 Error *local_err = NULL;
b3838a40 573 BlockdevDetectZeroesOptions detect_zeroes = BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
4fbec260 574 QDict *options = NULL;
68b96f15 575 const char *export_name = NULL; /* defaults to "" later for server mode */
b1a75b33 576 const char *export_description = NULL;
636192c4 577 const char *bitmap = NULL;
145614a1 578 const char *tlscredsid = NULL;
77c9aaef 579 bool imageOpts = false;
6effd5bf 580 bool writethrough = true;
39ca463e 581 char *trace_file = NULL;
ffb31e1d 582 bool fork_process = false;
68b96f15 583 bool list = false;
ffb31e1d 584 int old_stderr = -1;
a721f53b 585 unsigned socket_activation;
637bc5a5 586 const char *pid_file_name = NULL;
00917172 587 BlockExportOptions *export_opts;
7a5ca864 588
029a88c9 589#ifdef CONFIG_POSIX
cbc20bfb
SH
590 os_setup_early_signal_handling();
591 os_setup_signal_handling();
041e32b8
HR
592#endif
593
98c5d2e7 594 socket_init();
f5852efa 595 error_init(argv[0]);
fe4db84d 596 module_call_init(MODULE_INIT_TRACE);
e8f2d272 597 qcrypto_init(&error_fatal);
c2297088 598
0ab3b337
DB
599 module_call_init(MODULE_INIT_QOM);
600 qemu_add_opts(&qemu_object_opts);
39ca463e 601 qemu_add_opts(&qemu_trace_opts);
10f5bff6 602 qemu_init_exec_dir(argv[0]);
bb345110 603
7a5ca864
FB
604 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
605 switch (ch) {
606 case 's':
2f726488
TS
607 flags |= BDRV_O_SNAPSHOT;
608 break;
609 case 'n':
39a5235c
PB
610 optarg = (char *) "none";
611 /* fallthrough */
612 case QEMU_NBD_OPT_CACHE:
613 if (seen_cache) {
85b01e09
MA
614 error_report("-n and --cache can only be specified once");
615 exit(EXIT_FAILURE);
39a5235c
PB
616 }
617 seen_cache = true;
6effd5bf 618 if (bdrv_parse_cache_mode(optarg, &flags, &writethrough) == -1) {
85b01e09
MA
619 error_report("Invalid cache mode `%s'", optarg);
620 exit(EXIT_FAILURE);
39a5235c 621 }
7a5ca864 622 break;
39a5235c
PB
623 case QEMU_NBD_OPT_AIO:
624 if (seen_aio) {
85b01e09
MA
625 error_report("--aio can only be specified once");
626 exit(EXIT_FAILURE);
39a5235c
PB
627 }
628 seen_aio = true;
7680274d
AM
629 if (bdrv_parse_aio(optarg, &flags) < 0) {
630 error_report("Invalid aio mode '%s'", optarg);
631 exit(EXIT_FAILURE);
39a5235c
PB
632 }
633 break;
ded9d2d5
PB
634 case QEMU_NBD_OPT_DISCARD:
635 if (seen_discard) {
85b01e09
MA
636 error_report("--discard can only be specified once");
637 exit(EXIT_FAILURE);
ded9d2d5
PB
638 }
639 seen_discard = true;
640 if (bdrv_parse_discard_flags(optarg, &flags) == -1) {
85b01e09
MA
641 error_report("Invalid discard mode `%s'", optarg);
642 exit(EXIT_FAILURE);
ded9d2d5
PB
643 }
644 break;
b3838a40
PL
645 case QEMU_NBD_OPT_DETECT_ZEROES:
646 detect_zeroes =
f7abe0ec 647 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup,
b3838a40 648 optarg,
b3838a40
PL
649 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
650 &local_err);
651 if (local_err) {
c29b77f9
MA
652 error_reportf_err(local_err,
653 "Failed to parse detect_zeroes mode: ");
85b01e09 654 exit(EXIT_FAILURE);
b3838a40
PL
655 }
656 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
657 !(flags & BDRV_O_UNMAP)) {
85b01e09
MA
658 error_report("setting detect-zeroes to unmap is not allowed "
659 "without setting discard operation to unmap");
660 exit(EXIT_FAILURE);
b3838a40
PL
661 }
662 break;
7a5ca864
FB
663 case 'b':
664 bindto = optarg;
665 break;
666 case 'p':
48bec07e 667 port = optarg;
7a5ca864
FB
668 break;
669 case 'o':
43b51011
EB
670 if (qemu_strtou64(optarg, NULL, 0, &dev_offset) < 0) {
671 error_report("Invalid offset '%s'", optarg);
85b01e09 672 exit(EXIT_FAILURE);
7a5ca864 673 }
7a5ca864 674 break;
8c116b0e
WX
675 case 'l':
676 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
70b94331
MA
677 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
678 optarg, false);
8c116b0e 679 if (!sn_opts) {
85b01e09
MA
680 error_report("Failed in parsing snapshot param `%s'",
681 optarg);
682 exit(EXIT_FAILURE);
8c116b0e
WX
683 }
684 } else {
685 sn_id_or_name = optarg;
686 }
687 /* fall through */
7a5ca864 688 case 'r':
dbb38caa 689 readonly = true;
07108b29 690 flags &= ~BDRV_O_RDWR;
7a5ca864 691 break;
636192c4
EB
692 case 'B':
693 bitmap = optarg;
694 break;
cd831bd7 695 case 'k':
b32f6c28 696 sockpath = optarg;
713cc671 697 if (sockpath[0] != '/') {
9af9e0fe 698 error_report("socket path must be absolute");
85b01e09 699 exit(EXIT_FAILURE);
713cc671 700 }
cd831bd7
TS
701 break;
702 case 'd':
703 disconnect = true;
704 break;
705 case 'c':
706 device = optarg;
707 break;
3b05a8e9 708 case 'e':
43b51011
EB
709 if (qemu_strtoi(optarg, NULL, 0, &shared) < 0 ||
710 shared < 1) {
85b01e09
MA
711 error_report("Invalid shared device number '%s'", optarg);
712 exit(EXIT_FAILURE);
3b05a8e9 713 }
3b05a8e9 714 break;
e6b63677
DB
715 case 'f':
716 fmt = optarg;
717 break;
713cc671
PL
718 case 't':
719 persistent = 1;
720 break;
3d4b2f9c
DB
721 case 'x':
722 export_name = optarg;
93676c88
EB
723 if (strlen(export_name) > NBD_MAX_STRING_SIZE) {
724 error_report("export name '%s' too long", export_name);
725 exit(EXIT_FAILURE);
726 }
3d4b2f9c 727 break;
b1a75b33
EB
728 case 'D':
729 export_description = optarg;
93676c88
EB
730 if (strlen(export_description) > NBD_MAX_STRING_SIZE) {
731 error_report("export description '%s' too long",
732 export_description);
733 exit(EXIT_FAILURE);
734 }
b1a75b33 735 break;
7a5ca864
FB
736 case 'v':
737 verbose = 1;
738 break;
739 case 'V':
740 version(argv[0]);
741 exit(0);
742 break;
743 case 'h':
744 usage(argv[0]);
745 exit(0);
746 break;
747 case '?':
85b01e09
MA
748 error_report("Try `%s --help' for more information.", argv[0]);
749 exit(EXIT_FAILURE);
0ab3b337
DB
750 case QEMU_NBD_OPT_OBJECT: {
751 QemuOpts *opts;
752 opts = qemu_opts_parse_noisily(&qemu_object_opts,
753 optarg, true);
754 if (!opts) {
755 exit(EXIT_FAILURE);
756 }
757 } break;
145614a1
DB
758 case QEMU_NBD_OPT_TLSCREDS:
759 tlscredsid = optarg;
760 break;
77c9aaef
DB
761 case QEMU_NBD_OPT_IMAGE_OPTS:
762 imageOpts = true;
763 break;
39ca463e
DL
764 case 'T':
765 g_free(trace_file);
766 trace_file = trace_opt_parse(optarg);
767 break;
b25e12da
DB
768 case QEMU_NBD_OPT_TLSAUTHZ:
769 tlsauthz = optarg;
770 break;
ffb31e1d
HR
771 case QEMU_NBD_OPT_FORK:
772 fork_process = true;
773 break;
68b96f15
EB
774 case 'L':
775 list = true;
776 break;
637bc5a5
HR
777 case QEMU_NBD_OPT_PID_FILE:
778 pid_file_name = optarg;
779 break;
7a5ca864
FB
780 }
781 }
782
68b96f15
EB
783 if (list) {
784 if (argc != optind) {
785 error_report("List mode is incompatible with a file name");
786 exit(EXIT_FAILURE);
787 }
0bc16997 788 if (export_name || export_description || dev_offset ||
68b96f15
EB
789 device || disconnect || fmt || sn_id_or_name || bitmap ||
790 seen_aio || seen_discard || seen_cache) {
791 error_report("List mode is incompatible with per-device settings");
792 exit(EXIT_FAILURE);
793 }
794 if (fork_process) {
795 error_report("List mode is incompatible with forking");
796 exit(EXIT_FAILURE);
797 }
798 } else if ((argc - optind) != 1) {
433672b0
MA
799 error_report("Invalid number of arguments");
800 error_printf("Try `%s --help' for more information.\n", argv[0]);
85b01e09 801 exit(EXIT_FAILURE);
68b96f15
EB
802 } else if (!export_name) {
803 export_name = "";
7a5ca864
FB
804 }
805
7e1e0c11
MA
806 qemu_opts_foreach(&qemu_object_opts,
807 user_creatable_add_opts_foreach,
495bf893 808 qemu_nbd_object_print_help, &error_fatal);
0ab3b337 809
39ca463e
DL
810 if (!trace_init_backends()) {
811 exit(1);
812 }
813 trace_init_file(trace_file);
814 qemu_set_log(LOG_TRACE);
815
a721f53b
RJ
816 socket_activation = check_socket_activation();
817 if (socket_activation == 0) {
818 setup_address_and_port(&bindto, &port);
819 } else {
820 /* Using socket activation - check user didn't use -p etc. */
821 const char *err_msg = socket_activation_validate_opts(device, sockpath,
68b96f15
EB
822 bindto, port,
823 list);
a721f53b
RJ
824 if (err_msg != NULL) {
825 error_report("%s", err_msg);
826 exit(EXIT_FAILURE);
827 }
53fabd4b
PB
828
829 /* qemu-nbd can only listen on a single socket. */
830 if (socket_activation > 1) {
831 error_report("qemu-nbd does not support socket activation with %s > 1",
832 "LISTEN_FDS");
833 exit(EXIT_FAILURE);
834 }
a721f53b
RJ
835 }
836
145614a1
DB
837 if (tlscredsid) {
838 if (sockpath) {
839 error_report("TLS is only supported with IPv4/IPv6");
840 exit(EXIT_FAILURE);
841 }
842 if (device) {
843 error_report("TLS is not supported with a host device");
844 exit(EXIT_FAILURE);
845 }
b25e12da
DB
846 if (tlsauthz && list) {
847 error_report("TLS authorization is incompatible with export list");
848 exit(EXIT_FAILURE);
849 }
68b96f15 850 tlscreds = nbd_get_tls_creds(tlscredsid, list, &local_err);
145614a1 851 if (local_err) {
5217f188 852 error_reportf_err(local_err, "Failed to get TLS creds: ");
145614a1
DB
853 exit(EXIT_FAILURE);
854 }
b25e12da
DB
855 } else {
856 if (tlsauthz) {
857 error_report("--tls-authz is not permitted without --tls-creds");
858 exit(EXIT_FAILURE);
859 }
145614a1
DB
860 }
861
68b96f15
EB
862 if (list) {
863 saddr = nbd_build_socket_address(sockpath, bindto, port);
864 return qemu_nbd_client_list(saddr, tlscreds, bindto);
865 }
866
3c1fa35d
EB
867#if !HAVE_NBD_DEVICE
868 if (disconnect || device) {
869 error_report("Kernel /dev/nbdN support not available");
870 exit(EXIT_FAILURE);
871 }
872#else /* HAVE_NBD_DEVICE */
cd831bd7 873 if (disconnect) {
d0d6ff58
DB
874 int nbdfd = open(argv[optind], O_RDWR);
875 if (nbdfd < 0) {
85b01e09
MA
876 error_report("Cannot open %s: %s", argv[optind],
877 strerror(errno));
878 exit(EXIT_FAILURE);
fc19f8a0 879 }
d0d6ff58 880 nbd_disconnect(nbdfd);
cd831bd7 881
d0d6ff58 882 close(nbdfd);
cd831bd7
TS
883
884 printf("%s disconnected\n", argv[optind]);
885
713cc671 886 return 0;
cd831bd7 887 }
3c1fa35d 888#endif
cd831bd7 889
ffb31e1d 890 if ((device && !verbose) || fork_process) {
eb705985 891#ifndef WIN32
c1f8fdc3
PB
892 int stderr_fd[2];
893 pid_t pid;
894 int ret;
895
fc19f8a0 896 if (qemu_pipe(stderr_fd) < 0) {
85b01e09
MA
897 error_report("Error setting up communication pipe: %s",
898 strerror(errno));
899 exit(EXIT_FAILURE);
c1f8fdc3
PB
900 }
901
902 /* Now daemonize, but keep a communication channel open to
903 * print errors and exit with the proper status code.
904 */
905 pid = fork();
70d4739e 906 if (pid < 0) {
85b01e09
MA
907 error_report("Failed to fork: %s", strerror(errno));
908 exit(EXIT_FAILURE);
70d4739e 909 } else if (pid == 0) {
c1f8fdc3 910 close(stderr_fd[0]);
e6df58a5 911
0eaf453e
RP
912 /* Remember parent's stderr if we will be restoring it. */
913 if (fork_process) {
914 old_stderr = dup(STDERR_FILENO);
915 }
916
9faf31b6 917 ret = qemu_daemon(1, 0);
c1f8fdc3
PB
918
919 /* Temporarily redirect stderr to the parent's pipe... */
920 dup2(stderr_fd[1], STDERR_FILENO);
fc19f8a0 921 if (ret < 0) {
85b01e09
MA
922 error_report("Failed to daemonize: %s", strerror(errno));
923 exit(EXIT_FAILURE);
c1f8fdc3
PB
924 }
925
926 /* ... close the descriptor we inherited and go on. */
927 close(stderr_fd[1]);
928 } else {
929 bool errors = false;
930 char *buf;
931
932 /* In the parent. Print error messages from the child until
933 * it closes the pipe.
934 */
935 close(stderr_fd[1]);
936 buf = g_malloc(1024);
937 while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
938 errors = true;
939 ret = qemu_write_full(STDERR_FILENO, buf, ret);
fc19f8a0 940 if (ret < 0) {
c1f8fdc3
PB
941 exit(EXIT_FAILURE);
942 }
943 }
fc19f8a0 944 if (ret < 0) {
85b01e09
MA
945 error_report("Cannot read from daemon: %s",
946 strerror(errno));
947 exit(EXIT_FAILURE);
c1f8fdc3
PB
948 }
949
950 /* Usually the daemon should not print any message.
951 * Exit with zero status in that case.
952 */
953 exit(errors);
954 }
eb705985
DB
955#else /* WIN32 */
956 error_report("Unable to fork into background on Windows hosts");
957 exit(EXIT_FAILURE);
958#endif /* WIN32 */
c1f8fdc3
PB
959 }
960
a6ac2313
PB
961 if (device != NULL && sockpath == NULL) {
962 sockpath = g_malloc(128);
963 snprintf(sockpath, 128, SOCKET_PATH, basename(device));
cd831bd7
TS
964 }
965
e4849c1d 966 server = qio_net_listener_new();
a721f53b 967 if (socket_activation == 0) {
a721f53b 968 saddr = nbd_build_socket_address(sockpath, bindto, port);
fc8135c6 969 if (qio_net_listener_open_sync(server, saddr, 1, &local_err) < 0) {
e4849c1d 970 object_unref(OBJECT(server));
a721f53b 971 error_report_err(local_err);
e4849c1d 972 exit(EXIT_FAILURE);
a721f53b
RJ
973 }
974 } else {
e4849c1d 975 size_t i;
a721f53b 976 /* See comment in check_socket_activation above. */
e4849c1d
DB
977 for (i = 0; i < socket_activation; i++) {
978 QIOChannelSocket *sioc;
979 sioc = qio_channel_socket_new_fd(FIRST_SOCKET_ACTIVATION_FD + i,
980 &local_err);
981 if (sioc == NULL) {
982 object_unref(OBJECT(server));
5217f188
MA
983 error_reportf_err(local_err,
984 "Failed to use socket activation: ");
e4849c1d
DB
985 exit(EXIT_FAILURE);
986 }
987 qio_net_listener_add(server, sioc);
988 object_unref(OBJECT(sioc));
a721f53b
RJ
989 }
990 }
48bec07e 991
2f78e491 992 if (qemu_init_main_loop(&local_err)) {
565f65d2 993 error_report_err(local_err);
2f78e491
CN
994 exit(EXIT_FAILURE);
995 }
802ddc37 996 bdrv_init();
b3b5299d 997 atexit(qemu_nbd_shutdown);
802ddc37 998
77c9aaef
DB
999 srcpath = argv[optind];
1000 if (imageOpts) {
1001 QemuOpts *opts;
1002 if (fmt) {
1003 error_report("--image-opts and -f are mutually exclusive");
1004 exit(EXIT_FAILURE);
1005 }
1006 opts = qemu_opts_parse_noisily(&file_opts, srcpath, true);
1007 if (!opts) {
1008 qemu_opts_reset(&file_opts);
1009 exit(EXIT_FAILURE);
1010 }
1011 options = qemu_opts_to_qdict(opts, NULL);
1012 qemu_opts_reset(&file_opts);
efaa7c4e 1013 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
77c9aaef
DB
1014 } else {
1015 if (fmt) {
1016 options = qdict_new();
46f5ac20 1017 qdict_put_str(options, "driver", fmt);
77c9aaef 1018 }
efaa7c4e 1019 blk = blk_new_open(srcpath, NULL, options, flags, &local_err);
e6b63677
DB
1020 }
1021
4fbec260 1022 if (!blk) {
c29b77f9
MA
1023 error_reportf_err(local_err, "Failed to blk_new_open '%s': ",
1024 argv[optind]);
85b01e09 1025 exit(EXIT_FAILURE);
802ddc37 1026 }
4fbec260 1027 bs = blk_bs(blk);
802ddc37 1028
b57e4de0
KW
1029 if (dev_offset) {
1030 QDict *raw_opts = qdict_new();
1031 qdict_put_str(raw_opts, "driver", "raw");
1032 qdict_put_str(raw_opts, "file", bs->node_name);
1033 qdict_put_int(raw_opts, "offset", dev_offset);
1034 bs = bdrv_open(NULL, NULL, raw_opts, flags, &error_fatal);
1035 blk_remove_bs(blk);
1036 blk_insert_bs(blk, bs, &error_fatal);
1037 bdrv_unref(bs);
1038 }
1039
6effd5bf
KW
1040 blk_set_enable_write_cache(blk, !writethrough);
1041
8c116b0e
WX
1042 if (sn_opts) {
1043 ret = bdrv_snapshot_load_tmp(bs,
1044 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1045 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1046 &local_err);
1047 } else if (sn_id_or_name) {
1048 ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
1049 &local_err);
1050 }
1051 if (ret < 0) {
c29b77f9 1052 error_reportf_err(local_err, "Failed to load snapshot: ");
85b01e09 1053 exit(EXIT_FAILURE);
8c116b0e
WX
1054 }
1055
b3838a40 1056 bs->detect_zeroes = detect_zeroes;
e424b655 1057
00917172
KW
1058 nbd_server_is_qemu_nbd(true);
1059
1060 export_opts = g_new(BlockExportOptions, 1);
1061 *export_opts = (BlockExportOptions) {
1062 .type = BLOCK_EXPORT_TYPE_NBD,
d53be9ce 1063 .id = g_strdup("qemu-nbd-export"),
b6076afc 1064 .node_name = g_strdup(bdrv_get_node_name(bs)),
00917172
KW
1065 .has_writethrough = true,
1066 .writethrough = writethrough,
30dbc81d
KW
1067 .has_writable = true,
1068 .writable = !readonly,
00917172 1069 .u.nbd = {
00917172
KW
1070 .has_name = true,
1071 .name = g_strdup(export_name),
1072 .has_description = !!export_description,
1073 .description = g_strdup(export_description),
00917172
KW
1074 .has_bitmap = !!bitmap,
1075 .bitmap = g_strdup(bitmap),
1076 },
1077 };
1078 blk_exp_add(export_opts, &error_fatal);
1079 qapi_free_BlockExportOptions(export_opts);
3b05a8e9 1080
f1ef5555 1081 if (device) {
3c1fa35d 1082#if HAVE_NBD_DEVICE
f1ef5555
PB
1083 int ret;
1084
a6ac2313 1085 ret = pthread_create(&client_thread, NULL, nbd_client_thread, device);
f1ef5555 1086 if (ret != 0) {
85b01e09
MA
1087 error_report("Failed to create client thread: %s", strerror(ret));
1088 exit(EXIT_FAILURE);
f1ef5555 1089 }
3c1fa35d 1090#endif
f1ef5555
PB
1091 } else {
1092 /* Shut up GCC warnings. */
1093 memset(&client_thread, 0, sizeof(client_thread));
1094 }
1095
d0d6ff58 1096 nbd_update_server_watch();
7a5ca864 1097
637bc5a5
HR
1098 if (pid_file_name) {
1099 qemu_write_pidfile(pid_file_name, &error_fatal);
1100 }
1101
9faf31b6
MT
1102 /* now when the initialization is (almost) complete, chdir("/")
1103 * to free any busy filesystems */
1104 if (chdir("/") < 0) {
85b01e09
MA
1105 error_report("Could not chdir to root directory: %s",
1106 strerror(errno));
1107 exit(EXIT_FAILURE);
9faf31b6
MT
1108 }
1109
ffb31e1d
HR
1110 if (fork_process) {
1111 dup2(old_stderr, STDERR_FILENO);
1112 close(old_stderr);
1113 }
1114
7860a380 1115 state = RUNNING;
3b05a8e9 1116 do {
a61c6782 1117 main_loop_wait(false);
7860a380 1118 if (state == TERMINATE) {
bc4ee65b 1119 blk_exp_close_all();
d794f7f3 1120 state = TERMINATED;
7860a380
PB
1121 }
1122 } while (state != TERMINATED);
7a5ca864 1123
26f54e9a 1124 blk_unref(blk);
b32f6c28
PB
1125 if (sockpath) {
1126 unlink(sockpath);
1127 }
7a5ca864 1128
fbf28a43 1129 qemu_opts_del(sn_opts);
8c116b0e 1130
a517e88b
PB
1131 if (device) {
1132 void *ret;
1133 pthread_join(client_thread, &ret);
1134 exit(ret != NULL);
1135 } else {
1136 exit(EXIT_SUCCESS);
1137 }
7a5ca864 1138}