nbd: allow setting of an export name for qemu-nbd server
[sdk/emulator/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 "qemu-common.h"
21 #include "sysemu/block-backend.h"
22 #include "block/block_int.h"
23 #include "block/nbd.h"
24 #include "qemu/main-loop.h"
25 #include "qemu/error-report.h"
26 #include "qemu/config-file.h"
27 #include "block/snapshot.h"
28 #include "qapi/util.h"
29 #include "qapi/qmp/qstring.h"
30 #include "qom/object_interfaces.h"
31 #include "io/channel-socket.h"
32
33 #include <getopt.h>
34 #include <sys/types.h>
35 #include <signal.h>
36 #include <libgen.h>
37 #include <pthread.h>
38
39 #define SOCKET_PATH                "/var/lock/qemu-nbd-%s"
40 #define QEMU_NBD_OPT_CACHE         1
41 #define QEMU_NBD_OPT_AIO           2
42 #define QEMU_NBD_OPT_DISCARD       3
43 #define QEMU_NBD_OPT_DETECT_ZEROES 4
44 #define QEMU_NBD_OPT_OBJECT        5
45
46 static NBDExport *exp;
47 static bool newproto;
48 static int verbose;
49 static char *srcpath;
50 static SocketAddress *saddr;
51 static int persistent = 0;
52 static enum { RUNNING, TERMINATE, TERMINATING, TERMINATED } state;
53 static int shared = 1;
54 static int nb_fds;
55 static QIOChannelSocket *server_ioc;
56 static int server_watch = -1;
57
58 static void usage(const char *name)
59 {
60     (printf) (
61 "Usage: %s [OPTIONS] FILE\n"
62 "QEMU Disk Network Block Device Server\n"
63 "\n"
64 "  -h, --help                display this help and exit\n"
65 "  -V, --version             output version information and exit\n"
66 "\n"
67 "Connection properties:\n"
68 "  -p, --port=PORT           port to listen on (default `%d')\n"
69 "  -b, --bind=IFACE          interface to bind to (default `0.0.0.0')\n"
70 "  -k, --socket=PATH         path to the unix socket\n"
71 "                            (default '"SOCKET_PATH"')\n"
72 "  -e, --shared=NUM          device can be shared by NUM clients (default '1')\n"
73 "  -t, --persistent          don't exit on the last connection\n"
74 "  -v, --verbose             display extra debugging information\n"
75 "\n"
76 "Exposing part of the image:\n"
77 "  -o, --offset=OFFSET       offset into the image\n"
78 "  -P, --partition=NUM       only expose partition NUM\n"
79 "\n"
80 "General purpose options:\n"
81 "  --object type,id=ID,...   define an object such as 'secret' for providing\n"
82 "                            passwords and/or encryption keys\n"
83 #ifdef __linux__
84 "Kernel NBD client support:\n"
85 "  -c, --connect=DEV         connect FILE to the local NBD device DEV\n"
86 "  -d, --disconnect          disconnect the specified device\n"
87 "\n"
88 #endif
89 "\n"
90 "Block device options:\n"
91 "  -f, --format=FORMAT       set image format (raw, qcow2, ...)\n"
92 "  -r, --read-only           export read-only\n"
93 "  -s, --snapshot            use FILE as an external snapshot, create a temporary\n"
94 "                            file with backing_file=FILE, redirect the write to\n"
95 "                            the temporary one\n"
96 "  -l, --load-snapshot=SNAPSHOT_PARAM\n"
97 "                            load an internal snapshot inside FILE and export it\n"
98 "                            as an read-only device, SNAPSHOT_PARAM format is\n"
99 "                            'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
100 "                            '[ID_OR_NAME]'\n"
101 "  -n, --nocache             disable host cache\n"
102 "      --cache=MODE          set cache mode (none, writeback, ...)\n"
103 "      --aio=MODE            set AIO mode (native or threads)\n"
104 "      --discard=MODE        set discard mode (ignore, unmap)\n"
105 "      --detect-zeroes=MODE  set detect-zeroes mode (off, on, unmap)\n"
106 "\n"
107 "Report bugs to <qemu-devel@nongnu.org>\n"
108     , name, NBD_DEFAULT_PORT, "DEVICE");
109 }
110
111 static void version(const char *name)
112 {
113     printf(
114 "%s version 0.0.1\n"
115 "Written by Anthony Liguori.\n"
116 "\n"
117 "Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>.\n"
118 "This is free software; see the source for copying conditions.  There is NO\n"
119 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
120     , name);
121 }
122
123 struct partition_record
124 {
125     uint8_t bootable;
126     uint8_t start_head;
127     uint32_t start_cylinder;
128     uint8_t start_sector;
129     uint8_t system;
130     uint8_t end_head;
131     uint8_t end_cylinder;
132     uint8_t end_sector;
133     uint32_t start_sector_abs;
134     uint32_t nb_sectors_abs;
135 };
136
137 static void read_partition(uint8_t *p, struct partition_record *r)
138 {
139     r->bootable = p[0];
140     r->start_head = p[1];
141     r->start_cylinder = p[3] | ((p[2] << 2) & 0x0300);
142     r->start_sector = p[2] & 0x3f;
143     r->system = p[4];
144     r->end_head = p[5];
145     r->end_cylinder = p[7] | ((p[6] << 2) & 0x300);
146     r->end_sector = p[6] & 0x3f;
147
148     r->start_sector_abs = le32_to_cpup((uint32_t *)(p +  8));
149     r->nb_sectors_abs   = le32_to_cpup((uint32_t *)(p + 12));
150 }
151
152 static int find_partition(BlockBackend *blk, int partition,
153                           off_t *offset, off_t *size)
154 {
155     struct partition_record mbr[4];
156     uint8_t data[512];
157     int i;
158     int ext_partnum = 4;
159     int ret;
160
161     if ((ret = blk_read(blk, 0, data, 1)) < 0) {
162         error_report("error while reading: %s", strerror(-ret));
163         exit(EXIT_FAILURE);
164     }
165
166     if (data[510] != 0x55 || data[511] != 0xaa) {
167         return -EINVAL;
168     }
169
170     for (i = 0; i < 4; i++) {
171         read_partition(&data[446 + 16 * i], &mbr[i]);
172
173         if (!mbr[i].system || !mbr[i].nb_sectors_abs) {
174             continue;
175         }
176
177         if (mbr[i].system == 0xF || mbr[i].system == 0x5) {
178             struct partition_record ext[4];
179             uint8_t data1[512];
180             int j;
181
182             if ((ret = blk_read(blk, mbr[i].start_sector_abs, data1, 1)) < 0) {
183                 error_report("error while reading: %s", strerror(-ret));
184                 exit(EXIT_FAILURE);
185             }
186
187             for (j = 0; j < 4; j++) {
188                 read_partition(&data1[446 + 16 * j], &ext[j]);
189                 if (!ext[j].system || !ext[j].nb_sectors_abs) {
190                     continue;
191                 }
192
193                 if ((ext_partnum + j + 1) == partition) {
194                     *offset = (uint64_t)ext[j].start_sector_abs << 9;
195                     *size = (uint64_t)ext[j].nb_sectors_abs << 9;
196                     return 0;
197                 }
198             }
199             ext_partnum += 4;
200         } else if ((i + 1) == partition) {
201             *offset = (uint64_t)mbr[i].start_sector_abs << 9;
202             *size = (uint64_t)mbr[i].nb_sectors_abs << 9;
203             return 0;
204         }
205     }
206
207     return -ENOENT;
208 }
209
210 static void termsig_handler(int signum)
211 {
212     state = TERMINATE;
213     qemu_notify_event();
214 }
215
216
217 static void *show_parts(void *arg)
218 {
219     char *device = arg;
220     int nbd;
221
222     /* linux just needs an open() to trigger
223      * the partition table update
224      * but remember to load the module with max_part != 0 :
225      *     modprobe nbd max_part=63
226      */
227     nbd = open(device, O_RDWR);
228     if (nbd >= 0) {
229         close(nbd);
230     }
231     return NULL;
232 }
233
234 static void *nbd_client_thread(void *arg)
235 {
236     char *device = arg;
237     off_t size;
238     uint32_t nbdflags;
239     QIOChannelSocket *sioc;
240     int fd;
241     int ret;
242     pthread_t show_parts_thread;
243     Error *local_error = NULL;
244
245     sioc = qio_channel_socket_new();
246     if (qio_channel_socket_connect_sync(sioc,
247                                         saddr,
248                                         &local_error) < 0) {
249         error_report_err(local_error);
250         goto out;
251     }
252
253     ret = nbd_receive_negotiate(QIO_CHANNEL(sioc), NULL, &nbdflags,
254                                 &size, &local_error);
255     if (ret < 0) {
256         if (local_error) {
257             error_report_err(local_error);
258         }
259         goto out_socket;
260     }
261
262     fd = open(device, O_RDWR);
263     if (fd < 0) {
264         /* Linux-only, we can use %m in printf.  */
265         error_report("Failed to open %s: %m", device);
266         goto out_socket;
267     }
268
269     ret = nbd_init(fd, sioc, nbdflags, size);
270     if (ret < 0) {
271         goto out_fd;
272     }
273
274     /* update partition table */
275     pthread_create(&show_parts_thread, NULL, show_parts, device);
276
277     if (verbose) {
278         fprintf(stderr, "NBD device %s is now connected to %s\n",
279                 device, srcpath);
280     } else {
281         /* Close stderr so that the qemu-nbd process exits.  */
282         dup2(STDOUT_FILENO, STDERR_FILENO);
283     }
284
285     ret = nbd_client(fd);
286     if (ret) {
287         goto out_fd;
288     }
289     close(fd);
290     object_unref(OBJECT(sioc));
291     kill(getpid(), SIGTERM);
292     return (void *) EXIT_SUCCESS;
293
294 out_fd:
295     close(fd);
296 out_socket:
297     object_unref(OBJECT(sioc));
298 out:
299     kill(getpid(), SIGTERM);
300     return (void *) EXIT_FAILURE;
301 }
302
303 static int nbd_can_accept(void)
304 {
305     return nb_fds < shared;
306 }
307
308 static void nbd_export_closed(NBDExport *exp)
309 {
310     assert(state == TERMINATING);
311     state = TERMINATED;
312 }
313
314 static void nbd_update_server_watch(void);
315
316 static void nbd_client_closed(NBDClient *client)
317 {
318     nb_fds--;
319     if (nb_fds == 0 && !persistent && state == RUNNING) {
320         state = TERMINATE;
321     }
322     nbd_update_server_watch();
323     nbd_client_put(client);
324 }
325
326 static gboolean nbd_accept(QIOChannel *ioc, GIOCondition cond, gpointer opaque)
327 {
328     QIOChannelSocket *cioc;
329
330     cioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(ioc),
331                                      NULL);
332     if (!cioc) {
333         return TRUE;
334     }
335
336     if (state >= TERMINATE) {
337         object_unref(OBJECT(cioc));
338         return TRUE;
339     }
340
341     nb_fds++;
342     nbd_update_server_watch();
343     nbd_client_new(newproto ? NULL : exp, cioc, nbd_client_closed);
344     object_unref(OBJECT(cioc));
345
346     return TRUE;
347 }
348
349 static void nbd_update_server_watch(void)
350 {
351     if (nbd_can_accept()) {
352         if (server_watch == -1) {
353             server_watch = qio_channel_add_watch(QIO_CHANNEL(server_ioc),
354                                                  G_IO_IN,
355                                                  nbd_accept,
356                                                  NULL, NULL);
357         }
358     } else {
359         if (server_watch != -1) {
360             g_source_remove(server_watch);
361             server_watch = -1;
362         }
363     }
364 }
365
366
367 static SocketAddress *nbd_build_socket_address(const char *sockpath,
368                                                const char *bindto,
369                                                const char *port)
370 {
371     SocketAddress *saddr;
372
373     saddr = g_new0(SocketAddress, 1);
374     if (sockpath) {
375         saddr->type = SOCKET_ADDRESS_KIND_UNIX;
376         saddr->u.q_unix = g_new0(UnixSocketAddress, 1);
377         saddr->u.q_unix->path = g_strdup(sockpath);
378     } else {
379         saddr->type = SOCKET_ADDRESS_KIND_INET;
380         saddr->u.inet = g_new0(InetSocketAddress, 1);
381         saddr->u.inet->host = g_strdup(bindto);
382         if (port) {
383             saddr->u.inet->port = g_strdup(port);
384         } else  {
385             saddr->u.inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
386         }
387     }
388
389     return saddr;
390 }
391
392
393 static QemuOptsList qemu_object_opts = {
394     .name = "object",
395     .implied_opt_name = "qom-type",
396     .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
397     .desc = {
398         { }
399     },
400 };
401
402
403 int main(int argc, char **argv)
404 {
405     BlockBackend *blk;
406     BlockDriverState *bs;
407     off_t dev_offset = 0;
408     uint32_t nbdflags = 0;
409     bool disconnect = false;
410     const char *bindto = "0.0.0.0";
411     const char *port = NULL;
412     char *sockpath = NULL;
413     char *device = NULL;
414     off_t fd_size;
415     QemuOpts *sn_opts = NULL;
416     const char *sn_id_or_name = NULL;
417     const char *sopt = "hVb:o:p:rsnP:c:dvk:e:f:tl:x:";
418     struct option lopt[] = {
419         { "help", 0, NULL, 'h' },
420         { "version", 0, NULL, 'V' },
421         { "bind", 1, NULL, 'b' },
422         { "port", 1, NULL, 'p' },
423         { "socket", 1, NULL, 'k' },
424         { "offset", 1, NULL, 'o' },
425         { "read-only", 0, NULL, 'r' },
426         { "partition", 1, NULL, 'P' },
427         { "connect", 1, NULL, 'c' },
428         { "disconnect", 0, NULL, 'd' },
429         { "snapshot", 0, NULL, 's' },
430         { "load-snapshot", 1, NULL, 'l' },
431         { "nocache", 0, NULL, 'n' },
432         { "cache", 1, NULL, QEMU_NBD_OPT_CACHE },
433         { "aio", 1, NULL, QEMU_NBD_OPT_AIO },
434         { "discard", 1, NULL, QEMU_NBD_OPT_DISCARD },
435         { "detect-zeroes", 1, NULL, QEMU_NBD_OPT_DETECT_ZEROES },
436         { "shared", 1, NULL, 'e' },
437         { "format", 1, NULL, 'f' },
438         { "persistent", 0, NULL, 't' },
439         { "verbose", 0, NULL, 'v' },
440         { "object", 1, NULL, QEMU_NBD_OPT_OBJECT },
441         { "export-name", 1, NULL, 'x' },
442         { NULL, 0, NULL, 0 }
443     };
444     int ch;
445     int opt_ind = 0;
446     char *end;
447     int flags = BDRV_O_RDWR;
448     int partition = -1;
449     int ret = 0;
450     bool seen_cache = false;
451     bool seen_discard = false;
452     bool seen_aio = false;
453     pthread_t client_thread;
454     const char *fmt = NULL;
455     Error *local_err = NULL;
456     BlockdevDetectZeroesOptions detect_zeroes = BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
457     QDict *options = NULL;
458     const char *export_name = NULL;
459
460     /* The client thread uses SIGTERM to interrupt the server.  A signal
461      * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
462      */
463     struct sigaction sa_sigterm;
464     memset(&sa_sigterm, 0, sizeof(sa_sigterm));
465     sa_sigterm.sa_handler = termsig_handler;
466     sigaction(SIGTERM, &sa_sigterm, NULL);
467     module_call_init(MODULE_INIT_QOM);
468     qemu_add_opts(&qemu_object_opts);
469     qemu_init_exec_dir(argv[0]);
470
471     while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
472         switch (ch) {
473         case 's':
474             flags |= BDRV_O_SNAPSHOT;
475             break;
476         case 'n':
477             optarg = (char *) "none";
478             /* fallthrough */
479         case QEMU_NBD_OPT_CACHE:
480             if (seen_cache) {
481                 error_report("-n and --cache can only be specified once");
482                 exit(EXIT_FAILURE);
483             }
484             seen_cache = true;
485             if (bdrv_parse_cache_flags(optarg, &flags) == -1) {
486                 error_report("Invalid cache mode `%s'", optarg);
487                 exit(EXIT_FAILURE);
488             }
489             break;
490         case QEMU_NBD_OPT_AIO:
491             if (seen_aio) {
492                 error_report("--aio can only be specified once");
493                 exit(EXIT_FAILURE);
494             }
495             seen_aio = true;
496             if (!strcmp(optarg, "native")) {
497                 flags |= BDRV_O_NATIVE_AIO;
498             } else if (!strcmp(optarg, "threads")) {
499                 /* this is the default */
500             } else {
501                error_report("invalid aio mode `%s'", optarg);
502                exit(EXIT_FAILURE);
503             }
504             break;
505         case QEMU_NBD_OPT_DISCARD:
506             if (seen_discard) {
507                 error_report("--discard can only be specified once");
508                 exit(EXIT_FAILURE);
509             }
510             seen_discard = true;
511             if (bdrv_parse_discard_flags(optarg, &flags) == -1) {
512                 error_report("Invalid discard mode `%s'", optarg);
513                 exit(EXIT_FAILURE);
514             }
515             break;
516         case QEMU_NBD_OPT_DETECT_ZEROES:
517             detect_zeroes =
518                 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
519                                 optarg,
520                                 BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
521                                 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
522                                 &local_err);
523             if (local_err) {
524                 error_reportf_err(local_err,
525                                   "Failed to parse detect_zeroes mode: ");
526                 exit(EXIT_FAILURE);
527             }
528             if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
529                 !(flags & BDRV_O_UNMAP)) {
530                 error_report("setting detect-zeroes to unmap is not allowed "
531                              "without setting discard operation to unmap");
532                 exit(EXIT_FAILURE);
533             }
534             break;
535         case 'b':
536             bindto = optarg;
537             break;
538         case 'p':
539             port = optarg;
540             break;
541         case 'o':
542                 dev_offset = strtoll (optarg, &end, 0);
543             if (*end) {
544                 error_report("Invalid offset `%s'", optarg);
545                 exit(EXIT_FAILURE);
546             }
547             if (dev_offset < 0) {
548                 error_report("Offset must be positive `%s'", optarg);
549                 exit(EXIT_FAILURE);
550             }
551             break;
552         case 'l':
553             if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
554                 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
555                                                   optarg, false);
556                 if (!sn_opts) {
557                     error_report("Failed in parsing snapshot param `%s'",
558                                  optarg);
559                     exit(EXIT_FAILURE);
560                 }
561             } else {
562                 sn_id_or_name = optarg;
563             }
564             /* fall through */
565         case 'r':
566             nbdflags |= NBD_FLAG_READ_ONLY;
567             flags &= ~BDRV_O_RDWR;
568             break;
569         case 'P':
570             partition = strtol(optarg, &end, 0);
571             if (*end) {
572                 error_report("Invalid partition `%s'", optarg);
573                 exit(EXIT_FAILURE);
574             }
575             if (partition < 1 || partition > 8) {
576                 error_report("Invalid partition %d", partition);
577                 exit(EXIT_FAILURE);
578             }
579             break;
580         case 'k':
581             sockpath = optarg;
582             if (sockpath[0] != '/') {
583                 error_report("socket path must be absolute");
584                 exit(EXIT_FAILURE);
585             }
586             break;
587         case 'd':
588             disconnect = true;
589             break;
590         case 'c':
591             device = optarg;
592             break;
593         case 'e':
594             shared = strtol(optarg, &end, 0);
595             if (*end) {
596                 error_report("Invalid shared device number '%s'", optarg);
597                 exit(EXIT_FAILURE);
598             }
599             if (shared < 1) {
600                 error_report("Shared device number must be greater than 0");
601                 exit(EXIT_FAILURE);
602             }
603             break;
604         case 'f':
605             fmt = optarg;
606             break;
607         case 't':
608             persistent = 1;
609             break;
610         case 'x':
611             export_name = optarg;
612             break;
613         case 'v':
614             verbose = 1;
615             break;
616         case 'V':
617             version(argv[0]);
618             exit(0);
619             break;
620         case 'h':
621             usage(argv[0]);
622             exit(0);
623             break;
624         case '?':
625             error_report("Try `%s --help' for more information.", argv[0]);
626             exit(EXIT_FAILURE);
627         case QEMU_NBD_OPT_OBJECT: {
628             QemuOpts *opts;
629             opts = qemu_opts_parse_noisily(&qemu_object_opts,
630                                            optarg, true);
631             if (!opts) {
632                 exit(EXIT_FAILURE);
633             }
634         }   break;
635         }
636     }
637
638     if ((argc - optind) != 1) {
639         error_report("Invalid number of arguments");
640         error_printf("Try `%s --help' for more information.\n", argv[0]);
641         exit(EXIT_FAILURE);
642     }
643
644     if (qemu_opts_foreach(&qemu_object_opts,
645                           user_creatable_add_opts_foreach,
646                           NULL, &local_err)) {
647         error_report_err(local_err);
648         exit(EXIT_FAILURE);
649     }
650
651     if (disconnect) {
652         int nbdfd = open(argv[optind], O_RDWR);
653         if (nbdfd < 0) {
654             error_report("Cannot open %s: %s", argv[optind],
655                          strerror(errno));
656             exit(EXIT_FAILURE);
657         }
658         nbd_disconnect(nbdfd);
659
660         close(nbdfd);
661
662         printf("%s disconnected\n", argv[optind]);
663
664         return 0;
665     }
666
667     if (device && !verbose) {
668         int stderr_fd[2];
669         pid_t pid;
670         int ret;
671
672         if (qemu_pipe(stderr_fd) < 0) {
673             error_report("Error setting up communication pipe: %s",
674                          strerror(errno));
675             exit(EXIT_FAILURE);
676         }
677
678         /* Now daemonize, but keep a communication channel open to
679          * print errors and exit with the proper status code.
680          */
681         pid = fork();
682         if (pid < 0) {
683             error_report("Failed to fork: %s", strerror(errno));
684             exit(EXIT_FAILURE);
685         } else if (pid == 0) {
686             close(stderr_fd[0]);
687             ret = qemu_daemon(1, 0);
688
689             /* Temporarily redirect stderr to the parent's pipe...  */
690             dup2(stderr_fd[1], STDERR_FILENO);
691             if (ret < 0) {
692                 error_report("Failed to daemonize: %s", strerror(errno));
693                 exit(EXIT_FAILURE);
694             }
695
696             /* ... close the descriptor we inherited and go on.  */
697             close(stderr_fd[1]);
698         } else {
699             bool errors = false;
700             char *buf;
701
702             /* In the parent.  Print error messages from the child until
703              * it closes the pipe.
704              */
705             close(stderr_fd[1]);
706             buf = g_malloc(1024);
707             while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
708                 errors = true;
709                 ret = qemu_write_full(STDERR_FILENO, buf, ret);
710                 if (ret < 0) {
711                     exit(EXIT_FAILURE);
712                 }
713             }
714             if (ret < 0) {
715                 error_report("Cannot read from daemon: %s",
716                              strerror(errno));
717                 exit(EXIT_FAILURE);
718             }
719
720             /* Usually the daemon should not print any message.
721              * Exit with zero status in that case.
722              */
723             exit(errors);
724         }
725     }
726
727     if (device != NULL && sockpath == NULL) {
728         sockpath = g_malloc(128);
729         snprintf(sockpath, 128, SOCKET_PATH, basename(device));
730     }
731
732     saddr = nbd_build_socket_address(sockpath, bindto, port);
733
734     if (qemu_init_main_loop(&local_err)) {
735         error_report_err(local_err);
736         exit(EXIT_FAILURE);
737     }
738     bdrv_init();
739     atexit(bdrv_close_all);
740
741     if (fmt) {
742         options = qdict_new();
743         qdict_put(options, "driver", qstring_from_str(fmt));
744     }
745
746     srcpath = argv[optind];
747     blk = blk_new_open("hda", srcpath, NULL, options, flags, &local_err);
748     if (!blk) {
749         error_reportf_err(local_err, "Failed to blk_new_open '%s': ",
750                           argv[optind]);
751         exit(EXIT_FAILURE);
752     }
753     bs = blk_bs(blk);
754
755     if (sn_opts) {
756         ret = bdrv_snapshot_load_tmp(bs,
757                                      qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
758                                      qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
759                                      &local_err);
760     } else if (sn_id_or_name) {
761         ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
762                                                    &local_err);
763     }
764     if (ret < 0) {
765         error_reportf_err(local_err, "Failed to load snapshot: ");
766         exit(EXIT_FAILURE);
767     }
768
769     bs->detect_zeroes = detect_zeroes;
770     fd_size = blk_getlength(blk);
771     if (fd_size < 0) {
772         error_report("Failed to determine the image length: %s",
773                      strerror(-fd_size));
774         exit(EXIT_FAILURE);
775     }
776
777     if (partition != -1) {
778         ret = find_partition(blk, partition, &dev_offset, &fd_size);
779         if (ret < 0) {
780             error_report("Could not find partition %d: %s", partition,
781                          strerror(-ret));
782             exit(EXIT_FAILURE);
783         }
784     }
785
786     exp = nbd_export_new(blk, dev_offset, fd_size, nbdflags, nbd_export_closed,
787                          &local_err);
788     if (!exp) {
789         error_report_err(local_err);
790         exit(EXIT_FAILURE);
791     }
792     if (export_name) {
793         nbd_export_set_name(exp, export_name);
794         newproto = true;
795     }
796
797     server_ioc = qio_channel_socket_new();
798     if (qio_channel_socket_listen_sync(server_ioc, saddr, &local_err) < 0) {
799         object_unref(OBJECT(server_ioc));
800         error_report_err(local_err);
801         return 1;
802     }
803
804     if (device) {
805         int ret;
806
807         ret = pthread_create(&client_thread, NULL, nbd_client_thread, device);
808         if (ret != 0) {
809             error_report("Failed to create client thread: %s", strerror(ret));
810             exit(EXIT_FAILURE);
811         }
812     } else {
813         /* Shut up GCC warnings.  */
814         memset(&client_thread, 0, sizeof(client_thread));
815     }
816
817     nbd_update_server_watch();
818
819     /* now when the initialization is (almost) complete, chdir("/")
820      * to free any busy filesystems */
821     if (chdir("/") < 0) {
822         error_report("Could not chdir to root directory: %s",
823                      strerror(errno));
824         exit(EXIT_FAILURE);
825     }
826
827     state = RUNNING;
828     do {
829         main_loop_wait(false);
830         if (state == TERMINATE) {
831             state = TERMINATING;
832             nbd_export_close(exp);
833             nbd_export_put(exp);
834             exp = NULL;
835         }
836     } while (state != TERMINATED);
837
838     blk_unref(blk);
839     if (sockpath) {
840         unlink(sockpath);
841     }
842
843     qemu_opts_del(sn_opts);
844
845     if (device) {
846         void *ret;
847         pthread_join(client_thread, &ret);
848         exit(ret != NULL);
849     } else {
850         exit(EXIT_SUCCESS);
851     }
852 }