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