]> git.proxmox.com Git - mirror_qemu.git/blame - qemu-nbd.c
qemu-nbd: introduce nbd_do_receive_request
[mirror_qemu.git] / qemu-nbd.c
CommitLineData
cd831bd7 1/*
7a5ca864
FB
2 * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws>
3 *
4 * Network Block Device
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; under version 2 of the License.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
8167ee88 16 * along with this program; if not, see <http://www.gnu.org/licenses/>.
7a5ca864
FB
17 */
18
5a61cb60 19#include "qemu-common.h"
7a5ca864
FB
20#include "block_int.h"
21#include "nbd.h"
22
7a5ca864
FB
23#include <stdarg.h>
24#include <stdio.h>
25#include <getopt.h>
26#include <err.h>
cd831bd7 27#include <sys/types.h>
7a5ca864
FB
28#include <sys/socket.h>
29#include <netinet/in.h>
30#include <netinet/tcp.h>
31#include <arpa/inet.h>
cd831bd7 32#include <signal.h>
2bff4b6f 33#include <libgen.h>
a517e88b 34#include <pthread.h>
cd831bd7
TS
35
36#define SOCKET_PATH "/var/lock/qemu-nbd-%s"
7a5ca864 37
bb345110 38static int sigterm_wfd;
b1d8e52e 39static int verbose;
a517e88b
PB
40static char *device;
41static char *srcpath;
42static char *sockpath;
7a5ca864
FB
43
44static void usage(const char *name)
45{
46 printf(
47"Usage: %s [OPTIONS] FILE\n"
48"QEMU Disk Network Block Device Server\n"
49"\n"
c2e2872b 50" -p, --port=PORT port to listen on (default `%d')\n"
7a5ca864
FB
51" -o, --offset=OFFSET offset into the image\n"
52" -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
cd831bd7
TS
53" -k, --socket=PATH path to the unix socket\n"
54" (default '"SOCKET_PATH"')\n"
7a5ca864
FB
55" -r, --read-only export read-only\n"
56" -P, --partition=NUM only expose partition NUM\n"
2f726488
TS
57" -s, --snapshot use snapshot file\n"
58" -n, --nocache disable host cache\n"
cd831bd7
TS
59" -c, --connect=DEV connect FILE to the local NBD device DEV\n"
60" -d, --disconnect disconnect the specified device\n"
3b05a8e9 61" -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
75818250 62" -t, --persistent don't exit on the last connection\n"
7a5ca864
FB
63" -v, --verbose display extra debugging information\n"
64" -h, --help display this help and exit\n"
65" -V, --version output version information and exit\n"
66"\n"
67"Report bugs to <anthony@codemonkey.ws>\n"
c2e2872b 68 , name, NBD_DEFAULT_PORT, "DEVICE");
7a5ca864
FB
69}
70
71static void version(const char *name)
72{
73 printf(
315bc7aa 74"%s version 0.0.1\n"
7a5ca864
FB
75"Written by Anthony Liguori.\n"
76"\n"
77"Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>.\n"
78"This is free software; see the source for copying conditions. There is NO\n"
79"warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
315bc7aa 80 , name);
7a5ca864
FB
81}
82
83struct partition_record
84{
85 uint8_t bootable;
86 uint8_t start_head;
87 uint32_t start_cylinder;
88 uint8_t start_sector;
89 uint8_t system;
90 uint8_t end_head;
91 uint8_t end_cylinder;
92 uint8_t end_sector;
93 uint32_t start_sector_abs;
94 uint32_t nb_sectors_abs;
95};
96
97static void read_partition(uint8_t *p, struct partition_record *r)
98{
99 r->bootable = p[0];
100 r->start_head = p[1];
101 r->start_cylinder = p[3] | ((p[2] << 2) & 0x0300);
102 r->start_sector = p[2] & 0x3f;
103 r->system = p[4];
104 r->end_head = p[5];
105 r->end_cylinder = p[7] | ((p[6] << 2) & 0x300);
106 r->end_sector = p[6] & 0x3f;
107 r->start_sector_abs = p[8] | p[9] << 8 | p[10] << 16 | p[11] << 24;
108 r->nb_sectors_abs = p[12] | p[13] << 8 | p[14] << 16 | p[15] << 24;
109}
110
111static int find_partition(BlockDriverState *bs, int partition,
112 off_t *offset, off_t *size)
113{
114 struct partition_record mbr[4];
115 uint8_t data[512];
116 int i;
117 int ext_partnum = 4;
cb7cf0e3 118 int ret;
7a5ca864 119
cb7cf0e3
RO
120 if ((ret = bdrv_read(bs, 0, data, 1)) < 0) {
121 errno = -ret;
122 err(EXIT_FAILURE, "error while reading");
123 }
7a5ca864
FB
124
125 if (data[510] != 0x55 || data[511] != 0xaa) {
126 errno = -EINVAL;
127 return -1;
128 }
129
130 for (i = 0; i < 4; i++) {
131 read_partition(&data[446 + 16 * i], &mbr[i]);
132
133 if (!mbr[i].nb_sectors_abs)
134 continue;
135
136 if (mbr[i].system == 0xF || mbr[i].system == 0x5) {
137 struct partition_record ext[4];
138 uint8_t data1[512];
139 int j;
140
cb7cf0e3
RO
141 if ((ret = bdrv_read(bs, mbr[i].start_sector_abs, data1, 1)) < 0) {
142 errno = -ret;
143 err(EXIT_FAILURE, "error while reading");
144 }
7a5ca864
FB
145
146 for (j = 0; j < 4; j++) {
147 read_partition(&data1[446 + 16 * j], &ext[j]);
148 if (!ext[j].nb_sectors_abs)
149 continue;
150
151 if ((ext_partnum + j + 1) == partition) {
152 *offset = (uint64_t)ext[j].start_sector_abs << 9;
153 *size = (uint64_t)ext[j].nb_sectors_abs << 9;
154 return 0;
155 }
156 }
157 ext_partnum += 4;
158 } else if ((i + 1) == partition) {
159 *offset = (uint64_t)mbr[i].start_sector_abs << 9;
160 *size = (uint64_t)mbr[i].nb_sectors_abs << 9;
161 return 0;
162 }
163 }
164
165 errno = -ENOENT;
166 return -1;
167}
168
bb345110
PB
169static void termsig_handler(int signum)
170{
171 static int sigterm_reported;
172 if (!sigterm_reported) {
173 sigterm_reported = (write(sigterm_wfd, "", 1) == 1);
174 }
175}
176
a517e88b 177static void *show_parts(void *arg)
cd831bd7 178{
a517e88b
PB
179 int nbd;
180
181 /* linux just needs an open() to trigger
182 * the partition table update
183 * but remember to load the module with max_part != 0 :
184 * modprobe nbd max_part=63
185 */
186 nbd = open(device, O_RDWR);
187 if (nbd != -1) {
188 close(nbd);
189 }
190 return NULL;
191}
cd831bd7 192
a517e88b
PB
193static void *nbd_client_thread(void *arg)
194{
195 int fd = *(int *)arg;
196 off_t size;
197 size_t blocksize;
198 uint32_t nbdflags;
199 int sock;
200 int ret;
201 pthread_t show_parts_thread;
202
203 do {
204 sock = unix_socket_outgoing(sockpath);
205 if (sock == -1) {
f1ef5555 206 goto out;
a517e88b
PB
207 }
208 } while (sock == -1);
209
210 ret = nbd_receive_negotiate(sock, NULL, &nbdflags,
211 &size, &blocksize);
212 if (ret == -1) {
213 goto out;
214 }
215
216 ret = nbd_init(fd, sock, nbdflags, size, blocksize);
217 if (ret == -1) {
218 goto out;
219 }
220
221 /* update partition table */
222 pthread_create(&show_parts_thread, NULL, show_parts, NULL);
223
c1f8fdc3
PB
224 if (verbose) {
225 fprintf(stderr, "NBD device %s is now connected to %s\n",
226 device, srcpath);
227 } else {
228 /* Close stderr so that the qemu-nbd process exits. */
229 dup2(STDOUT_FILENO, STDERR_FILENO);
230 }
a517e88b
PB
231
232 ret = nbd_client(fd);
233 if (ret) {
234 goto out;
cd831bd7 235 }
a517e88b
PB
236 close(fd);
237 kill(getpid(), SIGTERM);
238 return (void *) EXIT_SUCCESS;
239
240out:
241 kill(getpid(), SIGTERM);
242 return (void *) EXIT_FAILURE;
cd831bd7
TS
243}
244
7a5ca864
FB
245int main(int argc, char **argv)
246{
247 BlockDriverState *bs;
248 off_t dev_offset = 0;
b90fb4b8 249 uint32_t nbdflags = 0;
cd831bd7 250 bool disconnect = false;
7a5ca864 251 const char *bindto = "0.0.0.0";
c2e2872b 252 int port = NBD_DEFAULT_PORT;
7a5ca864
FB
253 struct sockaddr_in addr;
254 socklen_t addr_len = sizeof(addr);
255 off_t fd_size;
d6aa671f 256 const char *sopt = "hVb:o:p:rsnP:c:dvk:e:t";
7a5ca864 257 struct option lopt[] = {
660f11be
BS
258 { "help", 0, NULL, 'h' },
259 { "version", 0, NULL, 'V' },
260 { "bind", 1, NULL, 'b' },
261 { "port", 1, NULL, 'p' },
262 { "socket", 1, NULL, 'k' },
263 { "offset", 1, NULL, 'o' },
264 { "read-only", 0, NULL, 'r' },
265 { "partition", 1, NULL, 'P' },
266 { "connect", 1, NULL, 'c' },
267 { "disconnect", 0, NULL, 'd' },
268 { "snapshot", 0, NULL, 's' },
269 { "nocache", 0, NULL, 'n' },
270 { "shared", 1, NULL, 'e' },
271 { "persistent", 0, NULL, 't' },
272 { "verbose", 0, NULL, 'v' },
273 { NULL, 0, NULL, 0 }
7a5ca864
FB
274 };
275 int ch;
276 int opt_ind = 0;
277 int li;
278 char *end;
f5edb014 279 int flags = BDRV_O_RDWR;
7a5ca864 280 int partition = -1;
cd831bd7 281 int ret;
3b05a8e9 282 int shared = 1;
2f726488 283 uint8_t *data;
3b05a8e9
TS
284 fd_set fds;
285 int *sharing_fds;
286 int fd;
287 int i;
288 int nb_fds = 0;
289 int max_fd;
75818250 290 int persistent = 0;
a517e88b 291 pthread_t client_thread;
7a5ca864 292
a517e88b
PB
293 /* The client thread uses SIGTERM to interrupt the server. A signal
294 * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
295 */
bb345110
PB
296 struct sigaction sa_sigterm;
297 int sigterm_fd[2];
298 if (qemu_pipe(sigterm_fd) == -1) {
299 err(EXIT_FAILURE, "Error setting up communication pipe");
300 }
301
302 sigterm_wfd = sigterm_fd[1];
303 memset(&sa_sigterm, 0, sizeof(sa_sigterm));
304 sa_sigterm.sa_handler = termsig_handler;
305 sigaction(SIGTERM, &sa_sigterm, NULL);
306
7a5ca864
FB
307 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
308 switch (ch) {
309 case 's':
2f726488
TS
310 flags |= BDRV_O_SNAPSHOT;
311 break;
312 case 'n':
a6599793 313 flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
7a5ca864
FB
314 break;
315 case 'b':
316 bindto = optarg;
317 break;
318 case 'p':
319 li = strtol(optarg, &end, 0);
320 if (*end) {
b6353bea 321 errx(EXIT_FAILURE, "Invalid port `%s'", optarg);
7a5ca864
FB
322 }
323 if (li < 1 || li > 65535) {
b6353bea 324 errx(EXIT_FAILURE, "Port out of range `%s'", optarg);
7a5ca864
FB
325 }
326 port = (uint16_t)li;
327 break;
328 case 'o':
329 dev_offset = strtoll (optarg, &end, 0);
330 if (*end) {
b6353bea 331 errx(EXIT_FAILURE, "Invalid offset `%s'", optarg);
7a5ca864
FB
332 }
333 if (dev_offset < 0) {
b6353bea 334 errx(EXIT_FAILURE, "Offset must be positive `%s'", optarg);
7a5ca864
FB
335 }
336 break;
337 case 'r':
b90fb4b8 338 nbdflags |= NBD_FLAG_READ_ONLY;
07108b29 339 flags &= ~BDRV_O_RDWR;
7a5ca864
FB
340 break;
341 case 'P':
342 partition = strtol(optarg, &end, 0);
343 if (*end)
b6353bea 344 errx(EXIT_FAILURE, "Invalid partition `%s'", optarg);
7a5ca864 345 if (partition < 1 || partition > 8)
b6353bea 346 errx(EXIT_FAILURE, "Invalid partition %d", partition);
7a5ca864 347 break;
cd831bd7 348 case 'k':
b32f6c28
PB
349 sockpath = optarg;
350 if (sockpath[0] != '/')
b6353bea 351 errx(EXIT_FAILURE, "socket path must be absolute\n");
cd831bd7
TS
352 break;
353 case 'd':
354 disconnect = true;
355 break;
356 case 'c':
357 device = optarg;
358 break;
3b05a8e9
TS
359 case 'e':
360 shared = strtol(optarg, &end, 0);
361 if (*end) {
b6353bea 362 errx(EXIT_FAILURE, "Invalid shared device number '%s'", optarg);
3b05a8e9
TS
363 }
364 if (shared < 1) {
b6353bea 365 errx(EXIT_FAILURE, "Shared device number must be greater than 0\n");
3b05a8e9
TS
366 }
367 break;
75818250
TS
368 case 't':
369 persistent = 1;
370 break;
7a5ca864
FB
371 case 'v':
372 verbose = 1;
373 break;
374 case 'V':
375 version(argv[0]);
376 exit(0);
377 break;
378 case 'h':
379 usage(argv[0]);
380 exit(0);
381 break;
382 case '?':
b6353bea 383 errx(EXIT_FAILURE, "Try `%s --help' for more information.",
7a5ca864
FB
384 argv[0]);
385 }
386 }
387
388 if ((argc - optind) != 1) {
b6353bea 389 errx(EXIT_FAILURE, "Invalid number of argument.\n"
7a5ca864
FB
390 "Try `%s --help' for more information.",
391 argv[0]);
392 }
393
cd831bd7
TS
394 if (disconnect) {
395 fd = open(argv[optind], O_RDWR);
396 if (fd == -1)
cb7cf0e3 397 err(EXIT_FAILURE, "Cannot open %s", argv[optind]);
cd831bd7
TS
398
399 nbd_disconnect(fd);
400
401 close(fd);
402
403 printf("%s disconnected\n", argv[optind]);
404
405 return 0;
406 }
407
c1f8fdc3
PB
408 if (device && !verbose) {
409 int stderr_fd[2];
410 pid_t pid;
411 int ret;
412
413 if (qemu_pipe(stderr_fd) == -1) {
414 err(EXIT_FAILURE, "Error setting up communication pipe");
415 }
416
417 /* Now daemonize, but keep a communication channel open to
418 * print errors and exit with the proper status code.
419 */
420 pid = fork();
421 if (pid == 0) {
422 close(stderr_fd[0]);
423 ret = qemu_daemon(0, 0);
424
425 /* Temporarily redirect stderr to the parent's pipe... */
426 dup2(stderr_fd[1], STDERR_FILENO);
427 if (ret == -1) {
428 err(EXIT_FAILURE, "Failed to daemonize");
429 }
430
431 /* ... close the descriptor we inherited and go on. */
432 close(stderr_fd[1]);
433 } else {
434 bool errors = false;
435 char *buf;
436
437 /* In the parent. Print error messages from the child until
438 * it closes the pipe.
439 */
440 close(stderr_fd[1]);
441 buf = g_malloc(1024);
442 while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
443 errors = true;
444 ret = qemu_write_full(STDERR_FILENO, buf, ret);
445 if (ret == -1) {
446 exit(EXIT_FAILURE);
447 }
448 }
449 if (ret == -1) {
450 err(EXIT_FAILURE, "Cannot read from daemon");
451 }
452
453 /* Usually the daemon should not print any message.
454 * Exit with zero status in that case.
455 */
456 exit(errors);
457 }
458 }
459
cd831bd7 460 if (device) {
a517e88b
PB
461 /* Open before spawning new threads. In the future, we may
462 * drop privileges after opening.
463 */
464 fd = open(device, O_RDWR);
465 if (fd == -1) {
466 err(EXIT_FAILURE, "Failed to open %s", device);
cb7cf0e3
RO
467 }
468
b32f6c28
PB
469 if (sockpath == NULL) {
470 sockpath = g_malloc(128);
471 snprintf(sockpath, 128, SOCKET_PATH, basename(device));
cd831bd7 472 }
cd831bd7
TS
473 }
474
802ddc37
PB
475 bdrv_init();
476 atexit(bdrv_close_all);
477
478 bs = bdrv_new("hda");
479 srcpath = argv[optind];
480 if ((ret = bdrv_open(bs, srcpath, flags, NULL)) < 0) {
481 errno = -ret;
482 err(EXIT_FAILURE, "Failed to bdrv_open '%s'", argv[optind]);
483 }
484
485 fd_size = bs->total_sectors * 512;
486
487 if (partition != -1 &&
488 find_partition(bs, partition, &dev_offset, &fd_size)) {
489 err(EXIT_FAILURE, "Could not find partition %d", partition);
490 }
491
7267c094 492 sharing_fds = g_malloc((shared + 1) * sizeof(int));
3b05a8e9 493
b32f6c28
PB
494 if (sockpath) {
495 sharing_fds[0] = unix_socket_incoming(sockpath);
cd831bd7 496 } else {
3b05a8e9 497 sharing_fds[0] = tcp_socket_incoming(bindto, port);
cd831bd7
TS
498 }
499
3b05a8e9 500 if (sharing_fds[0] == -1)
7a5ca864 501 return 1;
f1ef5555
PB
502
503 if (device) {
504 int ret;
505
506 ret = pthread_create(&client_thread, NULL, nbd_client_thread, &fd);
507 if (ret != 0) {
508 errx(EXIT_FAILURE, "Failed to create client thread: %s",
509 strerror(ret));
510 }
511 } else {
512 /* Shut up GCC warnings. */
513 memset(&client_thread, 0, sizeof(client_thread));
514 }
515
3b05a8e9
TS
516 max_fd = sharing_fds[0];
517 nb_fds++;
7a5ca864 518
72aef731 519 data = qemu_blockalign(bs, NBD_BUFFER_SIZE);
bb345110 520 if (data == NULL) {
b6353bea 521 errx(EXIT_FAILURE, "Cannot allocate data buffer");
bb345110 522 }
7a5ca864 523
3b05a8e9 524 do {
3b05a8e9 525 FD_ZERO(&fds);
bb345110 526 FD_SET(sigterm_fd[0], &fds);
3b05a8e9
TS
527 for (i = 0; i < nb_fds; i++)
528 FD_SET(sharing_fds[i], &fds);
529
bb345110
PB
530 do {
531 ret = select(max_fd + 1, &fds, NULL, NULL, NULL);
532 } while (ret == -1 && errno == EINTR);
533 if (ret == -1 || FD_ISSET(sigterm_fd[0], &fds)) {
3b05a8e9 534 break;
bb345110 535 }
3b05a8e9
TS
536
537 if (FD_ISSET(sharing_fds[0], &fds))
538 ret--;
539 for (i = 1; i < nb_fds && ret; i++) {
540 if (FD_ISSET(sharing_fds[i], &fds)) {
541 if (nbd_trip(bs, sharing_fds[i], fd_size, dev_offset,
3777b09f 542 nbdflags, data) != 0) {
3b05a8e9
TS
543 close(sharing_fds[i]);
544 nb_fds--;
545 sharing_fds[i] = sharing_fds[nb_fds];
546 i--;
547 }
548 ret--;
549 }
550 }
551 /* new connection ? */
552 if (FD_ISSET(sharing_fds[0], &fds)) {
553 if (nb_fds < shared + 1) {
554 sharing_fds[nb_fds] = accept(sharing_fds[0],
555 (struct sockaddr *)&addr,
556 &addr_len);
557 if (sharing_fds[nb_fds] != -1 &&
b90fb4b8 558 nbd_negotiate(sharing_fds[nb_fds], fd_size, nbdflags) != -1) {
3b05a8e9
TS
559 if (sharing_fds[nb_fds] > max_fd)
560 max_fd = sharing_fds[nb_fds];
561 nb_fds++;
562 }
563 }
564 }
75818250 565 } while (persistent || nb_fds > 1);
f8a83245 566 qemu_vfree(data);
7a5ca864 567
3b05a8e9 568 close(sharing_fds[0]);
7267c094 569 g_free(sharing_fds);
b32f6c28
PB
570 if (sockpath) {
571 unlink(sockpath);
572 }
7a5ca864 573
a517e88b
PB
574 if (device) {
575 void *ret;
576 pthread_join(client_thread, &ret);
577 exit(ret != NULL);
578 } else {
579 exit(EXIT_SUCCESS);
580 }
7a5ca864 581}