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