blob: ed5895861bb075bdf1d66c7488c83c48a1425bec [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"
Eric Blakec2a3d7d2017-07-21 08:50:47 -050020#include <getopt.h>
21#include <libgen.h>
22#include <pthread.h>
23
Marc-André Lureau49f95222022-04-20 17:25:49 +040024#include "qemu/help-texts.h"
Markus Armbrusterda34e652016-03-14 09:01:28 +010025#include "qapi/error.h"
Veronia Bahaaf348b6d2016-03-20 19:16:19 +020026#include "qemu/cutils.h"
Philippe Mathieu-Daudé32cad1f2024-12-03 15:20:13 +010027#include "system/block-backend.h"
28#include "system/runstate.h" /* for qemu_system_killed() prototype */
Peter Lievenb3838a42014-08-13 19:20:18 +020029#include "block/block_int.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010030#include "block/nbd.h"
Alex Bligh6a1751b2013-08-21 16:02:47 +010031#include "qemu/main-loop.h"
Markus Armbruster0b8fa322019-05-23 16:35:07 +020032#include "qemu/module.h"
Markus Armbruster922a01a2018-02-01 12:18:46 +010033#include "qemu/option.h"
Paolo Bonzini537b41f2014-02-17 14:43:51 +010034#include "qemu/error-report.h"
Daniel P. Berrange0ab3b332016-02-10 18:41:00 +000035#include "qemu/config-file.h"
Paolo Bonzini58369e22016-03-15 17:22:36 +010036#include "qemu/bswap.h"
Denis V. Lunev39ca4632016-06-17 17:44:12 +030037#include "qemu/log.h"
Paolo Bonzini53fabd42017-03-16 16:29:45 +010038#include "qemu/systemd.h"
Wenchao Xia8c116b02013-12-04 17:10:55 +080039#include "block/snapshot.h"
Daniel P. Berrangé407bc4b2024-11-18 16:12:34 +010040#include "qobject/qdict.h"
41#include "qobject/qstring.h"
Daniel P. Berrange0ab3b332016-02-10 18:41:00 +000042#include "qom/object_interfaces.h"
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +000043#include "io/channel-socket.h"
Daniel P. Berrangee4849c12017-12-18 10:16:43 +000044#include "io/net-listener.h"
Daniel P. Berrangec2297082016-04-06 12:12:06 +010045#include "crypto/init.h"
Philippe Mathieu-Daudé0279cd92021-06-28 18:09:10 +020046#include "crypto/tlscreds.h"
Denis V. Lunev39ca4632016-06-17 17:44:12 +030047#include "trace/control.h"
Eric Blakebe377132017-07-21 08:50:46 -050048#include "qemu-version.h"
bellard7a5ca862008-05-27 21:13:40 +000049
Richard W.M. Jones3d212b42021-11-15 14:29:43 -060050#ifdef CONFIG_SELINUX
51#include <selinux/selinux.h>
52#endif
53
Eric Blake3c1fa352018-12-15 07:53:08 -060054#ifdef __linux__
55#define HAVE_NBD_DEVICE 1
56#else
57#define HAVE_NBD_DEVICE 0
58#endif
59
Eric Blake617017f2025-02-03 16:26:06 -060060#define SOCKET_PATH "/var/lock/qemu-nbd-%s"
61#define QEMU_NBD_OPT_CACHE 256
62#define QEMU_NBD_OPT_AIO 257
63#define QEMU_NBD_OPT_DISCARD 258
64#define QEMU_NBD_OPT_DETECT_ZEROES 259
65#define QEMU_NBD_OPT_OBJECT 260
66#define QEMU_NBD_OPT_TLSCREDS 261
67#define QEMU_NBD_OPT_IMAGE_OPTS 262
68#define QEMU_NBD_OPT_FORK 263
69#define QEMU_NBD_OPT_TLSAUTHZ 264
70#define QEMU_NBD_OPT_PID_FILE 265
71#define QEMU_NBD_OPT_SELINUX_LABEL 266
72#define QEMU_NBD_OPT_TLSHOSTNAME 267
73#define QEMU_NBD_OPT_HANDSHAKE_LIMIT 268
bellard7a5ca862008-05-27 21:13:40 +000074
Eric Blakebd31c212016-05-06 10:26:42 -060075#define MBR_SIZE 512
76
Paolo Bonzini7860a382012-09-18 13:31:56 +020077static int persistent = 0;
Kevin Wolfd794f7f2020-09-24 17:26:56 +020078static enum { RUNNING, TERMINATE, TERMINATED } state;
Paolo Bonzinia61c6782011-09-12 17:28:11 +020079static int shared = 1;
80static int nb_fds;
Daniel P. Berrangee4849c12017-12-18 10:16:43 +000081static QIONetListener *server;
Daniel P. Berrange145614a2016-02-10 18:41:13 +000082static QCryptoTLSCreds *tlscreds;
Daniel P. Berrangeb25e12d2019-02-27 16:20:33 +000083static const char *tlsauthz;
Eric Blake617017f2025-02-03 16:26:06 -060084static int handshake_limit = NBD_DEFAULT_HANDSHAKE_MAX_SECS;
bellard7a5ca862008-05-27 21:13:40 +000085
86static void usage(const char *name)
87{
Paolo Bonzinib033cd82012-07-18 14:50:52 +020088 (printf) (
bellard7a5ca862008-05-27 21:13:40 +000089"Usage: %s [OPTIONS] FILE\n"
Eric Blake68b96f12019-01-17 13:36:56 -060090" or: %s -L [OPTIONS]\n"
91"QEMU Disk Network Block Device Utility\n"
bellard7a5ca862008-05-27 21:13:40 +000092"\n"
Peter Lieven713cc672014-08-13 19:20:19 +020093" -h, --help display this help and exit\n"
94" -V, --version output version information and exit\n"
bellard7a5ca862008-05-27 21:13:40 +000095"\n"
Paolo Bonzinib033cd82012-07-18 14:50:52 +020096"Connection properties:\n"
Peter Lieven713cc672014-08-13 19:20:19 +020097" -p, --port=PORT port to listen on (default `%d')\n"
98" -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
99" -k, --socket=PATH path to the unix socket\n"
100" (default '"SOCKET_PATH"')\n"
101" -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
102" -t, --persistent don't exit on the last connection\n"
103" -v, --verbose display extra debugging information\n"
Vladimir Sementsov-Ogievskiyf5cd0bb2018-10-03 20:02:27 +0300104" -x, --export-name=NAME expose export by name (default is empty string)\n"
105" -D, --description=TEXT export a human-readable description\n"
Eric Blake617017f2025-02-03 16:26:06 -0600106" --handshake-limit=N limit client's handshake to N seconds (default 10)\n"
Paolo Bonzinib033cd82012-07-18 14:50:52 +0200107"\n"
108"Exposing part of the image:\n"
Peter Lieven713cc672014-08-13 19:20:19 +0200109" -o, --offset=OFFSET offset into the image\n"
Eric Blakedbc7b012020-10-27 00:05:55 -0500110" -A, --allocation-depth expose the allocation depth\n"
Eric Blake636192c2019-01-11 13:47:20 -0600111" -B, --bitmap=NAME expose a persistent dirty bitmap\n"
Paolo Bonzinib033cd82012-07-18 14:50:52 +0200112"\n"
Daniel P. Berrange0ab3b332016-02-10 18:41:00 +0000113"General purpose options:\n"
Eric Blake68b96f12019-01-17 13:36:56 -0600114" -L, --list list exports available from another NBD server\n"
Daniel P. Berrange0ab3b332016-02-10 18:41:00 +0000115" --object type,id=ID,... define an object such as 'secret' for providing\n"
116" passwords and/or encryption keys\n"
Eric Blakef7812df2018-10-03 13:04:26 -0500117" --tls-creds=ID use id of an earlier --object to provide TLS\n"
Daniel P. Berrangeb25e12d2019-02-27 16:20:33 +0000118" --tls-authz=ID use id of an earlier --object to provide\n"
119" authorization\n"
Michael Tokarevd81b7972024-02-07 10:29:40 +0300120" --tls-hostname=HOSTNAME override hostname used to check x509 certificate\n"
Denis V. Lunev39ca4632016-06-17 17:44:12 +0300121" -T, --trace [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
122" specify tracing options\n"
Max Reitzffb31e12016-09-28 22:46:42 +0200123" --fork fork off the server process and exit the parent\n"
124" once the server is running\n"
Max Reitz637bc5a2019-05-08 23:18:16 +0200125" --pid-file=PATH store the server's process ID in the given file\n"
Richard W.M. Jones3d212b42021-11-15 14:29:43 -0600126#ifdef CONFIG_SELINUX
127" --selinux-label=LABEL set SELinux process label on listening socket\n"
128#endif
Eric Blake3c1fa352018-12-15 07:53:08 -0600129#if HAVE_NBD_DEVICE
130"\n"
Paolo Bonzinib033cd82012-07-18 14:50:52 +0200131"Kernel NBD client support:\n"
Peter Lieven713cc672014-08-13 19:20:19 +0200132" -c, --connect=DEV connect FILE to the local NBD device DEV\n"
133" -d, --disconnect disconnect the specified device\n"
Paolo Bonzinib033cd82012-07-18 14:50:52 +0200134#endif
135"\n"
136"Block device options:\n"
Peter Lieven713cc672014-08-13 19:20:19 +0200137" -f, --format=FORMAT set image format (raw, qcow2, ...)\n"
138" -r, --read-only export read-only\n"
139" -s, --snapshot use FILE as an external snapshot, create a temporary\n"
140" file with backing_file=FILE, redirect the write to\n"
141" the temporary one\n"
Wenchao Xia8c116b02013-12-04 17:10:55 +0800142" -l, --load-snapshot=SNAPSHOT_PARAM\n"
Peter Lieven713cc672014-08-13 19:20:19 +0200143" load an internal snapshot inside FILE and export it\n"
144" as an read-only device, SNAPSHOT_PARAM format is\n"
145" 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
146" '[ID_OR_NAME]'\n"
147" -n, --nocache disable host cache\n"
Nir Soffer09615252021-08-13 23:55:19 +0300148" --cache=MODE set cache mode used to access the disk image, the\n"
149" valid options are: 'none', 'writeback' (default),\n"
150" 'writethrough', 'directsync' and 'unsafe'\n"
Aarushi Mehta76802742020-01-20 14:18:56 +0000151" --aio=MODE set AIO mode (native, io_uring or threads)\n"
Peter Lievenb3838a42014-08-13 19:20:18 +0200152" --discard=MODE set discard mode (ignore, unmap)\n"
Andrey Korolyov6883de62015-07-31 22:12:54 +0300153" --detect-zeroes=MODE set detect-zeroes mode (off, on, unmap)\n"
Daniel P. Berrange77c9aae2016-02-17 10:10:19 +0000154" --image-opts treat FILE as a full set of image options\n"
Paolo Bonzinib033cd82012-07-18 14:50:52 +0200155"\n"
Eric Blakef5048cb2017-08-03 11:33:53 -0500156QEMU_HELP_BOTTOM "\n"
Eric Blake68b96f12019-01-17 13:36:56 -0600157 , name, name, NBD_DEFAULT_PORT, "DEVICE");
bellard7a5ca862008-05-27 21:13:40 +0000158}
159
160static void version(const char *name)
161{
162 printf(
Thomas Huth7e563bf2018-02-15 12:06:47 +0100163"%s " QEMU_FULL_VERSION "\n"
bellard7a5ca862008-05-27 21:13:40 +0000164"Written by Anthony Liguori.\n"
165"\n"
Eric Blakebe377132017-07-21 08:50:46 -0500166QEMU_COPYRIGHT "\n"
bellard7a5ca862008-05-27 21:13:40 +0000167"This is free software; see the source for copying conditions. There is NO\n"
168"warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
ths315bc7a2008-07-18 18:06:23 +0000169 , name);
bellard7a5ca862008-05-27 21:13:40 +0000170}
171
Eric Blake029a88c2020-09-30 07:11:01 -0500172#ifdef CONFIG_POSIX
Stefan Hajnoczicbc20bf2020-09-29 13:55:15 +0100173/*
174 * The client thread uses SIGTERM to interrupt the server. A signal
175 * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
176 */
177void qemu_system_killed(int signum, pid_t pid)
Paolo Bonzinibb345112011-11-04 15:51:19 +0100178{
Stefan Hajnoczid73415a2020-09-23 11:56:46 +0100179 qatomic_cmpxchg(&state, RUNNING, TERMINATE);
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200180 qemu_notify_event();
Paolo Bonzinibb345112011-11-04 15:51:19 +0100181}
Eric Blake029a88c2020-09-30 07:11:01 -0500182#endif /* CONFIG_POSIX */
Paolo Bonzini537b41f2014-02-17 14:43:51 +0100183
Eric Blake68b96f12019-01-17 13:36:56 -0600184static int qemu_nbd_client_list(SocketAddress *saddr, QCryptoTLSCreds *tls,
185 const char *hostname)
186{
187 int ret = EXIT_FAILURE;
188 int rc;
189 Error *err = NULL;
190 QIOChannelSocket *sioc;
191 NBDExportInfo *list;
192 int i, j;
193
194 sioc = qio_channel_socket_new();
195 if (qio_channel_socket_connect_sync(sioc, saddr, &err) < 0) {
196 error_report_err(err);
Alex Chen992809b2020-11-30 12:36:51 +0000197 goto out;
Eric Blake68b96f12019-01-17 13:36:56 -0600198 }
199 rc = nbd_receive_export_list(QIO_CHANNEL(sioc), tls, hostname, &list,
200 &err);
201 if (rc < 0) {
202 if (err) {
203 error_report_err(err);
204 }
205 goto out;
206 }
207 printf("exports available: %d\n", rc);
208 for (i = 0; i < rc; i++) {
209 printf(" export: '%s'\n", list[i].name);
210 if (list[i].description && *list[i].description) {
211 printf(" description: %s\n", list[i].description);
212 }
213 if (list[i].flags & NBD_FLAG_HAS_FLAGS) {
Max Reitzc4e2aff2019-04-05 21:16:35 +0200214 static const char *const flag_names[] = {
215 [NBD_FLAG_READ_ONLY_BIT] = "readonly",
216 [NBD_FLAG_SEND_FLUSH_BIT] = "flush",
217 [NBD_FLAG_SEND_FUA_BIT] = "fua",
218 [NBD_FLAG_ROTATIONAL_BIT] = "rotational",
219 [NBD_FLAG_SEND_TRIM_BIT] = "trim",
220 [NBD_FLAG_SEND_WRITE_ZEROES_BIT] = "zeroes",
221 [NBD_FLAG_SEND_DF_BIT] = "df",
222 [NBD_FLAG_CAN_MULTI_CONN_BIT] = "multi",
223 [NBD_FLAG_SEND_RESIZE_BIT] = "resize",
224 [NBD_FLAG_SEND_CACHE_BIT] = "cache",
Eric Blake0a479542019-08-23 09:37:23 -0500225 [NBD_FLAG_SEND_FAST_ZERO_BIT] = "fast-zero",
Eric Blake2dcbb112023-09-25 14:22:42 -0500226 [NBD_FLAG_BLOCK_STAT_PAYLOAD_BIT] = "block-status-payload",
Max Reitzc4e2aff2019-04-05 21:16:35 +0200227 };
228
Eric Blake68b96f12019-01-17 13:36:56 -0600229 printf(" size: %" PRIu64 "\n", list[i].size);
230 printf(" flags: 0x%x (", list[i].flags);
Max Reitzc4e2aff2019-04-05 21:16:35 +0200231 for (size_t bit = 0; bit < ARRAY_SIZE(flag_names); bit++) {
232 if (flag_names[bit] && (list[i].flags & (1 << bit))) {
233 printf(" %s", flag_names[bit]);
234 }
Eric Blake68b96f12019-01-17 13:36:56 -0600235 }
236 printf(" )\n");
237 }
238 if (list[i].min_block) {
239 printf(" min block: %u\n", list[i].min_block);
240 printf(" opt block: %u\n", list[i].opt_block);
241 printf(" max block: %u\n", list[i].max_block);
242 }
Eric Blake56cf9d02023-09-25 14:22:39 -0500243 printf(" transaction size: %s\n",
244 list[i].mode >= NBD_MODE_EXTENDED ?
245 "64-bit" : "32-bit");
Eric Blake68b96f12019-01-17 13:36:56 -0600246 if (list[i].n_contexts) {
247 printf(" available meta contexts: %d\n", list[i].n_contexts);
248 for (j = 0; j < list[i].n_contexts; j++) {
249 printf(" %s\n", list[i].contexts[j]);
250 }
251 }
252 }
253 nbd_free_export_list(list, rc);
254
255 ret = EXIT_SUCCESS;
256 out:
257 object_unref(OBJECT(sioc));
258 return ret;
259}
260
261
Denis V. Lunev3484f672023-09-06 11:32:04 +0200262struct NbdClientOpts {
263 char *device;
Denis V. Lunevb18d72d2023-09-06 11:32:05 +0200264 char *srcpath;
Denis V. Lunevb2cecdf2023-09-06 11:32:06 +0200265 SocketAddress *saddr;
Denis V. Lunevf6f46202023-09-06 11:32:08 +0200266 int old_stderr;
Denis V. Lunev3484f672023-09-06 11:32:04 +0200267 bool fork_process;
268 bool verbose;
269};
270
Denis V. Lunevf6f46202023-09-06 11:32:08 +0200271static void nbd_client_release_pipe(int old_stderr)
Denis V. Lunev2eb7c2a2023-09-06 11:32:07 +0200272{
273 /* Close stderr so that the qemu-nbd process exits. */
Denis V. Lunevf6f46202023-09-06 11:32:08 +0200274 if (dup2(old_stderr, STDERR_FILENO) < 0) {
Denis V. Lunev2eb7c2a2023-09-06 11:32:07 +0200275 error_report("Could not release pipe to parent: %s",
276 strerror(errno));
277 exit(EXIT_FAILURE);
278 }
Denis V. Lunevf6f46202023-09-06 11:32:08 +0200279 if (old_stderr != STDOUT_FILENO && close(old_stderr) < 0) {
280 error_report("Could not release qemu-nbd: %s", strerror(errno));
281 exit(EXIT_FAILURE);
282 }
Denis V. Lunev2eb7c2a2023-09-06 11:32:07 +0200283}
284
Eric Blake3c1fa352018-12-15 07:53:08 -0600285#if HAVE_NBD_DEVICE
Paolo Bonzinia517e882011-11-04 15:51:21 +0100286static void *show_parts(void *arg)
thscd831bd2008-07-03 10:23:51 +0000287{
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100288 char *device = arg;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100289 int nbd;
thscd831bd2008-07-03 10:23:51 +0000290
Paolo Bonzinia517e882011-11-04 15:51:21 +0100291 /* linux just needs an open() to trigger
292 * the partition table update
293 * but remember to load the module with max_part != 0 :
294 * modprobe nbd max_part=63
295 */
296 nbd = open(device, O_RDWR);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100297 if (nbd >= 0) {
Paolo Bonzinia517e882011-11-04 15:51:21 +0100298 close(nbd);
thscd831bd2008-07-03 10:23:51 +0000299 }
Paolo Bonzinia517e882011-11-04 15:51:21 +0100300 return NULL;
301}
302
303static void *nbd_client_thread(void *arg)
304{
Denis V. Lunev03b67622023-07-17 16:55:40 +0200305 struct NbdClientOpts *opts = arg;
Eric Blakeac132d02023-08-29 12:58:28 -0500306 /* TODO: Revisit this if nbd.ko ever gains support for structured reply */
307 NBDExportInfo info = { .request_sizes = false, .name = g_strdup(""),
308 .mode = NBD_MODE_SIMPLE };
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000309 QIOChannelSocket *sioc;
Alex Chenaf74b552020-12-08 13:49:44 +0000310 int fd = -1;
311 int ret = EXIT_FAILURE;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100312 pthread_t show_parts_thread;
Max Reitz1ce52842015-01-26 21:02:59 -0500313 Error *local_error = NULL;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100314
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000315 sioc = qio_channel_socket_new();
316 if (qio_channel_socket_connect_sync(sioc,
Denis V. Lunevb2cecdf2023-09-06 11:32:06 +0200317 opts->saddr,
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000318 &local_error) < 0) {
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100319 error_report_err(local_error);
Stefan Hajnoczidc10e8b2012-01-05 13:16:07 +0000320 goto out;
321 }
Paolo Bonzinia517e882011-11-04 15:51:21 +0100322
Stefan Hajnoczib84ca912023-08-30 18:47:59 -0400323 if (nbd_receive_negotiate(QIO_CHANNEL(sioc), NULL, NULL, NULL,
324 &info, &local_error) < 0) {
Max Reitz1ce52842015-01-26 21:02:59 -0500325 if (local_error) {
Markus Armbruster78288672015-12-18 16:35:07 +0100326 error_report_err(local_error);
Max Reitz1ce52842015-01-26 21:02:59 -0500327 }
Alex Chenaf74b552020-12-08 13:49:44 +0000328 goto out;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100329 }
330
Denis V. Lunev03b67622023-07-17 16:55:40 +0200331 fd = open(opts->device, O_RDWR);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100332 if (fd < 0) {
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100333 /* Linux-only, we can use %m in printf. */
Denis V. Lunev03b67622023-07-17 16:55:40 +0200334 error_report("Failed to open %s: %m", opts->device);
Alex Chenaf74b552020-12-08 13:49:44 +0000335 goto out;
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100336 }
337
Alex Chenaf74b552020-12-08 13:49:44 +0000338 if (nbd_init(fd, sioc, &info, &local_error) < 0) {
Vladimir Sementsov-Ogievskiybe41c102017-05-26 14:09:13 +0300339 error_report_err(local_error);
Alex Chenaf74b552020-12-08 13:49:44 +0000340 goto out;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100341 }
342
343 /* update partition table */
Denis V. Lunev03b67622023-07-17 16:55:40 +0200344 pthread_create(&show_parts_thread, NULL, show_parts, opts->device);
Paolo Bonzinia517e882011-11-04 15:51:21 +0100345
Denis V. Lunev414c0cf2023-07-17 22:25:20 +0200346 if (opts->verbose && !opts->fork_process) {
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100347 fprintf(stderr, "NBD device %s is now connected to %s\n",
Denis V. Lunevb18d72d2023-09-06 11:32:05 +0200348 opts->device, opts->srcpath);
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100349 } else {
Denis V. Lunevf6f46202023-09-06 11:32:08 +0200350 nbd_client_release_pipe(opts->old_stderr);
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100351 }
Paolo Bonzinia517e882011-11-04 15:51:21 +0100352
Alex Chenaf74b552020-12-08 13:49:44 +0000353 if (nbd_client(fd) < 0) {
354 goto out;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100355 }
Paolo Bonzinia517e882011-11-04 15:51:21 +0100356
Alex Chenaf74b552020-12-08 13:49:44 +0000357 ret = EXIT_SUCCESS;
358
359 out:
360 if (fd >= 0) {
361 close(fd);
362 }
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000363 object_unref(OBJECT(sioc));
Eric Blake6dc16672019-01-17 13:36:46 -0600364 g_free(info.name);
Paolo Bonzinia517e882011-11-04 15:51:21 +0100365 kill(getpid(), SIGTERM);
Alex Chenaf74b552020-12-08 13:49:44 +0000366 return (void *) (intptr_t) ret;
thscd831bd2008-07-03 10:23:51 +0000367}
Eric Blake3c1fa352018-12-15 07:53:08 -0600368#endif /* HAVE_NBD_DEVICE */
thscd831bd2008-07-03 10:23:51 +0000369
Fam Zhenge4afbf42015-05-19 10:50:59 +0000370static int nbd_can_accept(void)
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200371{
Eric Blake3dcf56e2021-02-09 09:27:59 -0600372 return state == RUNNING && (shared == 0 || nb_fds < shared);
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200373}
374
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000375static void nbd_update_server_watch(void);
Fam Zhenge4afbf42015-05-19 10:50:59 +0000376
Eric Blake0c9390d2017-06-08 17:26:17 -0500377static void nbd_client_closed(NBDClient *client, bool negotiated)
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200378{
Paolo Bonzini1743b512011-09-19 14:33:23 +0200379 nb_fds--;
Eric Blake0c9390d2017-06-08 17:26:17 -0500380 if (negotiated && nb_fds == 0 && !persistent && state == RUNNING) {
Paolo Bonzini7860a382012-09-18 13:31:56 +0200381 state = TERMINATE;
382 }
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000383 nbd_update_server_watch();
Paolo Bonzini7860a382012-09-18 13:31:56 +0200384 nbd_client_put(client);
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200385}
386
Daniel P. Berrangee4849c12017-12-18 10:16:43 +0000387static void nbd_accept(QIONetListener *listener, QIOChannelSocket *cioc,
388 gpointer opaque)
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200389{
Paolo Bonzini7860a382012-09-18 13:31:56 +0200390 if (state >= TERMINATE) {
Daniel P. Berrangee4849c12017-12-18 10:16:43 +0000391 return;
Paolo Bonzini7860a382012-09-18 13:31:56 +0200392 }
393
Fam Zhengee7d7aa2016-01-14 16:41:01 +0800394 nb_fds++;
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000395 nbd_update_server_watch();
Eric Blake617017f2025-02-03 16:26:06 -0600396 nbd_client_new(cioc, handshake_limit,
Eric Blakefb1c2aa2024-08-07 08:50:01 -0500397 tlscreds, tlsauthz, nbd_client_closed, NULL);
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200398}
399
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000400static void nbd_update_server_watch(void)
Fam Zhenge4afbf42015-05-19 10:50:59 +0000401{
402 if (nbd_can_accept()) {
Daniel P. Berrangee4849c12017-12-18 10:16:43 +0000403 qio_net_listener_set_client_func(server, nbd_accept, NULL, NULL);
Fam Zhenge4afbf42015-05-19 10:50:59 +0000404 } else {
Daniel P. Berrangee4849c12017-12-18 10:16:43 +0000405 qio_net_listener_set_client_func(server, NULL, NULL, NULL);
Fam Zhenge4afbf42015-05-19 10:50:59 +0000406 }
407}
408
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100409
Markus Armbrusterbd269eb2017-04-26 09:36:41 +0200410static SocketAddress *nbd_build_socket_address(const char *sockpath,
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100411 const char *bindto,
412 const char *port)
413{
Markus Armbrusterbd269eb2017-04-26 09:36:41 +0200414 SocketAddress *saddr;
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100415
Markus Armbrusterbd269eb2017-04-26 09:36:41 +0200416 saddr = g_new0(SocketAddress, 1);
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100417 if (sockpath) {
Markus Armbrusterbd269eb2017-04-26 09:36:41 +0200418 saddr->type = SOCKET_ADDRESS_TYPE_UNIX;
419 saddr->u.q_unix.path = g_strdup(sockpath);
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100420 } else {
Eric Blake03992932016-03-03 09:16:48 -0700421 InetSocketAddress *inet;
Markus Armbrusterbd269eb2017-04-26 09:36:41 +0200422 saddr->type = SOCKET_ADDRESS_TYPE_INET;
423 inet = &saddr->u.inet;
Eric Blake03992932016-03-03 09:16:48 -0700424 inet->host = g_strdup(bindto);
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100425 if (port) {
Eric Blake03992932016-03-03 09:16:48 -0700426 inet->port = g_strdup(port);
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100427 } else {
Eric Blake03992932016-03-03 09:16:48 -0700428 inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100429 }
430 }
431
432 return saddr;
433}
434
435
Daniel P. Berrange77c9aae2016-02-17 10:10:19 +0000436static QemuOptsList file_opts = {
437 .name = "file",
438 .implied_opt_name = "file",
439 .head = QTAILQ_HEAD_INITIALIZER(file_opts.head),
440 .desc = {
441 /* no elements => accept any params */
442 { /* end of list */ }
443 },
444};
445
Eric Blake68b96f12019-01-17 13:36:56 -0600446static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, bool list,
447 Error **errp)
Daniel P. Berrange145614a2016-02-10 18:41:13 +0000448{
449 Object *obj;
450 QCryptoTLSCreds *creds;
451
452 obj = object_resolve_path_component(
453 object_get_objects_root(), id);
454 if (!obj) {
455 error_setg(errp, "No TLS credentials with id '%s'",
456 id);
457 return NULL;
458 }
459 creds = (QCryptoTLSCreds *)
460 object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
461 if (!creds) {
462 error_setg(errp, "Object with id '%s' is not TLS credentials",
463 id);
464 return NULL;
465 }
466
Philippe Mathieu-Daudé0279cd92021-06-28 18:09:10 +0200467 if (!qcrypto_tls_creds_check_endpoint(creds,
468 list
469 ? QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT
470 : QCRYPTO_TLS_CREDS_ENDPOINT_SERVER,
471 errp)) {
472 return NULL;
Daniel P. Berrange145614a2016-02-10 18:41:13 +0000473 }
474 object_ref(obj);
475 return creds;
476}
477
Richard W.M. Jonesa721f532017-02-04 10:03:17 +0000478static void setup_address_and_port(const char **address, const char **port)
479{
480 if (*address == NULL) {
481 *address = "0.0.0.0";
482 }
483
484 if (*port == NULL) {
485 *port = stringify(NBD_DEFAULT_PORT);
486 }
487}
488
Richard W.M. Jonesa721f532017-02-04 10:03:17 +0000489/*
490 * Check socket parameters compatibility when socket activation is used.
491 */
492static const char *socket_activation_validate_opts(const char *device,
493 const char *sockpath,
494 const char *address,
Eric Blake68b96f12019-01-17 13:36:56 -0600495 const char *port,
Richard W.M. Jones3d212b42021-11-15 14:29:43 -0600496 const char *selinux,
Eric Blake68b96f12019-01-17 13:36:56 -0600497 bool list)
Richard W.M. Jonesa721f532017-02-04 10:03:17 +0000498{
499 if (device != NULL) {
500 return "NBD device can't be set when using socket activation";
501 }
502
503 if (sockpath != NULL) {
504 return "Unix socket can't be set when using socket activation";
505 }
506
507 if (address != NULL) {
508 return "The interface can't be set when using socket activation";
509 }
510
511 if (port != NULL) {
512 return "TCP port number can't be set when using socket activation";
513 }
514
Richard W.M. Jones3d212b42021-11-15 14:29:43 -0600515 if (selinux != NULL) {
516 return "SELinux label can't be set when using socket activation";
517 }
518
Eric Blake68b96f12019-01-17 13:36:56 -0600519 if (list) {
520 return "List mode is incompatible with socket activation";
521 }
522
Richard W.M. Jonesa721f532017-02-04 10:03:17 +0000523 return NULL;
524}
Daniel P. Berrange145614a2016-02-10 18:41:13 +0000525
Kevin Wolfb3b52992018-05-16 13:46:37 +0200526static void qemu_nbd_shutdown(void)
527{
528 job_cancel_sync_all();
Sergio Lopez1895b972021-02-01 13:50:32 +0100529 blk_exp_close_all();
Kevin Wolfb3b52992018-05-16 13:46:37 +0200530 bdrv_close_all();
531}
532
bellard7a5ca862008-05-27 21:13:40 +0000533int main(int argc, char **argv)
534{
Markus Armbruster26f54e92014-10-07 13:59:04 +0200535 BlockBackend *blk;
bellard7a5ca862008-05-27 21:13:40 +0000536 BlockDriverState *bs;
Eric Blake9d26dfc2019-01-17 13:36:43 -0600537 uint64_t dev_offset = 0;
Eric Blakedbb38ca2019-08-23 09:37:22 -0500538 bool readonly = false;
thscd831bd2008-07-03 10:23:51 +0000539 bool disconnect = false;
Richard W.M. Jonesa721f532017-02-04 10:03:17 +0000540 const char *bindto = NULL;
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100541 const char *port = NULL;
542 char *sockpath = NULL;
Wenchao Xia8c116b02013-12-04 17:10:55 +0800543 QemuOpts *sn_opts = NULL;
544 const char *sn_id_or_name = NULL;
Eric Blakedbc7b012020-10-27 00:05:55 -0500545 const char *sopt = "hVb:o:p:rsnc:dvk:e:f:tl:x:T:D:AB:L";
bellard7a5ca862008-05-27 21:13:40 +0000546 struct option lopt[] = {
Daniel P. Berrangeaa6e5462016-02-17 10:10:22 +0000547 { "help", no_argument, NULL, 'h' },
548 { "version", no_argument, NULL, 'V' },
549 { "bind", required_argument, NULL, 'b' },
550 { "port", required_argument, NULL, 'p' },
551 { "socket", required_argument, NULL, 'k' },
552 { "offset", required_argument, NULL, 'o' },
553 { "read-only", no_argument, NULL, 'r' },
Eric Blakedbc7b012020-10-27 00:05:55 -0500554 { "allocation-depth", no_argument, NULL, 'A' },
Eric Blake636192c2019-01-11 13:47:20 -0600555 { "bitmap", required_argument, NULL, 'B' },
Daniel P. Berrangeaa6e5462016-02-17 10:10:22 +0000556 { "connect", required_argument, NULL, 'c' },
557 { "disconnect", no_argument, NULL, 'd' },
Eric Blake68b96f12019-01-17 13:36:56 -0600558 { "list", no_argument, NULL, 'L' },
Daniel P. Berrangeaa6e5462016-02-17 10:10:22 +0000559 { "snapshot", no_argument, NULL, 's' },
560 { "load-snapshot", required_argument, NULL, 'l' },
561 { "nocache", no_argument, NULL, 'n' },
562 { "cache", required_argument, NULL, QEMU_NBD_OPT_CACHE },
563 { "aio", required_argument, NULL, QEMU_NBD_OPT_AIO },
564 { "discard", required_argument, NULL, QEMU_NBD_OPT_DISCARD },
565 { "detect-zeroes", required_argument, NULL,
566 QEMU_NBD_OPT_DETECT_ZEROES },
567 { "shared", required_argument, NULL, 'e' },
568 { "format", required_argument, NULL, 'f' },
569 { "persistent", no_argument, NULL, 't' },
570 { "verbose", no_argument, NULL, 'v' },
571 { "object", required_argument, NULL, QEMU_NBD_OPT_OBJECT },
572 { "export-name", required_argument, NULL, 'x' },
Eric Blakeb1a75b32016-10-14 13:33:03 -0500573 { "description", required_argument, NULL, 'D' },
Eric Blake617017f2025-02-03 16:26:06 -0600574 { "handshake-limit", required_argument, NULL,
575 QEMU_NBD_OPT_HANDSHAKE_LIMIT },
Daniel P. Berrangeaa6e5462016-02-17 10:10:22 +0000576 { "tls-creds", required_argument, NULL, QEMU_NBD_OPT_TLSCREDS },
Daniel P. Berrangé003b2b22022-03-04 19:36:02 +0000577 { "tls-hostname", required_argument, NULL, QEMU_NBD_OPT_TLSHOSTNAME },
Daniel P. Berrangeb25e12d2019-02-27 16:20:33 +0000578 { "tls-authz", required_argument, NULL, QEMU_NBD_OPT_TLSAUTHZ },
Daniel P. Berrangeaa6e5462016-02-17 10:10:22 +0000579 { "image-opts", no_argument, NULL, QEMU_NBD_OPT_IMAGE_OPTS },
Denis V. Lunev39ca4632016-06-17 17:44:12 +0300580 { "trace", required_argument, NULL, 'T' },
Max Reitzffb31e12016-09-28 22:46:42 +0200581 { "fork", no_argument, NULL, QEMU_NBD_OPT_FORK },
Max Reitz637bc5a2019-05-08 23:18:16 +0200582 { "pid-file", required_argument, NULL, QEMU_NBD_OPT_PID_FILE },
Richard W.M. Jones3d212b42021-11-15 14:29:43 -0600583 { "selinux-label", required_argument, NULL,
584 QEMU_NBD_OPT_SELINUX_LABEL },
Blue Swirl660f11b2009-07-31 21:16:51 +0000585 { NULL, 0, NULL, 0 }
bellard7a5ca862008-05-27 21:13:40 +0000586 };
587 int ch;
588 int opt_ind = 0;
Naphtali Spreif5edb012010-01-17 16:48:13 +0200589 int flags = BDRV_O_RDWR;
Max Reitz4fbec262015-02-05 13:58:19 -0500590 int ret = 0;
Paolo Bonzini39a52352012-07-18 14:57:15 +0200591 bool seen_cache = false;
Paolo Bonzinided9d2d2013-02-08 14:06:13 +0100592 bool seen_discard = false;
Paolo Bonzini39a52352012-07-18 14:57:15 +0200593 bool seen_aio = false;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100594 pthread_t client_thread;
Daniel P. Berrangee6b63672013-03-19 11:20:20 +0000595 const char *fmt = NULL;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200596 Error *local_err = NULL;
Eric Blakec7195732024-08-01 16:49:20 -0500597 BlockdevDetectZeroesOptions detect_zeroes =
598 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
Max Reitz4fbec262015-02-05 13:58:19 -0500599 QDict *options = NULL;
Eric Blake68b96f12019-01-17 13:36:56 -0600600 const char *export_name = NULL; /* defaults to "" later for server mode */
Eric Blakeb1a75b32016-10-14 13:33:03 -0500601 const char *export_description = NULL;
Vladimir Sementsov-Ogievskiye5fb29d2022-03-15 00:32:25 +0300602 BlockDirtyBitmapOrStrList *bitmaps = NULL;
Eric Blakedbc7b012020-10-27 00:05:55 -0500603 bool alloc_depth = false;
Daniel P. Berrange145614a2016-02-10 18:41:13 +0000604 const char *tlscredsid = NULL;
Daniel P. Berrangé003b2b22022-03-04 19:36:02 +0000605 const char *tlshostname = NULL;
Daniel P. Berrange77c9aae2016-02-17 10:10:19 +0000606 bool imageOpts = false;
Nir Soffer09615252021-08-13 23:55:19 +0300607 bool writethrough = false; /* Client will flush as needed. */
Eric Blake68b96f12019-01-17 13:36:56 -0600608 bool list = false;
Richard W.M. Jonesa721f532017-02-04 10:03:17 +0000609 unsigned socket_activation;
Max Reitz637bc5a2019-05-08 23:18:16 +0200610 const char *pid_file_name = NULL;
Richard W.M. Jones3d212b42021-11-15 14:29:43 -0600611 const char *selinux_label = NULL;
Kevin Wolf00917172020-09-24 17:26:57 +0200612 BlockExportOptions *export_opts;
Denis V. Lunev3484f672023-09-06 11:32:04 +0200613 struct NbdClientOpts opts = {
614 .fork_process = false,
615 .verbose = false,
616 .device = NULL,
Denis V. Lunevb18d72d2023-09-06 11:32:05 +0200617 .srcpath = NULL,
Denis V. Lunevb2cecdf2023-09-06 11:32:06 +0200618 .saddr = NULL,
Denis V. Lunevf6f46202023-09-06 11:32:08 +0200619 .old_stderr = STDOUT_FILENO,
Denis V. Lunev3484f672023-09-06 11:32:04 +0200620 };
bellard7a5ca862008-05-27 21:13:40 +0000621
Eric Blake029a88c2020-09-30 07:11:01 -0500622#ifdef CONFIG_POSIX
Stefan Hajnoczicbc20bf2020-09-29 13:55:15 +0100623 os_setup_early_signal_handling();
624 os_setup_signal_handling();
Max Reitz041e32b2017-06-11 14:37:14 +0200625#endif
626
Daniel P. Berrangé98c5d2e2020-08-25 11:38:48 +0100627 socket_init();
Christophe Fergeauf5852ef2019-01-31 17:46:14 +0100628 error_init(argv[0]);
Daniel P. Berrangefe4db842016-10-04 14:35:52 +0100629 module_call_init(MODULE_INIT_TRACE);
Eduardo Habkoste8f2d272016-05-12 11:10:04 -0300630 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +0100631
Daniel P. Berrange0ab3b332016-02-10 18:41:00 +0000632 module_call_init(MODULE_INIT_QOM);
Denis V. Lunev39ca4632016-06-17 17:44:12 +0300633 qemu_add_opts(&qemu_trace_opts);
Fam Zheng10f5bff2014-02-10 14:48:51 +0800634 qemu_init_exec_dir(argv[0]);
Paolo Bonzinibb345112011-11-04 15:51:19 +0100635
bellard7a5ca862008-05-27 21:13:40 +0000636 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
637 switch (ch) {
638 case 's':
ths2f726482008-07-03 11:47:46 +0000639 flags |= BDRV_O_SNAPSHOT;
640 break;
641 case 'n':
Paolo Bonzini39a52352012-07-18 14:57:15 +0200642 optarg = (char *) "none";
643 /* fallthrough */
644 case QEMU_NBD_OPT_CACHE:
645 if (seen_cache) {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100646 error_report("-n and --cache can only be specified once");
647 exit(EXIT_FAILURE);
Paolo Bonzini39a52352012-07-18 14:57:15 +0200648 }
649 seen_cache = true;
Kevin Wolf6effd5b2016-03-14 11:43:28 +0100650 if (bdrv_parse_cache_mode(optarg, &flags, &writethrough) == -1) {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100651 error_report("Invalid cache mode `%s'", optarg);
652 exit(EXIT_FAILURE);
Paolo Bonzini39a52352012-07-18 14:57:15 +0200653 }
bellard7a5ca862008-05-27 21:13:40 +0000654 break;
Paolo Bonzini39a52352012-07-18 14:57:15 +0200655 case QEMU_NBD_OPT_AIO:
656 if (seen_aio) {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100657 error_report("--aio can only be specified once");
658 exit(EXIT_FAILURE);
Paolo Bonzini39a52352012-07-18 14:57:15 +0200659 }
660 seen_aio = true;
Aarushi Mehta76802742020-01-20 14:18:56 +0000661 if (bdrv_parse_aio(optarg, &flags) < 0) {
662 error_report("Invalid aio mode '%s'", optarg);
663 exit(EXIT_FAILURE);
Paolo Bonzini39a52352012-07-18 14:57:15 +0200664 }
665 break;
Paolo Bonzinided9d2d2013-02-08 14:06:13 +0100666 case QEMU_NBD_OPT_DISCARD:
667 if (seen_discard) {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100668 error_report("--discard can only be specified once");
669 exit(EXIT_FAILURE);
Paolo Bonzinided9d2d2013-02-08 14:06:13 +0100670 }
671 seen_discard = true;
672 if (bdrv_parse_discard_flags(optarg, &flags) == -1) {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100673 error_report("Invalid discard mode `%s'", optarg);
674 exit(EXIT_FAILURE);
Paolo Bonzinided9d2d2013-02-08 14:06:13 +0100675 }
676 break;
Peter Lievenb3838a42014-08-13 19:20:18 +0200677 case QEMU_NBD_OPT_DETECT_ZEROES:
678 detect_zeroes =
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +0200679 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup,
Peter Lievenb3838a42014-08-13 19:20:18 +0200680 optarg,
Peter Lievenb3838a42014-08-13 19:20:18 +0200681 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
682 &local_err);
683 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100684 error_reportf_err(local_err,
685 "Failed to parse detect_zeroes mode: ");
Markus Armbruster85b01e02015-12-18 16:35:04 +0100686 exit(EXIT_FAILURE);
Peter Lievenb3838a42014-08-13 19:20:18 +0200687 }
688 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
689 !(flags & BDRV_O_UNMAP)) {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100690 error_report("setting detect-zeroes to unmap is not allowed "
691 "without setting discard operation to unmap");
692 exit(EXIT_FAILURE);
Peter Lievenb3838a42014-08-13 19:20:18 +0200693 }
694 break;
bellard7a5ca862008-05-27 21:13:40 +0000695 case 'b':
696 bindto = optarg;
697 break;
698 case 'p':
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100699 port = optarg;
bellard7a5ca862008-05-27 21:13:40 +0000700 break;
701 case 'o':
Eric Blake43b51012019-01-17 13:36:44 -0600702 if (qemu_strtou64(optarg, NULL, 0, &dev_offset) < 0) {
703 error_report("Invalid offset '%s'", optarg);
Markus Armbruster85b01e02015-12-18 16:35:04 +0100704 exit(EXIT_FAILURE);
bellard7a5ca862008-05-27 21:13:40 +0000705 }
bellard7a5ca862008-05-27 21:13:40 +0000706 break;
Wenchao Xia8c116b02013-12-04 17:10:55 +0800707 case 'l':
708 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +0100709 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
710 optarg, false);
Wenchao Xia8c116b02013-12-04 17:10:55 +0800711 if (!sn_opts) {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100712 error_report("Failed in parsing snapshot param `%s'",
713 optarg);
714 exit(EXIT_FAILURE);
Wenchao Xia8c116b02013-12-04 17:10:55 +0800715 }
716 } else {
717 sn_id_or_name = optarg;
718 }
719 /* fall through */
bellard7a5ca862008-05-27 21:13:40 +0000720 case 'r':
Eric Blakedbb38ca2019-08-23 09:37:22 -0500721 readonly = true;
Naphtali Sprei07108b22010-03-14 15:19:57 +0200722 flags &= ~BDRV_O_RDWR;
bellard7a5ca862008-05-27 21:13:40 +0000723 break;
Eric Blakedbc7b012020-10-27 00:05:55 -0500724 case 'A':
725 alloc_depth = true;
726 break;
Eric Blake636192c2019-01-11 13:47:20 -0600727 case 'B':
Vladimir Sementsov-Ogievskiye5fb29d2022-03-15 00:32:25 +0300728 {
729 BlockDirtyBitmapOrStr *el = g_new(BlockDirtyBitmapOrStr, 1);
730 *el = (BlockDirtyBitmapOrStr) {
731 .type = QTYPE_QSTRING,
732 .u.local = g_strdup(optarg),
733 };
734 QAPI_LIST_PREPEND(bitmaps, el);
735 }
Eric Blake636192c2019-01-11 13:47:20 -0600736 break;
thscd831bd2008-07-03 10:23:51 +0000737 case 'k':
Paolo Bonzinib32f6c22011-11-04 15:51:20 +0100738 sockpath = optarg;
Peter Lieven713cc672014-08-13 19:20:19 +0200739 if (sockpath[0] != '/') {
Markus Armbruster9af9e0f2015-12-18 16:35:19 +0100740 error_report("socket path must be absolute");
Markus Armbruster85b01e02015-12-18 16:35:04 +0100741 exit(EXIT_FAILURE);
Peter Lieven713cc672014-08-13 19:20:19 +0200742 }
thscd831bd2008-07-03 10:23:51 +0000743 break;
744 case 'd':
745 disconnect = true;
746 break;
747 case 'c':
Denis V. Lunev3484f672023-09-06 11:32:04 +0200748 opts.device = optarg;
thscd831bd2008-07-03 10:23:51 +0000749 break;
ths3b05a8e2008-07-03 12:45:02 +0000750 case 'e':
Eric Blake43b51012019-01-17 13:36:44 -0600751 if (qemu_strtoi(optarg, NULL, 0, &shared) < 0 ||
Eric Blake3dcf56e2021-02-09 09:27:59 -0600752 shared < 0) {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100753 error_report("Invalid shared device number '%s'", optarg);
754 exit(EXIT_FAILURE);
ths3b05a8e2008-07-03 12:45:02 +0000755 }
ths3b05a8e2008-07-03 12:45:02 +0000756 break;
Daniel P. Berrangee6b63672013-03-19 11:20:20 +0000757 case 'f':
758 fmt = optarg;
759 break;
Peter Lieven713cc672014-08-13 19:20:19 +0200760 case 't':
761 persistent = 1;
762 break;
Daniel P. Berrange3d4b2f92016-02-10 18:41:08 +0000763 case 'x':
764 export_name = optarg;
Eric Blake93676c82019-11-13 20:46:34 -0600765 if (strlen(export_name) > NBD_MAX_STRING_SIZE) {
766 error_report("export name '%s' too long", export_name);
767 exit(EXIT_FAILURE);
768 }
Daniel P. Berrange3d4b2f92016-02-10 18:41:08 +0000769 break;
Eric Blakeb1a75b32016-10-14 13:33:03 -0500770 case 'D':
771 export_description = optarg;
Eric Blake93676c82019-11-13 20:46:34 -0600772 if (strlen(export_description) > NBD_MAX_STRING_SIZE) {
773 error_report("export description '%s' too long",
774 export_description);
775 exit(EXIT_FAILURE);
776 }
Eric Blakeb1a75b32016-10-14 13:33:03 -0500777 break;
bellard7a5ca862008-05-27 21:13:40 +0000778 case 'v':
Denis V. Lunev3484f672023-09-06 11:32:04 +0200779 opts.verbose = true;
bellard7a5ca862008-05-27 21:13:40 +0000780 break;
781 case 'V':
782 version(argv[0]);
783 exit(0);
784 break;
785 case 'h':
786 usage(argv[0]);
787 exit(0);
788 break;
789 case '?':
Markus Armbruster85b01e02015-12-18 16:35:04 +0100790 error_report("Try `%s --help' for more information.", argv[0]);
791 exit(EXIT_FAILURE);
Kevin Wolffa40e432021-02-17 12:56:45 +0100792 case QEMU_NBD_OPT_OBJECT:
793 user_creatable_process_cmdline(optarg);
794 break;
Daniel P. Berrange145614a2016-02-10 18:41:13 +0000795 case QEMU_NBD_OPT_TLSCREDS:
796 tlscredsid = optarg;
797 break;
Daniel P. Berrangé003b2b22022-03-04 19:36:02 +0000798 case QEMU_NBD_OPT_TLSHOSTNAME:
799 tlshostname = optarg;
800 break;
Daniel P. Berrange77c9aae2016-02-17 10:10:19 +0000801 case QEMU_NBD_OPT_IMAGE_OPTS:
802 imageOpts = true;
803 break;
Denis V. Lunev39ca4632016-06-17 17:44:12 +0300804 case 'T':
Paolo Bonzini92eecff2020-11-02 06:58:41 -0500805 trace_opt_parse(optarg);
Denis V. Lunev39ca4632016-06-17 17:44:12 +0300806 break;
Daniel P. Berrangeb25e12d2019-02-27 16:20:33 +0000807 case QEMU_NBD_OPT_TLSAUTHZ:
808 tlsauthz = optarg;
809 break;
Max Reitzffb31e12016-09-28 22:46:42 +0200810 case QEMU_NBD_OPT_FORK:
Denis V. Lunev3484f672023-09-06 11:32:04 +0200811 opts.fork_process = true;
Max Reitzffb31e12016-09-28 22:46:42 +0200812 break;
Eric Blake68b96f12019-01-17 13:36:56 -0600813 case 'L':
814 list = true;
815 break;
Max Reitz637bc5a2019-05-08 23:18:16 +0200816 case QEMU_NBD_OPT_PID_FILE:
817 pid_file_name = optarg;
818 break;
Richard W.M. Jones3d212b42021-11-15 14:29:43 -0600819 case QEMU_NBD_OPT_SELINUX_LABEL:
820 selinux_label = optarg;
821 break;
Eric Blake617017f2025-02-03 16:26:06 -0600822 case QEMU_NBD_OPT_HANDSHAKE_LIMIT:
823 if (qemu_strtoi(optarg, NULL, 0, &handshake_limit) < 0 ||
824 handshake_limit < 0) {
825 error_report("Invalid handshake limit '%s'", optarg);
826 exit(EXIT_FAILURE);
827 }
828 break;
bellard7a5ca862008-05-27 21:13:40 +0000829 }
830 }
831
Eric Blake68b96f12019-01-17 13:36:56 -0600832 if (list) {
833 if (argc != optind) {
834 error_report("List mode is incompatible with a file name");
835 exit(EXIT_FAILURE);
836 }
Eric Blake0bc16992020-01-23 10:46:50 -0600837 if (export_name || export_description || dev_offset ||
Denis V. Lunev3484f672023-09-06 11:32:04 +0200838 opts.device || disconnect || fmt || sn_id_or_name || bitmaps ||
Eric Blakedbc7b012020-10-27 00:05:55 -0500839 alloc_depth || seen_aio || seen_discard || seen_cache) {
Eric Blake68b96f12019-01-17 13:36:56 -0600840 error_report("List mode is incompatible with per-device settings");
841 exit(EXIT_FAILURE);
842 }
Denis V. Lunev3484f672023-09-06 11:32:04 +0200843 if (opts.fork_process) {
Eric Blake68b96f12019-01-17 13:36:56 -0600844 error_report("List mode is incompatible with forking");
845 exit(EXIT_FAILURE);
846 }
847 } else if ((argc - optind) != 1) {
Markus Armbruster433672b2015-12-18 16:35:24 +0100848 error_report("Invalid number of arguments");
849 error_printf("Try `%s --help' for more information.\n", argv[0]);
Markus Armbruster85b01e02015-12-18 16:35:04 +0100850 exit(EXIT_FAILURE);
Eric Blake68b96f12019-01-17 13:36:56 -0600851 } else if (!export_name) {
852 export_name = "";
bellard7a5ca862008-05-27 21:13:40 +0000853 }
854
Richard Hendersonc5955f42022-04-17 11:29:44 -0700855 qemu_set_log(LOG_TRACE, &error_fatal);
Denis V. Lunev39ca4632016-06-17 17:44:12 +0300856
Richard W.M. Jonesa721f532017-02-04 10:03:17 +0000857 socket_activation = check_socket_activation();
858 if (socket_activation == 0) {
Daniel P. Berrangée8ae8b12022-03-04 19:36:03 +0000859 if (!sockpath) {
860 setup_address_and_port(&bindto, &port);
861 }
Richard W.M. Jonesa721f532017-02-04 10:03:17 +0000862 } else {
863 /* Using socket activation - check user didn't use -p etc. */
Denis V. Lunev3484f672023-09-06 11:32:04 +0200864 const char *err_msg = socket_activation_validate_opts(opts.device,
865 sockpath,
Eric Blake68b96f12019-01-17 13:36:56 -0600866 bindto, port,
Richard W.M. Jones3d212b42021-11-15 14:29:43 -0600867 selinux_label,
Eric Blake68b96f12019-01-17 13:36:56 -0600868 list);
Richard W.M. Jonesa721f532017-02-04 10:03:17 +0000869 if (err_msg != NULL) {
870 error_report("%s", err_msg);
871 exit(EXIT_FAILURE);
872 }
Paolo Bonzini53fabd42017-03-16 16:29:45 +0100873
874 /* qemu-nbd can only listen on a single socket. */
875 if (socket_activation > 1) {
876 error_report("qemu-nbd does not support socket activation with %s > 1",
877 "LISTEN_FDS");
878 exit(EXIT_FAILURE);
879 }
Richard W.M. Jonesa721f532017-02-04 10:03:17 +0000880 }
881
Daniel P. Berrange145614a2016-02-10 18:41:13 +0000882 if (tlscredsid) {
Denis V. Lunev3484f672023-09-06 11:32:04 +0200883 if (opts.device) {
Daniel P. Berrange145614a2016-02-10 18:41:13 +0000884 error_report("TLS is not supported with a host device");
885 exit(EXIT_FAILURE);
886 }
Daniel P. Berrangeb25e12d2019-02-27 16:20:33 +0000887 if (tlsauthz && list) {
888 error_report("TLS authorization is incompatible with export list");
889 exit(EXIT_FAILURE);
890 }
Daniel P. Berrangé003b2b22022-03-04 19:36:02 +0000891 if (tlshostname && !list) {
892 error_report("TLS hostname is only supported with export list");
893 exit(EXIT_FAILURE);
894 }
Eric Blake68b96f12019-01-17 13:36:56 -0600895 tlscreds = nbd_get_tls_creds(tlscredsid, list, &local_err);
Daniel P. Berrange145614a2016-02-10 18:41:13 +0000896 if (local_err) {
Markus Armbruster5217f182020-05-05 12:19:03 +0200897 error_reportf_err(local_err, "Failed to get TLS creds: ");
Daniel P. Berrange145614a2016-02-10 18:41:13 +0000898 exit(EXIT_FAILURE);
899 }
Daniel P. Berrangeb25e12d2019-02-27 16:20:33 +0000900 } else {
901 if (tlsauthz) {
902 error_report("--tls-authz is not permitted without --tls-creds");
903 exit(EXIT_FAILURE);
904 }
Daniel P. Berrangé003b2b22022-03-04 19:36:02 +0000905 if (tlshostname) {
906 error_report("--tls-hostname is not permitted without --tls-creds");
907 exit(EXIT_FAILURE);
908 }
Daniel P. Berrange145614a2016-02-10 18:41:13 +0000909 }
910
Richard W.M. Jones3d212b42021-11-15 14:29:43 -0600911 if (selinux_label) {
912#ifdef CONFIG_SELINUX
Denis V. Lunev3484f672023-09-06 11:32:04 +0200913 if (sockpath == NULL && opts.device == NULL) {
Richard W.M. Jones3d212b42021-11-15 14:29:43 -0600914 error_report("--selinux-label is not permitted without --socket");
915 exit(EXIT_FAILURE);
916 }
917#else
918 error_report("SELinux support not enabled in this binary");
919 exit(EXIT_FAILURE);
920#endif
921 }
922
Eric Blake68b96f12019-01-17 13:36:56 -0600923 if (list) {
Denis V. Lunevb2cecdf2023-09-06 11:32:06 +0200924 opts.saddr = nbd_build_socket_address(sockpath, bindto, port);
925 return qemu_nbd_client_list(opts.saddr, tlscreds,
Daniel P. Berrangé003b2b22022-03-04 19:36:02 +0000926 tlshostname ? tlshostname : bindto);
Eric Blake68b96f12019-01-17 13:36:56 -0600927 }
928
Eric Blake3c1fa352018-12-15 07:53:08 -0600929#if !HAVE_NBD_DEVICE
Denis V. Lunev3484f672023-09-06 11:32:04 +0200930 if (disconnect || opts.device) {
Eric Blake3c1fa352018-12-15 07:53:08 -0600931 error_report("Kernel /dev/nbdN support not available");
932 exit(EXIT_FAILURE);
933 }
934#else /* HAVE_NBD_DEVICE */
thscd831bd2008-07-03 10:23:51 +0000935 if (disconnect) {
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000936 int nbdfd = open(argv[optind], O_RDWR);
937 if (nbdfd < 0) {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100938 error_report("Cannot open %s: %s", argv[optind],
939 strerror(errno));
940 exit(EXIT_FAILURE);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100941 }
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000942 nbd_disconnect(nbdfd);
thscd831bd2008-07-03 10:23:51 +0000943
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +0000944 close(nbdfd);
thscd831bd2008-07-03 10:23:51 +0000945
946 printf("%s disconnected\n", argv[optind]);
947
Peter Lieven713cc672014-08-13 19:20:19 +0200948 return 0;
thscd831bd2008-07-03 10:23:51 +0000949 }
Eric Blake3c1fa352018-12-15 07:53:08 -0600950#endif
thscd831bd2008-07-03 10:23:51 +0000951
Denis V. Lunev3484f672023-09-06 11:32:04 +0200952 if ((opts.device && !opts.verbose) || opts.fork_process) {
Daniel P. Berrangéeb705982020-08-25 11:38:50 +0100953#ifndef WIN32
Marc-André Lureaua7241972022-03-29 15:21:00 +0400954 g_autoptr(GError) err = NULL;
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100955 int stderr_fd[2];
956 pid_t pid;
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100957
Marc-André Lureaua7241972022-03-29 15:21:00 +0400958 if (!g_unix_open_pipe(stderr_fd, FD_CLOEXEC, &err)) {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100959 error_report("Error setting up communication pipe: %s",
Marc-André Lureaua7241972022-03-29 15:21:00 +0400960 err->message);
Markus Armbruster85b01e02015-12-18 16:35:04 +0100961 exit(EXIT_FAILURE);
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100962 }
963
964 /* Now daemonize, but keep a communication channel open to
965 * print errors and exit with the proper status code.
966 */
967 pid = fork();
Max Reitz70d47392015-02-25 13:08:22 -0500968 if (pid < 0) {
Markus Armbruster85b01e02015-12-18 16:35:04 +0100969 error_report("Failed to fork: %s", strerror(errno));
970 exit(EXIT_FAILURE);
Max Reitz70d47392015-02-25 13:08:22 -0500971 } else if (pid == 0) {
Denis V. Lunev1dc82152023-07-17 16:55:43 +0200972 int saved_errno;
973
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100974 close(stderr_fd[0]);
Max Reitze6df58a2019-05-08 23:18:18 +0200975
Denis V. Lunevf6f46202023-09-06 11:32:08 +0200976 /* Remember parent's stderr if we will be restoring it. */
977 if (opts.verbose /* fork_process is set */) {
978 opts.old_stderr = dup(STDERR_FILENO);
979 if (opts.old_stderr < 0) {
980 error_report("Could not dup original stderr: %s",
981 strerror(errno));
982 exit(EXIT_FAILURE);
983 }
984 }
985
Michael Tokarev9faf31b2012-01-16 18:37:44 +0400986 ret = qemu_daemon(1, 0);
Denis V. Lunev1dc82152023-07-17 16:55:43 +0200987 saved_errno = errno; /* dup2 will overwrite error below */
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100988
989 /* Temporarily redirect stderr to the parent's pipe... */
Denis V. Luneve0892ce2023-07-17 16:55:42 +0200990 if (dup2(stderr_fd[1], STDERR_FILENO) < 0) {
991 char str[256];
992 snprintf(str, sizeof(str),
993 "%s: Failed to link stderr to the pipe: %s\n",
994 g_get_prgname(), strerror(errno));
995 /*
996 * We are unable to use error_report() here as we need to get
997 * stderr pointed to the parent's pipe. Write to that pipe
998 * manually.
999 */
1000 ret = write(stderr_fd[1], str, strlen(str));
1001 exit(EXIT_FAILURE);
1002 }
1003
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +01001004 if (ret < 0) {
Denis V. Lunev1dc82152023-07-17 16:55:43 +02001005 error_report("Failed to daemonize: %s", strerror(saved_errno));
Markus Armbruster85b01e02015-12-18 16:35:04 +01001006 exit(EXIT_FAILURE);
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +01001007 }
1008
1009 /* ... close the descriptor we inherited and go on. */
1010 close(stderr_fd[1]);
1011 } else {
1012 bool errors = false;
1013 char *buf;
1014
1015 /* In the parent. Print error messages from the child until
1016 * it closes the pipe.
1017 */
1018 close(stderr_fd[1]);
1019 buf = g_malloc(1024);
1020 while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
1021 errors = true;
1022 ret = qemu_write_full(STDERR_FILENO, buf, ret);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +01001023 if (ret < 0) {
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +01001024 exit(EXIT_FAILURE);
1025 }
1026 }
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +01001027 if (ret < 0) {
Markus Armbruster85b01e02015-12-18 16:35:04 +01001028 error_report("Cannot read from daemon: %s",
1029 strerror(errno));
1030 exit(EXIT_FAILURE);
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +01001031 }
1032
1033 /* Usually the daemon should not print any message.
1034 * Exit with zero status in that case.
1035 */
1036 exit(errors);
1037 }
Daniel P. Berrangéeb705982020-08-25 11:38:50 +01001038#else /* WIN32 */
1039 error_report("Unable to fork into background on Windows hosts");
1040 exit(EXIT_FAILURE);
1041#endif /* WIN32 */
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +01001042 }
1043
Eric Blake3e168342025-02-27 16:06:15 -06001044 /*
1045 * trace_init must be done after daemonization. Why? Because at
1046 * least the simple backend spins up a helper thread as well as an
1047 * atexit() handler that waits on that thread, but the helper
1048 * thread won't survive a fork, leading to deadlock in the child
1049 * if we initialized pre-fork.
1050 */
1051 if (!trace_init_backends()) {
1052 exit(1);
1053 }
1054 trace_init_file();
1055
Denis V. Lunev3484f672023-09-06 11:32:04 +02001056 if (opts.device != NULL && sockpath == NULL) {
Paolo Bonzinia6ac2312011-12-06 09:07:00 +01001057 sockpath = g_malloc(128);
Denis V. Lunev3484f672023-09-06 11:32:04 +02001058 snprintf(sockpath, 128, SOCKET_PATH, basename(opts.device));
thscd831bd2008-07-03 10:23:51 +00001059 }
1060
Daniel P. Berrangee4849c12017-12-18 10:16:43 +00001061 server = qio_net_listener_new();
Richard W.M. Jonesa721f532017-02-04 10:03:17 +00001062 if (socket_activation == 0) {
Eric Blake582d4212021-02-09 09:27:58 -06001063 int backlog;
1064
Eric Blake3dcf56e2021-02-09 09:27:59 -06001065 if (persistent || shared == 0) {
Eric Blake582d4212021-02-09 09:27:58 -06001066 backlog = SOMAXCONN;
1067 } else {
1068 backlog = MIN(shared, SOMAXCONN);
1069 }
Richard W.M. Jones3d212b42021-11-15 14:29:43 -06001070#ifdef CONFIG_SELINUX
1071 if (selinux_label && setsockcreatecon_raw(selinux_label) == -1) {
1072 error_report("Cannot set SELinux socket create context to %s: %s",
1073 selinux_label, strerror(errno));
1074 exit(EXIT_FAILURE);
1075 }
1076#endif
Denis V. Lunevb2cecdf2023-09-06 11:32:06 +02001077 opts.saddr = nbd_build_socket_address(sockpath, bindto, port);
1078 if (qio_net_listener_open_sync(server, opts.saddr, backlog,
Eric Blake582d4212021-02-09 09:27:58 -06001079 &local_err) < 0) {
Daniel P. Berrangee4849c12017-12-18 10:16:43 +00001080 object_unref(OBJECT(server));
Richard W.M. Jonesa721f532017-02-04 10:03:17 +00001081 error_report_err(local_err);
Daniel P. Berrangee4849c12017-12-18 10:16:43 +00001082 exit(EXIT_FAILURE);
Richard W.M. Jonesa721f532017-02-04 10:03:17 +00001083 }
Richard W.M. Jones3d212b42021-11-15 14:29:43 -06001084#ifdef CONFIG_SELINUX
1085 if (selinux_label && setsockcreatecon_raw(NULL) == -1) {
1086 error_report("Cannot clear SELinux socket create context: %s",
1087 strerror(errno));
1088 exit(EXIT_FAILURE);
1089 }
1090#endif
Richard W.M. Jonesa721f532017-02-04 10:03:17 +00001091 } else {
Daniel P. Berrangee4849c12017-12-18 10:16:43 +00001092 size_t i;
Richard W.M. Jonesa721f532017-02-04 10:03:17 +00001093 /* See comment in check_socket_activation above. */
Daniel P. Berrangee4849c12017-12-18 10:16:43 +00001094 for (i = 0; i < socket_activation; i++) {
1095 QIOChannelSocket *sioc;
1096 sioc = qio_channel_socket_new_fd(FIRST_SOCKET_ACTIVATION_FD + i,
1097 &local_err);
1098 if (sioc == NULL) {
1099 object_unref(OBJECT(server));
Markus Armbruster5217f182020-05-05 12:19:03 +02001100 error_reportf_err(local_err,
1101 "Failed to use socket activation: ");
Daniel P. Berrangee4849c12017-12-18 10:16:43 +00001102 exit(EXIT_FAILURE);
1103 }
1104 qio_net_listener_add(server, sioc);
1105 object_unref(OBJECT(sioc));
Richard W.M. Jonesa721f532017-02-04 10:03:17 +00001106 }
1107 }
Daniel P. Berrange48bec072015-09-16 14:52:23 +01001108
Markus Armbrusterf9734d52021-07-20 14:53:53 +02001109 qemu_init_main_loop(&error_fatal);
Paolo Bonzini802ddc32011-11-04 15:51:24 +01001110 bdrv_init();
Kevin Wolfb3b52992018-05-16 13:46:37 +02001111 atexit(qemu_nbd_shutdown);
Paolo Bonzini802ddc32011-11-04 15:51:24 +01001112
Denis V. Lunevb18d72d2023-09-06 11:32:05 +02001113 opts.srcpath = argv[optind];
Daniel P. Berrange77c9aae2016-02-17 10:10:19 +00001114 if (imageOpts) {
Denis V. Lunevb18d72d2023-09-06 11:32:05 +02001115 QemuOpts *o;
Daniel P. Berrange77c9aae2016-02-17 10:10:19 +00001116 if (fmt) {
1117 error_report("--image-opts and -f are mutually exclusive");
1118 exit(EXIT_FAILURE);
1119 }
Denis V. Lunevb18d72d2023-09-06 11:32:05 +02001120 o = qemu_opts_parse_noisily(&file_opts, opts.srcpath, true);
1121 if (!o) {
Daniel P. Berrange77c9aae2016-02-17 10:10:19 +00001122 qemu_opts_reset(&file_opts);
1123 exit(EXIT_FAILURE);
1124 }
Denis V. Lunevb18d72d2023-09-06 11:32:05 +02001125 options = qemu_opts_to_qdict(o, NULL);
Daniel P. Berrange77c9aae2016-02-17 10:10:19 +00001126 qemu_opts_reset(&file_opts);
Max Reitzefaa7c42016-03-16 19:54:38 +01001127 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrange77c9aae2016-02-17 10:10:19 +00001128 } else {
1129 if (fmt) {
1130 options = qdict_new();
Eric Blake46f5ac22017-04-27 16:58:17 -05001131 qdict_put_str(options, "driver", fmt);
Daniel P. Berrange77c9aae2016-02-17 10:10:19 +00001132 }
Denis V. Lunevb18d72d2023-09-06 11:32:05 +02001133 blk = blk_new_open(opts.srcpath, NULL, options, flags, &local_err);
Daniel P. Berrangee6b63672013-03-19 11:20:20 +00001134 }
1135
Max Reitz4fbec262015-02-05 13:58:19 -05001136 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01001137 error_reportf_err(local_err, "Failed to blk_new_open '%s': ",
1138 argv[optind]);
Markus Armbruster85b01e02015-12-18 16:35:04 +01001139 exit(EXIT_FAILURE);
Paolo Bonzini802ddc32011-11-04 15:51:24 +01001140 }
Max Reitz4fbec262015-02-05 13:58:19 -05001141 bs = blk_bs(blk);
Paolo Bonzini802ddc32011-11-04 15:51:24 +01001142
Kevin Wolfb57e4de2020-09-24 17:26:52 +02001143 if (dev_offset) {
1144 QDict *raw_opts = qdict_new();
1145 qdict_put_str(raw_opts, "driver", "raw");
1146 qdict_put_str(raw_opts, "file", bs->node_name);
1147 qdict_put_int(raw_opts, "offset", dev_offset);
Kevin Wolfc6e0a6d2023-05-25 14:47:04 +02001148
Kevin Wolfb57e4de2020-09-24 17:26:52 +02001149 bs = bdrv_open(NULL, NULL, raw_opts, flags, &error_fatal);
Kevin Wolfc6e0a6d2023-05-25 14:47:04 +02001150
Kevin Wolfb57e4de2020-09-24 17:26:52 +02001151 blk_remove_bs(blk);
1152 blk_insert_bs(blk, bs, &error_fatal);
1153 bdrv_unref(bs);
1154 }
1155
Kevin Wolf6effd5b2016-03-14 11:43:28 +01001156 blk_set_enable_write_cache(blk, !writethrough);
1157
Wenchao Xia8c116b02013-12-04 17:10:55 +08001158 if (sn_opts) {
1159 ret = bdrv_snapshot_load_tmp(bs,
1160 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1161 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1162 &local_err);
1163 } else if (sn_id_or_name) {
1164 ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
1165 &local_err);
1166 }
1167 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01001168 error_reportf_err(local_err, "Failed to load snapshot: ");
Markus Armbruster85b01e02015-12-18 16:35:04 +01001169 exit(EXIT_FAILURE);
Wenchao Xia8c116b02013-12-04 17:10:55 +08001170 }
1171
Peter Lievenb3838a42014-08-13 19:20:18 +02001172 bs->detect_zeroes = detect_zeroes;
Paolo Bonzini802ddc32011-11-04 15:51:24 +01001173
Eric Blakea5fced42022-05-11 19:49:23 -05001174 nbd_server_is_qemu_nbd(shared);
Kevin Wolf00917172020-09-24 17:26:57 +02001175
1176 export_opts = g_new(BlockExportOptions, 1);
1177 *export_opts = (BlockExportOptions) {
1178 .type = BLOCK_EXPORT_TYPE_NBD,
Kevin Wolfd53be9c2020-09-24 17:27:04 +02001179 .id = g_strdup("qemu-nbd-export"),
Kevin Wolfb6076af2020-09-24 17:27:01 +02001180 .node_name = g_strdup(bdrv_get_node_name(bs)),
Kevin Wolf00917172020-09-24 17:26:57 +02001181 .has_writethrough = true,
1182 .writethrough = writethrough,
Kevin Wolf30dbc812020-09-24 17:27:11 +02001183 .has_writable = true,
1184 .writable = !readonly,
Kevin Wolf00917172020-09-24 17:26:57 +02001185 .u.nbd = {
Eric Blakecbad81c2020-10-27 00:05:49 -05001186 .name = g_strdup(export_name),
Eric Blakecbad81c2020-10-27 00:05:49 -05001187 .description = g_strdup(export_description),
1188 .has_bitmaps = !!bitmaps,
1189 .bitmaps = bitmaps,
Eric Blakedbc7b012020-10-27 00:05:55 -05001190 .has_allocation_depth = alloc_depth,
1191 .allocation_depth = alloc_depth,
Kevin Wolf00917172020-09-24 17:26:57 +02001192 },
1193 };
1194 blk_exp_add(export_opts, &error_fatal);
1195 qapi_free_BlockExportOptions(export_opts);
ths3b05a8e2008-07-03 12:45:02 +00001196
Denis V. Lunev3484f672023-09-06 11:32:04 +02001197 if (opts.device) {
Eric Blake3c1fa352018-12-15 07:53:08 -06001198#if HAVE_NBD_DEVICE
Denis V. Lunev03b67622023-07-17 16:55:40 +02001199 ret = pthread_create(&client_thread, NULL, nbd_client_thread, &opts);
Paolo Bonzinif1ef5552011-11-04 15:51:23 +01001200 if (ret != 0) {
Markus Armbruster85b01e02015-12-18 16:35:04 +01001201 error_report("Failed to create client thread: %s", strerror(ret));
1202 exit(EXIT_FAILURE);
Paolo Bonzinif1ef5552011-11-04 15:51:23 +01001203 }
Eric Blake3c1fa352018-12-15 07:53:08 -06001204#endif
Paolo Bonzinif1ef5552011-11-04 15:51:23 +01001205 } else {
1206 /* Shut up GCC warnings. */
1207 memset(&client_thread, 0, sizeof(client_thread));
1208 }
1209
Daniel P. Berranged0d6ff52016-02-10 18:41:02 +00001210 nbd_update_server_watch();
bellard7a5ca862008-05-27 21:13:40 +00001211
Max Reitz637bc5a2019-05-08 23:18:16 +02001212 if (pid_file_name) {
1213 qemu_write_pidfile(pid_file_name, &error_fatal);
1214 }
1215
Michael Tokarev9faf31b2012-01-16 18:37:44 +04001216 /* now when the initialization is (almost) complete, chdir("/")
1217 * to free any busy filesystems */
1218 if (chdir("/") < 0) {
Markus Armbruster85b01e02015-12-18 16:35:04 +01001219 error_report("Could not chdir to root directory: %s",
1220 strerror(errno));
1221 exit(EXIT_FAILURE);
Michael Tokarev9faf31b2012-01-16 18:37:44 +04001222 }
1223
Denis V. Lunev3484f672023-09-06 11:32:04 +02001224 if (opts.fork_process) {
Denis V. Lunevf6f46202023-09-06 11:32:08 +02001225 nbd_client_release_pipe(opts.old_stderr);
Max Reitzffb31e12016-09-28 22:46:42 +02001226 }
1227
Paolo Bonzini7860a382012-09-18 13:31:56 +02001228 state = RUNNING;
ths3b05a8e2008-07-03 12:45:02 +00001229 do {
Paolo Bonzinia61c6782011-09-12 17:28:11 +02001230 main_loop_wait(false);
Paolo Bonzini7860a382012-09-18 13:31:56 +02001231 if (state == TERMINATE) {
Kevin Wolfbc4ee652020-09-24 17:27:03 +02001232 blk_exp_close_all();
Kevin Wolfd794f7f2020-09-24 17:26:56 +02001233 state = TERMINATED;
Paolo Bonzini7860a382012-09-18 13:31:56 +02001234 }
1235 } while (state != TERMINATED);
ths3b05a8e2008-07-03 12:45:02 +00001236
Markus Armbruster26f54e92014-10-07 13:59:04 +02001237 blk_unref(blk);
Paolo Bonzinib32f6c22011-11-04 15:51:20 +01001238 if (sockpath) {
1239 unlink(sockpath);
1240 }
bellard7a5ca862008-05-27 21:13:40 +00001241
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02001242 qemu_opts_del(sn_opts);
Wenchao Xia8c116b02013-12-04 17:10:55 +08001243
Denis V. Lunev3484f672023-09-06 11:32:04 +02001244 if (opts.device) {
Eric Blakee1617852023-09-22 15:50:20 -05001245 void *result;
1246 pthread_join(client_thread, &result);
1247 ret = (intptr_t)result;
1248 exit(ret);
Paolo Bonzinia517e882011-11-04 15:51:21 +01001249 } else {
1250 exit(EXIT_SUCCESS);
1251 }
bellard7a5ca862008-05-27 21:13:40 +00001252}