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