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