blob: e4fede641ec443e04061ac39dcaf201a2ea7db04 [file] [log] [blame]
thscd831bd2008-07-03 10:23:51 +00001/*
bellard7a5ca862008-05-27 21:13:40 +00002 * 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
Blue Swirl8167ee82009-07-16 20:47:01 +000016 * along with this program; if not, see <http://www.gnu.org/licenses/>.
bellard7a5ca862008-05-27 21:13:40 +000017 */
18
Peter Maydelld38ea872016-01-29 17:50:05 +000019#include "qemu/osdep.h"
Markus Armbrusterda34e652016-03-14 09:01:28 +010020#include "qapi/error.h"
Stefan Weil5a61cb62011-09-08 17:55:32 +020021#include "qemu-common.h"
Veronia Bahaaf348b6d2016-03-20 19:16:19 +020022#include "qemu/cutils.h"
Markus Armbruster26f54e92014-10-07 13:59:04 +020023#include "sysemu/block-backend.h"
Peter Lievenb3838a42014-08-13 19:20:18 +020024#include "block/block_int.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010025#include "block/nbd.h"
Alex Bligh6a1751b2013-08-21 16:02:47 +010026#include "qemu/main-loop.h"
Paolo Bonzini537b41f2014-02-17 14:43:51 +010027#include "qemu/error-report.h"
Daniel P. Berrange0ab3b332016-02-10 18:41:00 +000028#include "qemu/config-file.h"
Paolo Bonzini58369e22016-03-15 17:22:36 +010029#include "qemu/bswap.h"
Denis V. Lunev39ca4632016-06-17 17:44:12 +030030#include "qemu/log.h"
Wenchao Xia8c116b02013-12-04 17:10:55 +080031#include "block/snapshot.h"
Peter Lievenb3838a42014-08-13 19:20:18 +020032#include "qapi/util.h"
Markus Armbrusterd49b6832015-03-17 18:29:20 +010033#include "qapi/qmp/qstring.h"
Daniel P. Berrange0ab3b332016-02-10 18:41:00 +000034#include "qom/object_interfaces.h"
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +000035#include "io/channel-socket.h"
Daniel P. Berrangec2297082016-04-06 12:12:06 +010036#include "crypto/init.h"
Denis V. Lunev39ca4632016-06-17 17:44:12 +030037#include "trace/control.h"
bellard7a5ca862008-05-27 21:13:40 +000038
bellard7a5ca862008-05-27 21:13:40 +000039#include <getopt.h>
Blue Swirl2bff4b62009-12-23 15:34:04 +000040#include <libgen.h>
Paolo Bonzinia517e882011-11-04 15:51:21 +010041#include <pthread.h>
thscd831bd2008-07-03 10:23:51 +000042
Peter Lieven713cc672014-08-13 19:20:19 +020043#define SOCKET_PATH "/var/lock/qemu-nbd-%s"
Daniel P. Berrangefa8b7ce2016-02-17 10:10:21 +000044#define QEMU_NBD_OPT_CACHE 256
45#define QEMU_NBD_OPT_AIO 257
46#define QEMU_NBD_OPT_DISCARD 258
47#define QEMU_NBD_OPT_DETECT_ZEROES 259
48#define QEMU_NBD_OPT_OBJECT 260
49#define QEMU_NBD_OPT_TLSCREDS 261
50#define QEMU_NBD_OPT_IMAGE_OPTS 262
Max Reitzffb31e12016-09-28 22:46:42 +020051#define QEMU_NBD_OPT_FORK 263
bellard7a5ca862008-05-27 21:13:40 +000052
Eric Blakebd31c212016-05-06 10:26:42 -060053#define MBR_SIZE 512
54
Paolo Bonziniaf49bbb2011-09-19 14:03:37 +020055static NBDExport *exp;
Daniel P. Berrange3d4b2f92016-02-10 18:41:08 +000056static bool newproto;
blueswir1b1d8e522008-10-26 13:43:07 +000057static int verbose;
Paolo Bonzinia517e882011-11-04 15:51:21 +010058static char *srcpath;
Daniel P. Berrange48bec072015-09-16 14:52:23 +010059static SocketAddress *saddr;
Paolo Bonzini7860a382012-09-18 13:31:56 +020060static int persistent = 0;
61static enum { RUNNING, TERMINATE, TERMINATING, TERMINATED } state;
Paolo Bonzinia61c6782011-09-12 17:28:11 +020062static int shared = 1;
63static int nb_fds;
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +000064static QIOChannelSocket *server_ioc;
65static int server_watch = -1;
Daniel P. Berrange145614a2016-02-10 18:41:13 +000066static QCryptoTLSCreds *tlscreds;
bellard7a5ca862008-05-27 21:13:40 +000067
68static void usage(const char *name)
69{
Paolo Bonzinib033cd82012-07-18 14:50:52 +020070 (printf) (
bellard7a5ca862008-05-27 21:13:40 +000071"Usage: %s [OPTIONS] FILE\n"
72"QEMU Disk Network Block Device Server\n"
73"\n"
Peter Lieven713cc672014-08-13 19:20:19 +020074" -h, --help display this help and exit\n"
75" -V, --version output version information and exit\n"
bellard7a5ca862008-05-27 21:13:40 +000076"\n"
Paolo Bonzinib033cd82012-07-18 14:50:52 +020077"Connection properties:\n"
Peter Lieven713cc672014-08-13 19:20:19 +020078" -p, --port=PORT port to listen on (default `%d')\n"
79" -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
80" -k, --socket=PATH path to the unix socket\n"
81" (default '"SOCKET_PATH"')\n"
82" -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
83" -t, --persistent don't exit on the last connection\n"
84" -v, --verbose display extra debugging information\n"
Eric Blake332a2542016-04-05 20:02:08 -060085" -x, --export-name=NAME expose export by name\n"
Eric Blakeb1a75b32016-10-14 13:33:03 -050086" -D, --description=TEXT with -x, also export a human-readable description\n"
Paolo Bonzinib033cd82012-07-18 14:50:52 +020087"\n"
88"Exposing part of the image:\n"
Peter Lieven713cc672014-08-13 19:20:19 +020089" -o, --offset=OFFSET offset into the image\n"
90" -P, --partition=NUM only expose partition NUM\n"
Paolo Bonzinib033cd82012-07-18 14:50:52 +020091"\n"
Daniel P. Berrange0ab3b332016-02-10 18:41:00 +000092"General purpose options:\n"
93" --object type,id=ID,... define an object such as 'secret' for providing\n"
94" passwords and/or encryption keys\n"
Denis V. Lunev39ca4632016-06-17 17:44:12 +030095" -T, --trace [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
96" specify tracing options\n"
Max Reitzffb31e12016-09-28 22:46:42 +020097" --fork fork off the server process and exit the parent\n"
98" once the server is running\n"
Paolo Bonzinib033cd82012-07-18 14:50:52 +020099#ifdef __linux__
100"Kernel NBD client support:\n"
Peter Lieven713cc672014-08-13 19:20:19 +0200101" -c, --connect=DEV connect FILE to the local NBD device DEV\n"
102" -d, --disconnect disconnect the specified device\n"
Paolo Bonzinib033cd82012-07-18 14:50:52 +0200103"\n"
104#endif
105"\n"
106"Block device options:\n"
Peter Lieven713cc672014-08-13 19:20:19 +0200107" -f, --format=FORMAT set image format (raw, qcow2, ...)\n"
108" -r, --read-only export read-only\n"
109" -s, --snapshot use FILE as an external snapshot, create a temporary\n"
110" file with backing_file=FILE, redirect the write to\n"
111" the temporary one\n"
Wenchao Xia8c116b02013-12-04 17:10:55 +0800112" -l, --load-snapshot=SNAPSHOT_PARAM\n"
Peter Lieven713cc672014-08-13 19:20:19 +0200113" load an internal snapshot inside FILE and export it\n"
114" as an read-only device, SNAPSHOT_PARAM format is\n"
115" 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
116" '[ID_OR_NAME]'\n"
117" -n, --nocache disable host cache\n"
118" --cache=MODE set cache mode (none, writeback, ...)\n"
Peter Lieven713cc672014-08-13 19:20:19 +0200119" --aio=MODE set AIO mode (native or threads)\n"
Peter Lievenb3838a42014-08-13 19:20:18 +0200120" --discard=MODE set discard mode (ignore, unmap)\n"
Andrey Korolyov6883de62015-07-31 22:12:54 +0300121" --detect-zeroes=MODE set detect-zeroes mode (off, on, unmap)\n"
Daniel P. Berrange77c9aae2016-02-17 10:10:19 +0000122" --image-opts treat FILE as a full set of image options\n"
Paolo Bonzinib033cd82012-07-18 14:50:52 +0200123"\n"
124"Report bugs to <qemu-devel@nongnu.org>\n"
Laurent Vivierc2e28722010-09-17 20:37:25 +0200125 , name, NBD_DEFAULT_PORT, "DEVICE");
bellard7a5ca862008-05-27 21:13:40 +0000126}
127
128static void version(const char *name)
129{
130 printf(
ths315bc7a2008-07-18 18:06:23 +0000131"%s version 0.0.1\n"
bellard7a5ca862008-05-27 21:13:40 +0000132"Written by Anthony Liguori.\n"
133"\n"
134"Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>.\n"
135"This is free software; see the source for copying conditions. There is NO\n"
136"warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
ths315bc7a2008-07-18 18:06:23 +0000137 , name);
bellard7a5ca862008-05-27 21:13:40 +0000138}
139
140struct partition_record
141{
142 uint8_t bootable;
143 uint8_t start_head;
144 uint32_t start_cylinder;
145 uint8_t start_sector;
146 uint8_t system;
147 uint8_t end_head;
148 uint8_t end_cylinder;
149 uint8_t end_sector;
150 uint32_t start_sector_abs;
151 uint32_t nb_sectors_abs;
152};
153
154static void read_partition(uint8_t *p, struct partition_record *r)
155{
156 r->bootable = p[0];
157 r->start_head = p[1];
158 r->start_cylinder = p[3] | ((p[2] << 2) & 0x0300);
159 r->start_sector = p[2] & 0x3f;
160 r->system = p[4];
161 r->end_head = p[5];
162 r->end_cylinder = p[7] | ((p[6] << 2) & 0x300);
163 r->end_sector = p[6] & 0x3f;
Max Reitzac973932015-02-25 13:08:23 -0500164
Peter Maydell773dce32016-06-10 16:00:36 +0100165 r->start_sector_abs = ldl_le_p(p + 8);
166 r->nb_sectors_abs = ldl_le_p(p + 12);
bellard7a5ca862008-05-27 21:13:40 +0000167}
168
Max Reitz4c58e802014-11-18 12:21:19 +0100169static int find_partition(BlockBackend *blk, int partition,
bellard7a5ca862008-05-27 21:13:40 +0000170 off_t *offset, off_t *size)
171{
172 struct partition_record mbr[4];
Eric Blakebd31c212016-05-06 10:26:42 -0600173 uint8_t data[MBR_SIZE];
bellard7a5ca862008-05-27 21:13:40 +0000174 int i;
175 int ext_partnum = 4;
Ryota Ozakicb7cf0e2010-05-03 06:50:25 +0900176 int ret;
bellard7a5ca862008-05-27 21:13:40 +0000177
Eric Blakebd31c212016-05-06 10:26:42 -0600178 ret = blk_pread(blk, 0, data, sizeof(data));
179 if (ret < 0) {
Markus Armbrustera4699e52015-12-18 16:35:10 +0100180 error_report("error while reading: %s", strerror(-ret));
Markus Armbruster85b01e02015-12-18 16:35:04 +0100181 exit(EXIT_FAILURE);
Ryota Ozakicb7cf0e2010-05-03 06:50:25 +0900182 }
bellard7a5ca862008-05-27 21:13:40 +0000183
184 if (data[510] != 0x55 || data[511] != 0xaa) {
Paolo Bonzini185b4332012-03-05 08:56:10 +0100185 return -EINVAL;
bellard7a5ca862008-05-27 21:13:40 +0000186 }
187
188 for (i = 0; i < 4; i++) {
189 read_partition(&data[446 + 16 * i], &mbr[i]);
190
Max Reitz453b07b2015-02-25 13:08:15 -0500191 if (!mbr[i].system || !mbr[i].nb_sectors_abs) {
bellard7a5ca862008-05-27 21:13:40 +0000192 continue;
Max Reitz453b07b2015-02-25 13:08:15 -0500193 }
bellard7a5ca862008-05-27 21:13:40 +0000194
195 if (mbr[i].system == 0xF || mbr[i].system == 0x5) {
196 struct partition_record ext[4];
Eric Blakebd31c212016-05-06 10:26:42 -0600197 uint8_t data1[MBR_SIZE];
bellard7a5ca862008-05-27 21:13:40 +0000198 int j;
199
Eric Blakebd31c212016-05-06 10:26:42 -0600200 ret = blk_pread(blk, mbr[i].start_sector_abs * MBR_SIZE,
201 data1, sizeof(data1));
202 if (ret < 0) {
Markus Armbrustera4699e52015-12-18 16:35:10 +0100203 error_report("error while reading: %s", strerror(-ret));
Markus Armbruster85b01e02015-12-18 16:35:04 +0100204 exit(EXIT_FAILURE);
Ryota Ozakicb7cf0e2010-05-03 06:50:25 +0900205 }
bellard7a5ca862008-05-27 21:13:40 +0000206
207 for (j = 0; j < 4; j++) {
208 read_partition(&data1[446 + 16 * j], &ext[j]);
Max Reitz453b07b2015-02-25 13:08:15 -0500209 if (!ext[j].system || !ext[j].nb_sectors_abs) {
bellard7a5ca862008-05-27 21:13:40 +0000210 continue;
Max Reitz453b07b2015-02-25 13:08:15 -0500211 }
bellard7a5ca862008-05-27 21:13:40 +0000212
213 if ((ext_partnum + j + 1) == partition) {
214 *offset = (uint64_t)ext[j].start_sector_abs << 9;
215 *size = (uint64_t)ext[j].nb_sectors_abs << 9;
216 return 0;
217 }
218 }
219 ext_partnum += 4;
220 } else if ((i + 1) == partition) {
221 *offset = (uint64_t)mbr[i].start_sector_abs << 9;
222 *size = (uint64_t)mbr[i].nb_sectors_abs << 9;
223 return 0;
224 }
225 }
226
Paolo Bonzini185b4332012-03-05 08:56:10 +0100227 return -ENOENT;
bellard7a5ca862008-05-27 21:13:40 +0000228}
229
Paolo Bonzinibb345112011-11-04 15:51:19 +0100230static void termsig_handler(int signum)
231{
Pavel Butsykin23994a52016-04-14 13:20:15 +0300232 atomic_cmpxchg(&state, RUNNING, TERMINATE);
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200233 qemu_notify_event();
Paolo Bonzinibb345112011-11-04 15:51:19 +0100234}
235
Paolo Bonzini537b41f2014-02-17 14:43:51 +0100236
Paolo Bonzinia517e882011-11-04 15:51:21 +0100237static void *show_parts(void *arg)
thscd831bd2008-07-03 10:23:51 +0000238{
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100239 char *device = arg;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100240 int nbd;
thscd831bd2008-07-03 10:23:51 +0000241
Paolo Bonzinia517e882011-11-04 15:51:21 +0100242 /* linux just needs an open() to trigger
243 * the partition table update
244 * but remember to load the module with max_part != 0 :
245 * modprobe nbd max_part=63
246 */
247 nbd = open(device, O_RDWR);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100248 if (nbd >= 0) {
Paolo Bonzinia517e882011-11-04 15:51:21 +0100249 close(nbd);
thscd831bd2008-07-03 10:23:51 +0000250 }
Paolo Bonzinia517e882011-11-04 15:51:21 +0100251 return NULL;
252}
253
254static void *nbd_client_thread(void *arg)
255{
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100256 char *device = arg;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100257 off_t size;
Eric Blake7423f412016-07-21 13:34:46 -0600258 uint16_t nbdflags;
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000259 QIOChannelSocket *sioc;
260 int fd;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100261 int ret;
262 pthread_t show_parts_thread;
Max Reitz1ce52842015-01-26 21:02:59 -0500263 Error *local_error = NULL;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100264
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000265 sioc = qio_channel_socket_new();
266 if (qio_channel_socket_connect_sync(sioc,
267 saddr,
268 &local_error) < 0) {
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100269 error_report_err(local_error);
Stefan Hajnoczidc10e8b2012-01-05 13:16:07 +0000270 goto out;
271 }
Paolo Bonzinia517e882011-11-04 15:51:21 +0100272
Daniel P. Berrange1c778ef2016-02-10 18:41:04 +0000273 ret = nbd_receive_negotiate(QIO_CHANNEL(sioc), NULL, &nbdflags,
Daniel P. Berrangef95910f2016-02-10 18:41:11 +0000274 NULL, NULL, NULL,
Max Reitz3f472652015-02-25 13:08:25 -0500275 &size, &local_error);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100276 if (ret < 0) {
Max Reitz1ce52842015-01-26 21:02:59 -0500277 if (local_error) {
Markus Armbruster78288672015-12-18 16:35:07 +0100278 error_report_err(local_error);
Max Reitz1ce52842015-01-26 21:02:59 -0500279 }
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100280 goto out_socket;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100281 }
282
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100283 fd = open(device, O_RDWR);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100284 if (fd < 0) {
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100285 /* Linux-only, we can use %m in printf. */
Markus Armbrusterb9884682015-12-18 16:35:18 +0100286 error_report("Failed to open %s: %m", device);
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100287 goto out_socket;
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100288 }
289
Daniel P. Berrange1c778ef2016-02-10 18:41:04 +0000290 ret = nbd_init(fd, sioc, nbdflags, size);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100291 if (ret < 0) {
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100292 goto out_fd;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100293 }
294
295 /* update partition table */
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100296 pthread_create(&show_parts_thread, NULL, show_parts, device);
Paolo Bonzinia517e882011-11-04 15:51:21 +0100297
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100298 if (verbose) {
299 fprintf(stderr, "NBD device %s is now connected to %s\n",
300 device, srcpath);
301 } else {
302 /* Close stderr so that the qemu-nbd process exits. */
303 dup2(STDOUT_FILENO, STDERR_FILENO);
304 }
Paolo Bonzinia517e882011-11-04 15:51:21 +0100305
306 ret = nbd_client(fd);
307 if (ret) {
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100308 goto out_fd;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100309 }
310 close(fd);
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000311 object_unref(OBJECT(sioc));
Paolo Bonzinia517e882011-11-04 15:51:21 +0100312 kill(getpid(), SIGTERM);
313 return (void *) EXIT_SUCCESS;
314
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100315out_fd:
316 close(fd);
317out_socket:
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000318 object_unref(OBJECT(sioc));
Paolo Bonzinia517e882011-11-04 15:51:21 +0100319out:
320 kill(getpid(), SIGTERM);
321 return (void *) EXIT_FAILURE;
thscd831bd2008-07-03 10:23:51 +0000322}
323
Fam Zhenge4afbf42015-05-19 10:50:59 +0000324static int nbd_can_accept(void)
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200325{
326 return nb_fds < shared;
327}
328
Paolo Bonzini7860a382012-09-18 13:31:56 +0200329static void nbd_export_closed(NBDExport *exp)
330{
331 assert(state == TERMINATING);
332 state = TERMINATED;
333}
334
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000335static void nbd_update_server_watch(void);
Fam Zhenge4afbf42015-05-19 10:50:59 +0000336
Paolo Bonzini1743b512011-09-19 14:33:23 +0200337static void nbd_client_closed(NBDClient *client)
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200338{
Paolo Bonzini1743b512011-09-19 14:33:23 +0200339 nb_fds--;
Paolo Bonzini7860a382012-09-18 13:31:56 +0200340 if (nb_fds == 0 && !persistent && state == RUNNING) {
341 state = TERMINATE;
342 }
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000343 nbd_update_server_watch();
Paolo Bonzini7860a382012-09-18 13:31:56 +0200344 nbd_client_put(client);
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200345}
346
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000347static gboolean nbd_accept(QIOChannel *ioc, GIOCondition cond, gpointer opaque)
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200348{
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000349 QIOChannelSocket *cioc;
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200350
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000351 cioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(ioc),
352 NULL);
353 if (!cioc) {
354 return TRUE;
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100355 }
356
Paolo Bonzini7860a382012-09-18 13:31:56 +0200357 if (state >= TERMINATE) {
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000358 object_unref(OBJECT(cioc));
359 return TRUE;
Paolo Bonzini7860a382012-09-18 13:31:56 +0200360 }
361
Fam Zhengee7d7aa2016-01-14 16:41:01 +0800362 nb_fds++;
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000363 nbd_update_server_watch();
Daniel P. Berrangef95910f2016-02-10 18:41:11 +0000364 nbd_client_new(newproto ? NULL : exp, cioc,
Daniel P. Berrange145614a2016-02-10 18:41:13 +0000365 tlscreds, NULL, nbd_client_closed);
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000366 object_unref(OBJECT(cioc));
367
368 return TRUE;
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200369}
370
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000371static void nbd_update_server_watch(void)
Fam Zhenge4afbf42015-05-19 10:50:59 +0000372{
373 if (nbd_can_accept()) {
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000374 if (server_watch == -1) {
375 server_watch = qio_channel_add_watch(QIO_CHANNEL(server_ioc),
376 G_IO_IN,
377 nbd_accept,
378 NULL, NULL);
379 }
Fam Zhenge4afbf42015-05-19 10:50:59 +0000380 } else {
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000381 if (server_watch != -1) {
382 g_source_remove(server_watch);
383 server_watch = -1;
384 }
Fam Zhenge4afbf42015-05-19 10:50:59 +0000385 }
386}
387
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100388
389static SocketAddress *nbd_build_socket_address(const char *sockpath,
390 const char *bindto,
391 const char *port)
392{
393 SocketAddress *saddr;
394
395 saddr = g_new0(SocketAddress, 1);
396 if (sockpath) {
Eric Blake2d32add2015-10-26 16:34:55 -0600397 saddr->type = SOCKET_ADDRESS_KIND_UNIX;
Eric Blake32bafa82016-03-17 16:48:37 -0600398 saddr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
399 saddr->u.q_unix.data->path = g_strdup(sockpath);
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100400 } else {
Eric Blake03992932016-03-03 09:16:48 -0700401 InetSocketAddress *inet;
Eric Blake2d32add2015-10-26 16:34:55 -0600402 saddr->type = SOCKET_ADDRESS_KIND_INET;
Eric Blake32bafa82016-03-17 16:48:37 -0600403 inet = saddr->u.inet.data = g_new0(InetSocketAddress, 1);
Eric Blake03992932016-03-03 09:16:48 -0700404 inet->host = g_strdup(bindto);
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100405 if (port) {
Eric Blake03992932016-03-03 09:16:48 -0700406 inet->port = g_strdup(port);
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100407 } else {
Eric Blake03992932016-03-03 09:16:48 -0700408 inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100409 }
410 }
411
412 return saddr;
413}
414
415
Daniel P. Berrange77c9aae2016-02-17 10:10:19 +0000416static QemuOptsList file_opts = {
417 .name = "file",
418 .implied_opt_name = "file",
419 .head = QTAILQ_HEAD_INITIALIZER(file_opts.head),
420 .desc = {
421 /* no elements => accept any params */
422 { /* end of list */ }
423 },
424};
425
Daniel P. Berrange0ab3b332016-02-10 18:41:00 +0000426static QemuOptsList qemu_object_opts = {
427 .name = "object",
428 .implied_opt_name = "qom-type",
429 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
430 .desc = {
431 { }
432 },
433};
434
435
Daniel P. Berrange145614a2016-02-10 18:41:13 +0000436
437static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, Error **errp)
438{
439 Object *obj;
440 QCryptoTLSCreds *creds;
441
442 obj = object_resolve_path_component(
443 object_get_objects_root(), id);
444 if (!obj) {
445 error_setg(errp, "No TLS credentials with id '%s'",
446 id);
447 return NULL;
448 }
449 creds = (QCryptoTLSCreds *)
450 object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
451 if (!creds) {
452 error_setg(errp, "Object with id '%s' is not TLS credentials",
453 id);
454 return NULL;
455 }
456
457 if (creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
458 error_setg(errp,
459 "Expecting TLS credentials with a server endpoint");
460 return NULL;
461 }
462 object_ref(obj);
463 return creds;
464}
465
Richard W.M. Jonesa721f532017-02-04 10:03:17 +0000466static void setup_address_and_port(const char **address, const char **port)
467{
468 if (*address == NULL) {
469 *address = "0.0.0.0";
470 }
471
472 if (*port == NULL) {
473 *port = stringify(NBD_DEFAULT_PORT);
474 }
475}
476
477#define FIRST_SOCKET_ACTIVATION_FD 3 /* defined by systemd ABI */
478
479#ifndef _WIN32
480/*
481 * Check if socket activation was requested via use of the
482 * LISTEN_FDS and LISTEN_PID environment variables.
483 *
484 * Returns 0 if no socket activation, or the number of FDs.
485 */
486static unsigned int check_socket_activation(void)
487{
488 const char *s;
489 unsigned long pid;
490 unsigned long nr_fds;
491 unsigned int i;
492 int fd;
493 int err;
494
495 s = getenv("LISTEN_PID");
496 if (s == NULL) {
497 return 0;
498 }
499 err = qemu_strtoul(s, NULL, 10, &pid);
500 if (err) {
501 if (verbose) {
502 fprintf(stderr, "malformed %s environment variable (ignored)\n",
503 "LISTEN_PID");
504 }
505 return 0;
506 }
507 if (pid != getpid()) {
508 if (verbose) {
509 fprintf(stderr, "%s was not for us (ignored)\n",
510 "LISTEN_PID");
511 }
512 return 0;
513 }
514
515 s = getenv("LISTEN_FDS");
516 if (s == NULL) {
517 return 0;
518 }
519 err = qemu_strtoul(s, NULL, 10, &nr_fds);
520 if (err) {
521 if (verbose) {
522 fprintf(stderr, "malformed %s environment variable (ignored)\n",
523 "LISTEN_FDS");
524 }
525 return 0;
526 }
527 assert(nr_fds <= UINT_MAX);
528
529 /* A limitation of current qemu-nbd is that it can only listen on
530 * a single socket. When that limitation is lifted, we can change
531 * this function to allow LISTEN_FDS > 1, and remove the assertion
532 * in the main function below.
533 */
534 if (nr_fds > 1) {
535 error_report("qemu-nbd does not support socket activation with %s > 1",
536 "LISTEN_FDS");
537 exit(EXIT_FAILURE);
538 }
539
540 /* So these are not passed to any child processes we might start. */
541 unsetenv("LISTEN_FDS");
542 unsetenv("LISTEN_PID");
543
544 /* So the file descriptors don't leak into child processes. */
545 for (i = 0; i < nr_fds; ++i) {
546 fd = FIRST_SOCKET_ACTIVATION_FD + i;
547 if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
548 /* If we cannot set FD_CLOEXEC then it probably means the file
549 * descriptor is invalid, so socket activation has gone wrong
550 * and we should exit.
551 */
552 error_report("Socket activation failed: "
553 "invalid file descriptor fd = %d: %m",
554 fd);
555 exit(EXIT_FAILURE);
556 }
557 }
558
559 return (unsigned int) nr_fds;
560}
561
562#else /* !_WIN32 */
563static unsigned int check_socket_activation(void)
564{
565 return 0;
566}
567#endif
568
569/*
570 * Check socket parameters compatibility when socket activation is used.
571 */
572static const char *socket_activation_validate_opts(const char *device,
573 const char *sockpath,
574 const char *address,
575 const char *port)
576{
577 if (device != NULL) {
578 return "NBD device can't be set when using socket activation";
579 }
580
581 if (sockpath != NULL) {
582 return "Unix socket can't be set when using socket activation";
583 }
584
585 if (address != NULL) {
586 return "The interface can't be set when using socket activation";
587 }
588
589 if (port != NULL) {
590 return "TCP port number can't be set when using socket activation";
591 }
592
593 return NULL;
594}
Daniel P. Berrange145614a2016-02-10 18:41:13 +0000595
bellard7a5ca862008-05-27 21:13:40 +0000596int main(int argc, char **argv)
597{
Markus Armbruster26f54e92014-10-07 13:59:04 +0200598 BlockBackend *blk;
bellard7a5ca862008-05-27 21:13:40 +0000599 BlockDriverState *bs;
600 off_t dev_offset = 0;
Eric Blake7423f412016-07-21 13:34:46 -0600601 uint16_t nbdflags = 0;
thscd831bd2008-07-03 10:23:51 +0000602 bool disconnect = false;
Richard W.M. Jonesa721f532017-02-04 10:03:17 +0000603 const char *bindto = NULL;
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100604 const char *port = NULL;
605 char *sockpath = NULL;
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100606 char *device = NULL;
bellard7a5ca862008-05-27 21:13:40 +0000607 off_t fd_size;
Wenchao Xia8c116b02013-12-04 17:10:55 +0800608 QemuOpts *sn_opts = NULL;
609 const char *sn_id_or_name = NULL;
Eric Blakeb1a75b32016-10-14 13:33:03 -0500610 const char *sopt = "hVb:o:p:rsnP:c:dvk:e:f:tl:x:T:D:";
bellard7a5ca862008-05-27 21:13:40 +0000611 struct option lopt[] = {
Daniel P. Berrangeaa6e5462016-02-17 10:10:22 +0000612 { "help", no_argument, NULL, 'h' },
613 { "version", no_argument, NULL, 'V' },
614 { "bind", required_argument, NULL, 'b' },
615 { "port", required_argument, NULL, 'p' },
616 { "socket", required_argument, NULL, 'k' },
617 { "offset", required_argument, NULL, 'o' },
618 { "read-only", no_argument, NULL, 'r' },
619 { "partition", required_argument, NULL, 'P' },
620 { "connect", required_argument, NULL, 'c' },
621 { "disconnect", no_argument, NULL, 'd' },
622 { "snapshot", no_argument, NULL, 's' },
623 { "load-snapshot", required_argument, NULL, 'l' },
624 { "nocache", no_argument, NULL, 'n' },
625 { "cache", required_argument, NULL, QEMU_NBD_OPT_CACHE },
626 { "aio", required_argument, NULL, QEMU_NBD_OPT_AIO },
627 { "discard", required_argument, NULL, QEMU_NBD_OPT_DISCARD },
628 { "detect-zeroes", required_argument, NULL,
629 QEMU_NBD_OPT_DETECT_ZEROES },
630 { "shared", required_argument, NULL, 'e' },
631 { "format", required_argument, NULL, 'f' },
632 { "persistent", no_argument, NULL, 't' },
633 { "verbose", no_argument, NULL, 'v' },
634 { "object", required_argument, NULL, QEMU_NBD_OPT_OBJECT },
635 { "export-name", required_argument, NULL, 'x' },
Eric Blakeb1a75b32016-10-14 13:33:03 -0500636 { "description", required_argument, NULL, 'D' },
Daniel P. Berrangeaa6e5462016-02-17 10:10:22 +0000637 { "tls-creds", required_argument, NULL, QEMU_NBD_OPT_TLSCREDS },
638 { "image-opts", no_argument, NULL, QEMU_NBD_OPT_IMAGE_OPTS },
Denis V. Lunev39ca4632016-06-17 17:44:12 +0300639 { "trace", required_argument, NULL, 'T' },
Max Reitzffb31e12016-09-28 22:46:42 +0200640 { "fork", no_argument, NULL, QEMU_NBD_OPT_FORK },
Blue Swirl660f11b2009-07-31 21:16:51 +0000641 { NULL, 0, NULL, 0 }
bellard7a5ca862008-05-27 21:13:40 +0000642 };
643 int ch;
644 int opt_ind = 0;
bellard7a5ca862008-05-27 21:13:40 +0000645 char *end;
Naphtali Spreif5edb012010-01-17 16:48:13 +0200646 int flags = BDRV_O_RDWR;
bellard7a5ca862008-05-27 21:13:40 +0000647 int partition = -1;
Max Reitz4fbec262015-02-05 13:58:19 -0500648 int ret = 0;
Paolo Bonzini39a52352012-07-18 14:57:15 +0200649 bool seen_cache = false;
Paolo Bonzinided9d2d2013-02-08 14:06:13 +0100650 bool seen_discard = false;
Paolo Bonzini39a52352012-07-18 14:57:15 +0200651 bool seen_aio = false;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100652 pthread_t client_thread;
Daniel P. Berrangee6b63672013-03-19 11:20:20 +0000653 const char *fmt = NULL;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200654 Error *local_err = NULL;
Peter Lievenb3838a42014-08-13 19:20:18 +0200655 BlockdevDetectZeroesOptions detect_zeroes = BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
Max Reitz4fbec262015-02-05 13:58:19 -0500656 QDict *options = NULL;
Daniel P. Berrange3d4b2f92016-02-10 18:41:08 +0000657 const char *export_name = NULL;
Eric Blakeb1a75b32016-10-14 13:33:03 -0500658 const char *export_description = NULL;
Daniel P. Berrange145614a2016-02-10 18:41:13 +0000659 const char *tlscredsid = NULL;
Daniel P. Berrange77c9aae2016-02-17 10:10:19 +0000660 bool imageOpts = false;
Kevin Wolf6effd5b2016-03-14 11:43:28 +0100661 bool writethrough = true;
Denis V. Lunev39ca4632016-06-17 17:44:12 +0300662 char *trace_file = NULL;
Max Reitzffb31e12016-09-28 22:46:42 +0200663 bool fork_process = false;
664 int old_stderr = -1;
Richard W.M. Jonesa721f532017-02-04 10:03:17 +0000665 unsigned socket_activation;
bellard7a5ca862008-05-27 21:13:40 +0000666
Paolo Bonzinia517e882011-11-04 15:51:21 +0100667 /* The client thread uses SIGTERM to interrupt the server. A signal
668 * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
669 */
Paolo Bonzinibb345112011-11-04 15:51:19 +0100670 struct sigaction sa_sigterm;
Paolo Bonzinibb345112011-11-04 15:51:19 +0100671 memset(&sa_sigterm, 0, sizeof(sa_sigterm));
672 sa_sigterm.sa_handler = termsig_handler;
673 sigaction(SIGTERM, &sa_sigterm, NULL);
Daniel P. Berrangec2297082016-04-06 12:12:06 +0100674
Daniel P. Berrangefe4db842016-10-04 14:35:52 +0100675 module_call_init(MODULE_INIT_TRACE);
Eduardo Habkoste8f2d272016-05-12 11:10:04 -0300676 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +0100677
Daniel P. Berrange0ab3b332016-02-10 18:41:00 +0000678 module_call_init(MODULE_INIT_QOM);
679 qemu_add_opts(&qemu_object_opts);
Denis V. Lunev39ca4632016-06-17 17:44:12 +0300680 qemu_add_opts(&qemu_trace_opts);
Fam Zheng10f5bff2014-02-10 14:48:51 +0800681 qemu_init_exec_dir(argv[0]);
Paolo Bonzinibb345112011-11-04 15:51:19 +0100682
bellard7a5ca862008-05-27 21:13:40 +0000683 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
684 switch (ch) {
685 case 's':
ths2f726482008-07-03 11:47:46 +0000686 flags |= BDRV_O_SNAPSHOT;
687 break;
688 case 'n':
Paolo Bonzini39a52352012-07-18 14:57:15 +0200689 optarg = (char *) "none";
690 /* fallthrough */
691 case QEMU_NBD_OPT_CACHE:
692 if (seen_cache) {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100693 error_report("-n and --cache can only be specified once");
694 exit(EXIT_FAILURE);
Paolo Bonzini39a52352012-07-18 14:57:15 +0200695 }
696 seen_cache = true;
Kevin Wolf6effd5b2016-03-14 11:43:28 +0100697 if (bdrv_parse_cache_mode(optarg, &flags, &writethrough) == -1) {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100698 error_report("Invalid cache mode `%s'", optarg);
699 exit(EXIT_FAILURE);
Paolo Bonzini39a52352012-07-18 14:57:15 +0200700 }
bellard7a5ca862008-05-27 21:13:40 +0000701 break;
Paolo Bonzini39a52352012-07-18 14:57:15 +0200702 case QEMU_NBD_OPT_AIO:
703 if (seen_aio) {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100704 error_report("--aio can only be specified once");
705 exit(EXIT_FAILURE);
Paolo Bonzini39a52352012-07-18 14:57:15 +0200706 }
707 seen_aio = true;
708 if (!strcmp(optarg, "native")) {
709 flags |= BDRV_O_NATIVE_AIO;
710 } else if (!strcmp(optarg, "threads")) {
711 /* this is the default */
712 } else {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100713 error_report("invalid aio mode `%s'", optarg);
714 exit(EXIT_FAILURE);
Paolo Bonzini39a52352012-07-18 14:57:15 +0200715 }
716 break;
Paolo Bonzinided9d2d2013-02-08 14:06:13 +0100717 case QEMU_NBD_OPT_DISCARD:
718 if (seen_discard) {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100719 error_report("--discard can only be specified once");
720 exit(EXIT_FAILURE);
Paolo Bonzinided9d2d2013-02-08 14:06:13 +0100721 }
722 seen_discard = true;
723 if (bdrv_parse_discard_flags(optarg, &flags) == -1) {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100724 error_report("Invalid discard mode `%s'", optarg);
725 exit(EXIT_FAILURE);
Paolo Bonzinided9d2d2013-02-08 14:06:13 +0100726 }
727 break;
Peter Lievenb3838a42014-08-13 19:20:18 +0200728 case QEMU_NBD_OPT_DETECT_ZEROES:
729 detect_zeroes =
730 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
731 optarg,
Eric Blake7fb1cf12015-11-18 01:52:57 -0700732 BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
Peter Lievenb3838a42014-08-13 19:20:18 +0200733 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
734 &local_err);
735 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100736 error_reportf_err(local_err,
737 "Failed to parse detect_zeroes mode: ");
Markus Armbruster85b01e02015-12-18 16:35:04 +0100738 exit(EXIT_FAILURE);
Peter Lievenb3838a42014-08-13 19:20:18 +0200739 }
740 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
741 !(flags & BDRV_O_UNMAP)) {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100742 error_report("setting detect-zeroes to unmap is not allowed "
743 "without setting discard operation to unmap");
744 exit(EXIT_FAILURE);
Peter Lievenb3838a42014-08-13 19:20:18 +0200745 }
746 break;
bellard7a5ca862008-05-27 21:13:40 +0000747 case 'b':
748 bindto = optarg;
749 break;
750 case 'p':
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100751 port = optarg;
bellard7a5ca862008-05-27 21:13:40 +0000752 break;
753 case 'o':
754 dev_offset = strtoll (optarg, &end, 0);
755 if (*end) {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100756 error_report("Invalid offset `%s'", optarg);
757 exit(EXIT_FAILURE);
bellard7a5ca862008-05-27 21:13:40 +0000758 }
759 if (dev_offset < 0) {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100760 error_report("Offset must be positive `%s'", optarg);
761 exit(EXIT_FAILURE);
bellard7a5ca862008-05-27 21:13:40 +0000762 }
763 break;
Wenchao Xia8c116b02013-12-04 17:10:55 +0800764 case 'l':
765 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +0100766 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
767 optarg, false);
Wenchao Xia8c116b02013-12-04 17:10:55 +0800768 if (!sn_opts) {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100769 error_report("Failed in parsing snapshot param `%s'",
770 optarg);
771 exit(EXIT_FAILURE);
Wenchao Xia8c116b02013-12-04 17:10:55 +0800772 }
773 } else {
774 sn_id_or_name = optarg;
775 }
776 /* fall through */
bellard7a5ca862008-05-27 21:13:40 +0000777 case 'r':
Paolo Bonzinib90fb4b2011-09-08 17:24:54 +0200778 nbdflags |= NBD_FLAG_READ_ONLY;
Naphtali Sprei07108b22010-03-14 15:19:57 +0200779 flags &= ~BDRV_O_RDWR;
bellard7a5ca862008-05-27 21:13:40 +0000780 break;
781 case 'P':
782 partition = strtol(optarg, &end, 0);
Peter Lieven713cc672014-08-13 19:20:19 +0200783 if (*end) {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100784 error_report("Invalid partition `%s'", optarg);
785 exit(EXIT_FAILURE);
Peter Lieven713cc672014-08-13 19:20:19 +0200786 }
787 if (partition < 1 || partition > 8) {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100788 error_report("Invalid partition %d", partition);
789 exit(EXIT_FAILURE);
Peter Lieven713cc672014-08-13 19:20:19 +0200790 }
bellard7a5ca862008-05-27 21:13:40 +0000791 break;
thscd831bd2008-07-03 10:23:51 +0000792 case 'k':
Paolo Bonzinib32f6c22011-11-04 15:51:20 +0100793 sockpath = optarg;
Peter Lieven713cc672014-08-13 19:20:19 +0200794 if (sockpath[0] != '/') {
Markus Armbruster9af9e0f2015-12-18 16:35:19 +0100795 error_report("socket path must be absolute");
Markus Armbruster85b01e02015-12-18 16:35:04 +0100796 exit(EXIT_FAILURE);
Peter Lieven713cc672014-08-13 19:20:19 +0200797 }
thscd831bd2008-07-03 10:23:51 +0000798 break;
799 case 'd':
800 disconnect = true;
801 break;
802 case 'c':
803 device = optarg;
804 break;
ths3b05a8e2008-07-03 12:45:02 +0000805 case 'e':
806 shared = strtol(optarg, &end, 0);
807 if (*end) {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100808 error_report("Invalid shared device number '%s'", optarg);
809 exit(EXIT_FAILURE);
ths3b05a8e2008-07-03 12:45:02 +0000810 }
811 if (shared < 1) {
Markus Armbruster9af9e0f2015-12-18 16:35:19 +0100812 error_report("Shared device number must be greater than 0");
Markus Armbruster85b01e02015-12-18 16:35:04 +0100813 exit(EXIT_FAILURE);
ths3b05a8e2008-07-03 12:45:02 +0000814 }
815 break;
Daniel P. Berrangee6b63672013-03-19 11:20:20 +0000816 case 'f':
817 fmt = optarg;
818 break;
Peter Lieven713cc672014-08-13 19:20:19 +0200819 case 't':
820 persistent = 1;
821 break;
Daniel P. Berrange3d4b2f92016-02-10 18:41:08 +0000822 case 'x':
823 export_name = optarg;
824 break;
Eric Blakeb1a75b32016-10-14 13:33:03 -0500825 case 'D':
826 export_description = optarg;
827 break;
bellard7a5ca862008-05-27 21:13:40 +0000828 case 'v':
829 verbose = 1;
830 break;
831 case 'V':
832 version(argv[0]);
833 exit(0);
834 break;
835 case 'h':
836 usage(argv[0]);
837 exit(0);
838 break;
839 case '?':
Markus Armbruster85b01e02015-12-18 16:35:04 +0100840 error_report("Try `%s --help' for more information.", argv[0]);
841 exit(EXIT_FAILURE);
Daniel P. Berrange0ab3b332016-02-10 18:41:00 +0000842 case QEMU_NBD_OPT_OBJECT: {
843 QemuOpts *opts;
844 opts = qemu_opts_parse_noisily(&qemu_object_opts,
845 optarg, true);
846 if (!opts) {
847 exit(EXIT_FAILURE);
848 }
849 } break;
Daniel P. Berrange145614a2016-02-10 18:41:13 +0000850 case QEMU_NBD_OPT_TLSCREDS:
851 tlscredsid = optarg;
852 break;
Daniel P. Berrange77c9aae2016-02-17 10:10:19 +0000853 case QEMU_NBD_OPT_IMAGE_OPTS:
854 imageOpts = true;
855 break;
Denis V. Lunev39ca4632016-06-17 17:44:12 +0300856 case 'T':
857 g_free(trace_file);
858 trace_file = trace_opt_parse(optarg);
859 break;
Max Reitzffb31e12016-09-28 22:46:42 +0200860 case QEMU_NBD_OPT_FORK:
861 fork_process = true;
862 break;
bellard7a5ca862008-05-27 21:13:40 +0000863 }
864 }
865
866 if ((argc - optind) != 1) {
Markus Armbruster433672b2015-12-18 16:35:24 +0100867 error_report("Invalid number of arguments");
868 error_printf("Try `%s --help' for more information.\n", argv[0]);
Markus Armbruster85b01e02015-12-18 16:35:04 +0100869 exit(EXIT_FAILURE);
bellard7a5ca862008-05-27 21:13:40 +0000870 }
871
Daniel P. Berrange0ab3b332016-02-10 18:41:00 +0000872 if (qemu_opts_foreach(&qemu_object_opts,
873 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200874 NULL, NULL)) {
Daniel P. Berrange0ab3b332016-02-10 18:41:00 +0000875 exit(EXIT_FAILURE);
876 }
877
Denis V. Lunev39ca4632016-06-17 17:44:12 +0300878 if (!trace_init_backends()) {
879 exit(1);
880 }
881 trace_init_file(trace_file);
882 qemu_set_log(LOG_TRACE);
883
Richard W.M. Jonesa721f532017-02-04 10:03:17 +0000884 socket_activation = check_socket_activation();
885 if (socket_activation == 0) {
886 setup_address_and_port(&bindto, &port);
887 } else {
888 /* Using socket activation - check user didn't use -p etc. */
889 const char *err_msg = socket_activation_validate_opts(device, sockpath,
890 bindto, port);
891 if (err_msg != NULL) {
892 error_report("%s", err_msg);
893 exit(EXIT_FAILURE);
894 }
895 }
896
Daniel P. Berrange145614a2016-02-10 18:41:13 +0000897 if (tlscredsid) {
898 if (sockpath) {
899 error_report("TLS is only supported with IPv4/IPv6");
900 exit(EXIT_FAILURE);
901 }
902 if (device) {
903 error_report("TLS is not supported with a host device");
904 exit(EXIT_FAILURE);
905 }
906 if (!export_name) {
907 /* Set the default NBD protocol export name, since
908 * we *must* use new style protocol for TLS */
909 export_name = "";
910 }
911 tlscreds = nbd_get_tls_creds(tlscredsid, &local_err);
912 if (local_err) {
913 error_report("Failed to get TLS creds %s",
914 error_get_pretty(local_err));
915 exit(EXIT_FAILURE);
916 }
917 }
918
thscd831bd2008-07-03 10:23:51 +0000919 if (disconnect) {
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000920 int nbdfd = open(argv[optind], O_RDWR);
921 if (nbdfd < 0) {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100922 error_report("Cannot open %s: %s", argv[optind],
923 strerror(errno));
924 exit(EXIT_FAILURE);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100925 }
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000926 nbd_disconnect(nbdfd);
thscd831bd2008-07-03 10:23:51 +0000927
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000928 close(nbdfd);
thscd831bd2008-07-03 10:23:51 +0000929
930 printf("%s disconnected\n", argv[optind]);
931
Peter Lieven713cc672014-08-13 19:20:19 +0200932 return 0;
thscd831bd2008-07-03 10:23:51 +0000933 }
934
Max Reitzffb31e12016-09-28 22:46:42 +0200935 if ((device && !verbose) || fork_process) {
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100936 int stderr_fd[2];
937 pid_t pid;
938 int ret;
939
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100940 if (qemu_pipe(stderr_fd) < 0) {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100941 error_report("Error setting up communication pipe: %s",
942 strerror(errno));
943 exit(EXIT_FAILURE);
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100944 }
945
946 /* Now daemonize, but keep a communication channel open to
947 * print errors and exit with the proper status code.
948 */
949 pid = fork();
Max Reitz70d47392015-02-25 13:08:22 -0500950 if (pid < 0) {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100951 error_report("Failed to fork: %s", strerror(errno));
952 exit(EXIT_FAILURE);
Max Reitz70d47392015-02-25 13:08:22 -0500953 } else if (pid == 0) {
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100954 close(stderr_fd[0]);
Michael Tokarev9faf31b2012-01-16 18:37:44 +0400955 ret = qemu_daemon(1, 0);
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100956
957 /* Temporarily redirect stderr to the parent's pipe... */
Max Reitzffb31e12016-09-28 22:46:42 +0200958 old_stderr = dup(STDERR_FILENO);
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100959 dup2(stderr_fd[1], STDERR_FILENO);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100960 if (ret < 0) {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100961 error_report("Failed to daemonize: %s", strerror(errno));
962 exit(EXIT_FAILURE);
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100963 }
964
965 /* ... close the descriptor we inherited and go on. */
966 close(stderr_fd[1]);
967 } else {
968 bool errors = false;
969 char *buf;
970
971 /* In the parent. Print error messages from the child until
972 * it closes the pipe.
973 */
974 close(stderr_fd[1]);
975 buf = g_malloc(1024);
976 while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
977 errors = true;
978 ret = qemu_write_full(STDERR_FILENO, buf, ret);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100979 if (ret < 0) {
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100980 exit(EXIT_FAILURE);
981 }
982 }
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100983 if (ret < 0) {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100984 error_report("Cannot read from daemon: %s",
985 strerror(errno));
986 exit(EXIT_FAILURE);
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100987 }
988
989 /* Usually the daemon should not print any message.
990 * Exit with zero status in that case.
991 */
992 exit(errors);
993 }
994 }
995
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100996 if (device != NULL && sockpath == NULL) {
997 sockpath = g_malloc(128);
998 snprintf(sockpath, 128, SOCKET_PATH, basename(device));
thscd831bd2008-07-03 10:23:51 +0000999 }
1000
Richard W.M. Jonesa721f532017-02-04 10:03:17 +00001001 if (socket_activation == 0) {
1002 server_ioc = qio_channel_socket_new();
1003 saddr = nbd_build_socket_address(sockpath, bindto, port);
1004 if (qio_channel_socket_listen_sync(server_ioc, saddr, &local_err) < 0) {
1005 object_unref(OBJECT(server_ioc));
1006 error_report_err(local_err);
1007 return 1;
1008 }
1009 } else {
1010 /* See comment in check_socket_activation above. */
1011 assert(socket_activation == 1);
1012 server_ioc = qio_channel_socket_new_fd(FIRST_SOCKET_ACTIVATION_FD,
1013 &local_err);
1014 if (server_ioc == NULL) {
1015 error_report("Failed to use socket activation: %s",
1016 error_get_pretty(local_err));
1017 exit(EXIT_FAILURE);
1018 }
1019 }
Daniel P. Berrange48bec072015-09-16 14:52:23 +01001020
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03001021 if (qemu_init_main_loop(&local_err)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01001022 error_report_err(local_err);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03001023 exit(EXIT_FAILURE);
1024 }
Paolo Bonzini802ddc32011-11-04 15:51:24 +01001025 bdrv_init();
1026 atexit(bdrv_close_all);
1027
Daniel P. Berrange77c9aae2016-02-17 10:10:19 +00001028 srcpath = argv[optind];
1029 if (imageOpts) {
1030 QemuOpts *opts;
1031 if (fmt) {
1032 error_report("--image-opts and -f are mutually exclusive");
1033 exit(EXIT_FAILURE);
1034 }
1035 opts = qemu_opts_parse_noisily(&file_opts, srcpath, true);
1036 if (!opts) {
1037 qemu_opts_reset(&file_opts);
1038 exit(EXIT_FAILURE);
1039 }
1040 options = qemu_opts_to_qdict(opts, NULL);
1041 qemu_opts_reset(&file_opts);
Max Reitzefaa7c42016-03-16 19:54:38 +01001042 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrange77c9aae2016-02-17 10:10:19 +00001043 } else {
1044 if (fmt) {
1045 options = qdict_new();
1046 qdict_put(options, "driver", qstring_from_str(fmt));
1047 }
Max Reitzefaa7c42016-03-16 19:54:38 +01001048 blk = blk_new_open(srcpath, NULL, options, flags, &local_err);
Daniel P. Berrangee6b63672013-03-19 11:20:20 +00001049 }
1050
Max Reitz4fbec262015-02-05 13:58:19 -05001051 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01001052 error_reportf_err(local_err, "Failed to blk_new_open '%s': ",
1053 argv[optind]);
Markus Armbruster85b01e02015-12-18 16:35:04 +01001054 exit(EXIT_FAILURE);
Paolo Bonzini802ddc32011-11-04 15:51:24 +01001055 }
Max Reitz4fbec262015-02-05 13:58:19 -05001056 bs = blk_bs(blk);
Paolo Bonzini802ddc32011-11-04 15:51:24 +01001057
Kevin Wolf6effd5b2016-03-14 11:43:28 +01001058 blk_set_enable_write_cache(blk, !writethrough);
1059
Wenchao Xia8c116b02013-12-04 17:10:55 +08001060 if (sn_opts) {
1061 ret = bdrv_snapshot_load_tmp(bs,
1062 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1063 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1064 &local_err);
1065 } else if (sn_id_or_name) {
1066 ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
1067 &local_err);
1068 }
1069 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01001070 error_reportf_err(local_err, "Failed to load snapshot: ");
Markus Armbruster85b01e02015-12-18 16:35:04 +01001071 exit(EXIT_FAILURE);
Wenchao Xia8c116b02013-12-04 17:10:55 +08001072 }
1073
Peter Lievenb3838a42014-08-13 19:20:18 +02001074 bs->detect_zeroes = detect_zeroes;
Max Reitz4c58e802014-11-18 12:21:19 +01001075 fd_size = blk_getlength(blk);
Max Reitz98f44bb2015-02-25 13:08:21 -05001076 if (fd_size < 0) {
Markus Armbruster85b01e02015-12-18 16:35:04 +01001077 error_report("Failed to determine the image length: %s",
1078 strerror(-fd_size));
1079 exit(EXIT_FAILURE);
Max Reitz98f44bb2015-02-25 13:08:21 -05001080 }
Paolo Bonzini802ddc32011-11-04 15:51:24 +01001081
Tomáš Golembiovskýe424b652016-10-05 23:40:20 +02001082 if (dev_offset >= fd_size) {
1083 error_report("Offset (%lld) has to be smaller than the image size "
1084 "(%lld)",
1085 (long long int)dev_offset, (long long int)fd_size);
1086 exit(EXIT_FAILURE);
1087 }
1088 fd_size -= dev_offset;
1089
Paolo Bonzini185b4332012-03-05 08:56:10 +01001090 if (partition != -1) {
Max Reitz4c58e802014-11-18 12:21:19 +01001091 ret = find_partition(blk, partition, &dev_offset, &fd_size);
Paolo Bonzini185b4332012-03-05 08:56:10 +01001092 if (ret < 0) {
Markus Armbruster85b01e02015-12-18 16:35:04 +01001093 error_report("Could not find partition %d: %s", partition,
Markus Armbrustera4699e52015-12-18 16:35:10 +01001094 strerror(-ret));
Markus Armbruster85b01e02015-12-18 16:35:04 +01001095 exit(EXIT_FAILURE);
Paolo Bonzini185b4332012-03-05 08:56:10 +01001096 }
Paolo Bonzini802ddc32011-11-04 15:51:24 +01001097 }
1098
Kevin Wolfcd7fca92016-07-06 11:22:39 +02001099 exp = nbd_export_new(bs, dev_offset, fd_size, nbdflags, nbd_export_closed,
1100 writethrough, NULL, &local_err);
Max Reitz98f44bb2015-02-25 13:08:21 -05001101 if (!exp) {
Markus Armbruster4fffeb52015-12-18 16:35:05 +01001102 error_report_err(local_err);
Markus Armbruster85b01e02015-12-18 16:35:04 +01001103 exit(EXIT_FAILURE);
Max Reitz98f44bb2015-02-25 13:08:21 -05001104 }
Daniel P. Berrange3d4b2f92016-02-10 18:41:08 +00001105 if (export_name) {
1106 nbd_export_set_name(exp, export_name);
Eric Blakeb1a75b32016-10-14 13:33:03 -05001107 nbd_export_set_description(exp, export_description);
Daniel P. Berrange3d4b2f92016-02-10 18:41:08 +00001108 newproto = true;
Eric Blakeb1a75b32016-10-14 13:33:03 -05001109 } else if (export_description) {
1110 error_report("Export description requires an export name");
1111 exit(EXIT_FAILURE);
Daniel P. Berrange3d4b2f92016-02-10 18:41:08 +00001112 }
ths3b05a8e2008-07-03 12:45:02 +00001113
Paolo Bonzinif1ef5552011-11-04 15:51:23 +01001114 if (device) {
1115 int ret;
1116
Paolo Bonzinia6ac2312011-12-06 09:07:00 +01001117 ret = pthread_create(&client_thread, NULL, nbd_client_thread, device);
Paolo Bonzinif1ef5552011-11-04 15:51:23 +01001118 if (ret != 0) {
Markus Armbruster85b01e02015-12-18 16:35:04 +01001119 error_report("Failed to create client thread: %s", strerror(ret));
1120 exit(EXIT_FAILURE);
Paolo Bonzinif1ef5552011-11-04 15:51:23 +01001121 }
1122 } else {
1123 /* Shut up GCC warnings. */
1124 memset(&client_thread, 0, sizeof(client_thread));
1125 }
1126
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +00001127 nbd_update_server_watch();
bellard7a5ca862008-05-27 21:13:40 +00001128
Michael Tokarev9faf31b2012-01-16 18:37:44 +04001129 /* now when the initialization is (almost) complete, chdir("/")
1130 * to free any busy filesystems */
1131 if (chdir("/") < 0) {
Markus Armbruster85b01e02015-12-18 16:35:04 +01001132 error_report("Could not chdir to root directory: %s",
1133 strerror(errno));
1134 exit(EXIT_FAILURE);
Michael Tokarev9faf31b2012-01-16 18:37:44 +04001135 }
1136
Max Reitzffb31e12016-09-28 22:46:42 +02001137 if (fork_process) {
1138 dup2(old_stderr, STDERR_FILENO);
1139 close(old_stderr);
1140 }
1141
Paolo Bonzini7860a382012-09-18 13:31:56 +02001142 state = RUNNING;
ths3b05a8e2008-07-03 12:45:02 +00001143 do {
Paolo Bonzinia61c6782011-09-12 17:28:11 +02001144 main_loop_wait(false);
Paolo Bonzini7860a382012-09-18 13:31:56 +02001145 if (state == TERMINATE) {
1146 state = TERMINATING;
1147 nbd_export_close(exp);
1148 nbd_export_put(exp);
1149 exp = NULL;
1150 }
1151 } while (state != TERMINATED);
ths3b05a8e2008-07-03 12:45:02 +00001152
Markus Armbruster26f54e92014-10-07 13:59:04 +02001153 blk_unref(blk);
Paolo Bonzinib32f6c22011-11-04 15:51:20 +01001154 if (sockpath) {
1155 unlink(sockpath);
1156 }
bellard7a5ca862008-05-27 21:13:40 +00001157
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02001158 qemu_opts_del(sn_opts);
Wenchao Xia8c116b02013-12-04 17:10:55 +08001159
Paolo Bonzinia517e882011-11-04 15:51:21 +01001160 if (device) {
1161 void *ret;
1162 pthread_join(client_thread, &ret);
1163 exit(ret != NULL);
1164 } else {
1165 exit(EXIT_SUCCESS);
1166 }
bellard7a5ca862008-05-27 21:13:40 +00001167}