nbd: implement TLS support in the protocol negotiation
[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                                 NULL, NULL, NULL,
255                                 &size, &local_error);
256     if (ret < 0) {
257         if (local_error) {
258             error_report_err(local_error);
259         }
260         goto out_socket;
261     }
262
263     fd = open(device, O_RDWR);
264     if (fd < 0) {
265         /* Linux-only, we can use %m in printf.  */
266         error_report("Failed to open %s: %m", device);
267         goto out_socket;
268     }
269
270     ret = nbd_init(fd, sioc, nbdflags, size);
271     if (ret < 0) {
272         goto out_fd;
273     }
274
275     /* update partition table */
276     pthread_create(&show_parts_thread, NULL, show_parts, device);
277
278     if (verbose) {
279         fprintf(stderr, "NBD device %s is now connected to %s\n",
280                 device, srcpath);
281     } else {
282         /* Close stderr so that the qemu-nbd process exits.  */
283         dup2(STDOUT_FILENO, STDERR_FILENO);
284     }
285
286     ret = nbd_client(fd);
287     if (ret) {
288         goto out_fd;
289     }
290     close(fd);
291     object_unref(OBJECT(sioc));
292     kill(getpid(), SIGTERM);
293     return (void *) EXIT_SUCCESS;
294
295 out_fd:
296     close(fd);
297 out_socket:
298     object_unref(OBJECT(sioc));
299 out:
300     kill(getpid(), SIGTERM);
301     return (void *) EXIT_FAILURE;
302 }
303
304 static int nbd_can_accept(void)
305 {
306     return nb_fds < shared;
307 }
308
309 static void nbd_export_closed(NBDExport *exp)
310 {
311     assert(state == TERMINATING);
312     state = TERMINATED;
313 }
314
315 static void nbd_update_server_watch(void);
316
317 static void nbd_client_closed(NBDClient *client)
318 {
319     nb_fds--;
320     if (nb_fds == 0 && !persistent && state == RUNNING) {
321         state = TERMINATE;
322     }
323     nbd_update_server_watch();
324     nbd_client_put(client);
325 }
326
327 static gboolean nbd_accept(QIOChannel *ioc, GIOCondition cond, gpointer opaque)
328 {
329     QIOChannelSocket *cioc;
330
331     cioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(ioc),
332                                      NULL);
333     if (!cioc) {
334         return TRUE;
335     }
336
337     if (state >= TERMINATE) {
338         object_unref(OBJECT(cioc));
339         return TRUE;
340     }
341
342     nb_fds++;
343     nbd_update_server_watch();
344     nbd_client_new(newproto ? NULL : exp, cioc,
345                    NULL, NULL, nbd_client_closed);
346     object_unref(OBJECT(cioc));
347
348     return TRUE;
349 }
350
351 static void nbd_update_server_watch(void)
352 {
353     if (nbd_can_accept()) {
354         if (server_watch == -1) {
355             server_watch = qio_channel_add_watch(QIO_CHANNEL(server_ioc),
356                                                  G_IO_IN,
357                                                  nbd_accept,
358                                                  NULL, NULL);
359         }
360     } else {
361         if (server_watch != -1) {
362             g_source_remove(server_watch);
363             server_watch = -1;
364         }
365     }
366 }
367
368
369 static SocketAddress *nbd_build_socket_address(const char *sockpath,
370                                                const char *bindto,
371                                                const char *port)
372 {
373     SocketAddress *saddr;
374
375     saddr = g_new0(SocketAddress, 1);
376     if (sockpath) {
377         saddr->type = SOCKET_ADDRESS_KIND_UNIX;
378         saddr->u.q_unix = g_new0(UnixSocketAddress, 1);
379         saddr->u.q_unix->path = g_strdup(sockpath);
380     } else {
381         saddr->type = SOCKET_ADDRESS_KIND_INET;
382         saddr->u.inet = g_new0(InetSocketAddress, 1);
383         saddr->u.inet->host = g_strdup(bindto);
384         if (port) {
385             saddr->u.inet->port = g_strdup(port);
386         } else  {
387             saddr->u.inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
388         }
389     }
390
391     return saddr;
392 }
393
394
395 static QemuOptsList qemu_object_opts = {
396     .name = "object",
397     .implied_opt_name = "qom-type",
398     .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
399     .desc = {
400         { }
401     },
402 };
403
404
405 int main(int argc, char **argv)
406 {
407     BlockBackend *blk;
408     BlockDriverState *bs;
409     off_t dev_offset = 0;
410     uint32_t nbdflags = 0;
411     bool disconnect = false;
412     const char *bindto = "0.0.0.0";
413     const char *port = NULL;
414     char *sockpath = NULL;
415     char *device = NULL;
416     off_t fd_size;
417     QemuOpts *sn_opts = NULL;
418     const char *sn_id_or_name = NULL;
419     const char *sopt = "hVb:o:p:rsnP:c:dvk:e:f:tl:x:";
420     struct option lopt[] = {
421         { "help", 0, NULL, 'h' },
422         { "version", 0, NULL, 'V' },
423         { "bind", 1, NULL, 'b' },
424         { "port", 1, NULL, 'p' },
425         { "socket", 1, NULL, 'k' },
426         { "offset", 1, NULL, 'o' },
427         { "read-only", 0, NULL, 'r' },
428         { "partition", 1, NULL, 'P' },
429         { "connect", 1, NULL, 'c' },
430         { "disconnect", 0, NULL, 'd' },
431         { "snapshot", 0, NULL, 's' },
432         { "load-snapshot", 1, NULL, 'l' },
433         { "nocache", 0, NULL, 'n' },
434         { "cache", 1, NULL, QEMU_NBD_OPT_CACHE },
435         { "aio", 1, NULL, QEMU_NBD_OPT_AIO },
436         { "discard", 1, NULL, QEMU_NBD_OPT_DISCARD },
437         { "detect-zeroes", 1, NULL, QEMU_NBD_OPT_DETECT_ZEROES },
438         { "shared", 1, NULL, 'e' },
439         { "format", 1, NULL, 'f' },
440         { "persistent", 0, NULL, 't' },
441         { "verbose", 0, NULL, 'v' },
442         { "object", 1, NULL, QEMU_NBD_OPT_OBJECT },
443         { "export-name", 1, NULL, 'x' },
444         { NULL, 0, NULL, 0 }
445     };
446     int ch;
447     int opt_ind = 0;
448     char *end;
449     int flags = BDRV_O_RDWR;
450     int partition = -1;
451     int ret = 0;
452     bool seen_cache = false;
453     bool seen_discard = false;
454     bool seen_aio = false;
455     pthread_t client_thread;
456     const char *fmt = NULL;
457     Error *local_err = NULL;
458     BlockdevDetectZeroesOptions detect_zeroes = BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
459     QDict *options = NULL;
460     const char *export_name = NULL;
461
462     /* The client thread uses SIGTERM to interrupt the server.  A signal
463      * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
464      */
465     struct sigaction sa_sigterm;
466     memset(&sa_sigterm, 0, sizeof(sa_sigterm));
467     sa_sigterm.sa_handler = termsig_handler;
468     sigaction(SIGTERM, &sa_sigterm, NULL);
469     module_call_init(MODULE_INIT_QOM);
470     qemu_add_opts(&qemu_object_opts);
471     qemu_init_exec_dir(argv[0]);
472
473     while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
474         switch (ch) {
475         case 's':
476             flags |= BDRV_O_SNAPSHOT;
477             break;
478         case 'n':
479             optarg = (char *) "none";
480             /* fallthrough */
481         case QEMU_NBD_OPT_CACHE:
482             if (seen_cache) {
483                 error_report("-n and --cache can only be specified once");
484                 exit(EXIT_FAILURE);
485             }
486             seen_cache = true;
487             if (bdrv_parse_cache_flags(optarg, &flags) == -1) {
488                 error_report("Invalid cache mode `%s'", optarg);
489                 exit(EXIT_FAILURE);
490             }
491             break;
492         case QEMU_NBD_OPT_AIO:
493             if (seen_aio) {
494                 error_report("--aio can only be specified once");
495                 exit(EXIT_FAILURE);
496             }
497             seen_aio = true;
498             if (!strcmp(optarg, "native")) {
499                 flags |= BDRV_O_NATIVE_AIO;
500             } else if (!strcmp(optarg, "threads")) {
501                 /* this is the default */
502             } else {
503                error_report("invalid aio mode `%s'", optarg);
504                exit(EXIT_FAILURE);
505             }
506             break;
507         case QEMU_NBD_OPT_DISCARD:
508             if (seen_discard) {
509                 error_report("--discard can only be specified once");
510                 exit(EXIT_FAILURE);
511             }
512             seen_discard = true;
513             if (bdrv_parse_discard_flags(optarg, &flags) == -1) {
514                 error_report("Invalid discard mode `%s'", optarg);
515                 exit(EXIT_FAILURE);
516             }
517             break;
518         case QEMU_NBD_OPT_DETECT_ZEROES:
519             detect_zeroes =
520                 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
521                                 optarg,
522                                 BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
523                                 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
524                                 &local_err);
525             if (local_err) {
526                 error_reportf_err(local_err,
527                                   "Failed to parse detect_zeroes mode: ");
528                 exit(EXIT_FAILURE);
529             }
530             if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
531                 !(flags & BDRV_O_UNMAP)) {
532                 error_report("setting detect-zeroes to unmap is not allowed "
533                              "without setting discard operation to unmap");
534                 exit(EXIT_FAILURE);
535             }
536             break;
537         case 'b':
538             bindto = optarg;
539             break;
540         case 'p':
541             port = optarg;
542             break;
543         case 'o':
544                 dev_offset = strtoll (optarg, &end, 0);
545             if (*end) {
546                 error_report("Invalid offset `%s'", optarg);
547                 exit(EXIT_FAILURE);
548             }
549             if (dev_offset < 0) {
550                 error_report("Offset must be positive `%s'", optarg);
551                 exit(EXIT_FAILURE);
552             }
553             break;
554         case 'l':
555             if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
556                 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
557                                                   optarg, false);
558                 if (!sn_opts) {
559                     error_report("Failed in parsing snapshot param `%s'",
560                                  optarg);
561                     exit(EXIT_FAILURE);
562                 }
563             } else {
564                 sn_id_or_name = optarg;
565             }
566             /* fall through */
567         case 'r':
568             nbdflags |= NBD_FLAG_READ_ONLY;
569             flags &= ~BDRV_O_RDWR;
570             break;
571         case 'P':
572             partition = strtol(optarg, &end, 0);
573             if (*end) {
574                 error_report("Invalid partition `%s'", optarg);
575                 exit(EXIT_FAILURE);
576             }
577             if (partition < 1 || partition > 8) {
578                 error_report("Invalid partition %d", partition);
579                 exit(EXIT_FAILURE);
580             }
581             break;
582         case 'k':
583             sockpath = optarg;
584             if (sockpath[0] != '/') {
585                 error_report("socket path must be absolute");
586                 exit(EXIT_FAILURE);
587             }
588             break;
589         case 'd':
590             disconnect = true;
591             break;
592         case 'c':
593             device = optarg;
594             break;
595         case 'e':
596             shared = strtol(optarg, &end, 0);
597             if (*end) {
598                 error_report("Invalid shared device number '%s'", optarg);
599                 exit(EXIT_FAILURE);
600             }
601             if (shared < 1) {
602                 error_report("Shared device number must be greater than 0");
603                 exit(EXIT_FAILURE);
604             }
605             break;
606         case 'f':
607             fmt = optarg;
608             break;
609         case 't':
610             persistent = 1;
611             break;
612         case 'x':
613             export_name = optarg;
614             break;
615         case 'v':
616             verbose = 1;
617             break;
618         case 'V':
619             version(argv[0]);
620             exit(0);
621             break;
622         case 'h':
623             usage(argv[0]);
624             exit(0);
625             break;
626         case '?':
627             error_report("Try `%s --help' for more information.", argv[0]);
628             exit(EXIT_FAILURE);
629         case QEMU_NBD_OPT_OBJECT: {
630             QemuOpts *opts;
631             opts = qemu_opts_parse_noisily(&qemu_object_opts,
632                                            optarg, true);
633             if (!opts) {
634                 exit(EXIT_FAILURE);
635             }
636         }   break;
637         }
638     }
639
640     if ((argc - optind) != 1) {
641         error_report("Invalid number of arguments");
642         error_printf("Try `%s --help' for more information.\n", argv[0]);
643         exit(EXIT_FAILURE);
644     }
645
646     if (qemu_opts_foreach(&qemu_object_opts,
647                           user_creatable_add_opts_foreach,
648                           NULL, &local_err)) {
649         error_report_err(local_err);
650         exit(EXIT_FAILURE);
651     }
652
653     if (disconnect) {
654         int nbdfd = open(argv[optind], O_RDWR);
655         if (nbdfd < 0) {
656             error_report("Cannot open %s: %s", argv[optind],
657                          strerror(errno));
658             exit(EXIT_FAILURE);
659         }
660         nbd_disconnect(nbdfd);
661
662         close(nbdfd);
663
664         printf("%s disconnected\n", argv[optind]);
665
666         return 0;
667     }
668
669     if (device && !verbose) {
670         int stderr_fd[2];
671         pid_t pid;
672         int ret;
673
674         if (qemu_pipe(stderr_fd) < 0) {
675             error_report("Error setting up communication pipe: %s",
676                          strerror(errno));
677             exit(EXIT_FAILURE);
678         }
679
680         /* Now daemonize, but keep a communication channel open to
681          * print errors and exit with the proper status code.
682          */
683         pid = fork();
684         if (pid < 0) {
685             error_report("Failed to fork: %s", strerror(errno));
686             exit(EXIT_FAILURE);
687         } else if (pid == 0) {
688             close(stderr_fd[0]);
689             ret = qemu_daemon(1, 0);
690
691             /* Temporarily redirect stderr to the parent's pipe...  */
692             dup2(stderr_fd[1], STDERR_FILENO);
693             if (ret < 0) {
694                 error_report("Failed to daemonize: %s", strerror(errno));
695                 exit(EXIT_FAILURE);
696             }
697
698             /* ... close the descriptor we inherited and go on.  */
699             close(stderr_fd[1]);
700         } else {
701             bool errors = false;
702             char *buf;
703
704             /* In the parent.  Print error messages from the child until
705              * it closes the pipe.
706              */
707             close(stderr_fd[1]);
708             buf = g_malloc(1024);
709             while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
710                 errors = true;
711                 ret = qemu_write_full(STDERR_FILENO, buf, ret);
712                 if (ret < 0) {
713                     exit(EXIT_FAILURE);
714                 }
715             }
716             if (ret < 0) {
717                 error_report("Cannot read from daemon: %s",
718                              strerror(errno));
719                 exit(EXIT_FAILURE);
720             }
721
722             /* Usually the daemon should not print any message.
723              * Exit with zero status in that case.
724              */
725             exit(errors);
726         }
727     }
728
729     if (device != NULL && sockpath == NULL) {
730         sockpath = g_malloc(128);
731         snprintf(sockpath, 128, SOCKET_PATH, basename(device));
732     }
733
734     saddr = nbd_build_socket_address(sockpath, bindto, port);
735
736     if (qemu_init_main_loop(&local_err)) {
737         error_report_err(local_err);
738         exit(EXIT_FAILURE);
739     }
740     bdrv_init();
741     atexit(bdrv_close_all);
742
743     if (fmt) {
744         options = qdict_new();
745         qdict_put(options, "driver", qstring_from_str(fmt));
746     }
747
748     srcpath = argv[optind];
749     blk = blk_new_open("hda", srcpath, NULL, options, flags, &local_err);
750     if (!blk) {
751         error_reportf_err(local_err, "Failed to blk_new_open '%s': ",
752                           argv[optind]);
753         exit(EXIT_FAILURE);
754     }
755     bs = blk_bs(blk);
756
757     if (sn_opts) {
758         ret = bdrv_snapshot_load_tmp(bs,
759                                      qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
760                                      qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
761                                      &local_err);
762     } else if (sn_id_or_name) {
763         ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
764                                                    &local_err);
765     }
766     if (ret < 0) {
767         error_reportf_err(local_err, "Failed to load snapshot: ");
768         exit(EXIT_FAILURE);
769     }
770
771     bs->detect_zeroes = detect_zeroes;
772     fd_size = blk_getlength(blk);
773     if (fd_size < 0) {
774         error_report("Failed to determine the image length: %s",
775                      strerror(-fd_size));
776         exit(EXIT_FAILURE);
777     }
778
779     if (partition != -1) {
780         ret = find_partition(blk, partition, &dev_offset, &fd_size);
781         if (ret < 0) {
782             error_report("Could not find partition %d: %s", partition,
783                          strerror(-ret));
784             exit(EXIT_FAILURE);
785         }
786     }
787
788     exp = nbd_export_new(blk, dev_offset, fd_size, nbdflags, nbd_export_closed,
789                          &local_err);
790     if (!exp) {
791         error_report_err(local_err);
792         exit(EXIT_FAILURE);
793     }
794     if (export_name) {
795         nbd_export_set_name(exp, export_name);
796         newproto = true;
797     }
798
799     server_ioc = qio_channel_socket_new();
800     if (qio_channel_socket_listen_sync(server_ioc, saddr, &local_err) < 0) {
801         object_unref(OBJECT(server_ioc));
802         error_report_err(local_err);
803         return 1;
804     }
805
806     if (device) {
807         int ret;
808
809         ret = pthread_create(&client_thread, NULL, nbd_client_thread, device);
810         if (ret != 0) {
811             error_report("Failed to create client thread: %s", strerror(ret));
812             exit(EXIT_FAILURE);
813         }
814     } else {
815         /* Shut up GCC warnings.  */
816         memset(&client_thread, 0, sizeof(client_thread));
817     }
818
819     nbd_update_server_watch();
820
821     /* now when the initialization is (almost) complete, chdir("/")
822      * to free any busy filesystems */
823     if (chdir("/") < 0) {
824         error_report("Could not chdir to root directory: %s",
825                      strerror(errno));
826         exit(EXIT_FAILURE);
827     }
828
829     state = RUNNING;
830     do {
831         main_loop_wait(false);
832         if (state == TERMINATE) {
833             state = TERMINATING;
834             nbd_export_close(exp);
835             nbd_export_put(exp);
836             exp = NULL;
837         }
838     } while (state != TERMINATED);
839
840     blk_unref(blk);
841     if (sockpath) {
842         unlink(sockpath);
843     }
844
845     qemu_opts_del(sn_opts);
846
847     if (device) {
848         void *ret;
849         pthread_join(client_thread, &ret);
850         exit(ret != NULL);
851     } else {
852         exit(EXIT_SUCCESS);
853     }
854 }