2 * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws>
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.
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.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, see <http://www.gnu.org/licenses/>.
19 #include "qemu-common.h"
20 #include "block_int.h"
27 #include <sys/types.h>
28 #include <sys/socket.h>
29 #include <netinet/in.h>
30 #include <netinet/tcp.h>
31 #include <arpa/inet.h>
36 #define SOCKET_PATH "/var/lock/qemu-nbd-%s"
38 static int sigterm_wfd
;
39 static NBDExport
*exp
;
43 static char *sockpath
;
45 static void usage(const char *name
)
48 "Usage: %s [OPTIONS] FILE\n"
49 "QEMU Disk Network Block Device Server\n"
51 " -p, --port=PORT port to listen on (default `%d')\n"
52 " -o, --offset=OFFSET offset into the image\n"
53 " -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
54 " -k, --socket=PATH path to the unix socket\n"
55 " (default '"SOCKET_PATH
"')\n"
56 " -r, --read-only export read-only\n"
57 " -P, --partition=NUM only expose partition NUM\n"
58 " -s, --snapshot use snapshot file\n"
59 " -n, --nocache disable host cache\n"
60 " -c, --connect=DEV connect FILE to the local NBD device DEV\n"
61 " -d, --disconnect disconnect the specified device\n"
62 " -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
63 " -t, --persistent don't exit on the last connection\n"
64 " -v, --verbose display extra debugging information\n"
65 " -h, --help display this help and exit\n"
66 " -V, --version output version information and exit\n"
68 "Report bugs to <anthony@codemonkey.ws>\n"
69 , name
, NBD_DEFAULT_PORT
, "DEVICE");
72 static void version(const char *name
)
76 "Written by Anthony Liguori.\n"
78 "Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>.\n"
79 "This is free software; see the source for copying conditions. There is NO\n"
80 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
84 struct partition_record
88 uint32_t start_cylinder
;
94 uint32_t start_sector_abs
;
95 uint32_t nb_sectors_abs
;
98 static void read_partition(uint8_t *p
, struct partition_record
*r
)
101 r
->start_head
= p
[1];
102 r
->start_cylinder
= p
[3] | ((p
[2] << 2) & 0x0300);
103 r
->start_sector
= p
[2] & 0x3f;
106 r
->end_cylinder
= p
[7] | ((p
[6] << 2) & 0x300);
107 r
->end_sector
= p
[6] & 0x3f;
108 r
->start_sector_abs
= p
[8] | p
[9] << 8 | p
[10] << 16 | p
[11] << 24;
109 r
->nb_sectors_abs
= p
[12] | p
[13] << 8 | p
[14] << 16 | p
[15] << 24;
112 static int find_partition(BlockDriverState
*bs
, int partition
,
113 off_t
*offset
, off_t
*size
)
115 struct partition_record mbr
[4];
121 if ((ret
= bdrv_read(bs
, 0, data
, 1)) < 0) {
123 err(EXIT_FAILURE
, "error while reading");
126 if (data
[510] != 0x55 || data
[511] != 0xaa) {
131 for (i
= 0; i
< 4; i
++) {
132 read_partition(&data
[446 + 16 * i
], &mbr
[i
]);
134 if (!mbr
[i
].nb_sectors_abs
)
137 if (mbr
[i
].system
== 0xF || mbr
[i
].system
== 0x5) {
138 struct partition_record ext
[4];
142 if ((ret
= bdrv_read(bs
, mbr
[i
].start_sector_abs
, data1
, 1)) < 0) {
144 err(EXIT_FAILURE
, "error while reading");
147 for (j
= 0; j
< 4; j
++) {
148 read_partition(&data1
[446 + 16 * j
], &ext
[j
]);
149 if (!ext
[j
].nb_sectors_abs
)
152 if ((ext_partnum
+ j
+ 1) == partition
) {
153 *offset
= (uint64_t)ext
[j
].start_sector_abs
<< 9;
154 *size
= (uint64_t)ext
[j
].nb_sectors_abs
<< 9;
159 } else if ((i
+ 1) == partition
) {
160 *offset
= (uint64_t)mbr
[i
].start_sector_abs
<< 9;
161 *size
= (uint64_t)mbr
[i
].nb_sectors_abs
<< 9;
170 static void termsig_handler(int signum
)
172 static int sigterm_reported
;
173 if (!sigterm_reported
) {
174 sigterm_reported
= (write(sigterm_wfd
, "", 1) == 1);
178 static void *show_parts(void *arg
)
182 /* linux just needs an open() to trigger
183 * the partition table update
184 * but remember to load the module with max_part != 0 :
185 * modprobe nbd max_part=63
187 nbd
= open(device
, O_RDWR
);
194 static void *nbd_client_thread(void *arg
)
196 int fd
= *(int *)arg
;
202 pthread_t show_parts_thread
;
205 sock
= unix_socket_outgoing(sockpath
);
209 } while (sock
== -1);
211 ret
= nbd_receive_negotiate(sock
, NULL
, &nbdflags
,
217 ret
= nbd_init(fd
, sock
, nbdflags
, size
, blocksize
);
222 /* update partition table */
223 pthread_create(&show_parts_thread
, NULL
, show_parts
, NULL
);
226 fprintf(stderr
, "NBD device %s is now connected to %s\n",
229 /* Close stderr so that the qemu-nbd process exits. */
230 dup2(STDOUT_FILENO
, STDERR_FILENO
);
233 ret
= nbd_client(fd
);
238 kill(getpid(), SIGTERM
);
239 return (void *) EXIT_SUCCESS
;
242 kill(getpid(), SIGTERM
);
243 return (void *) EXIT_FAILURE
;
246 int main(int argc
, char **argv
)
248 BlockDriverState
*bs
;
249 off_t dev_offset
= 0;
250 uint32_t nbdflags
= 0;
251 bool disconnect
= false;
252 const char *bindto
= "0.0.0.0";
253 int port
= NBD_DEFAULT_PORT
;
254 struct sockaddr_in addr
;
255 socklen_t addr_len
= sizeof(addr
);
257 const char *sopt
= "hVb:o:p:rsnP:c:dvk:e:t";
258 struct option lopt
[] = {
259 { "help", 0, NULL
, 'h' },
260 { "version", 0, NULL
, 'V' },
261 { "bind", 1, NULL
, 'b' },
262 { "port", 1, NULL
, 'p' },
263 { "socket", 1, NULL
, 'k' },
264 { "offset", 1, NULL
, 'o' },
265 { "read-only", 0, NULL
, 'r' },
266 { "partition", 1, NULL
, 'P' },
267 { "connect", 1, NULL
, 'c' },
268 { "disconnect", 0, NULL
, 'd' },
269 { "snapshot", 0, NULL
, 's' },
270 { "nocache", 0, NULL
, 'n' },
271 { "shared", 1, NULL
, 'e' },
272 { "persistent", 0, NULL
, 't' },
273 { "verbose", 0, NULL
, 'v' },
280 int flags
= BDRV_O_RDWR
;
291 pthread_t client_thread
;
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.
296 struct sigaction sa_sigterm
;
298 if (qemu_pipe(sigterm_fd
) == -1) {
299 err(EXIT_FAILURE
, "Error setting up communication pipe");
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
);
307 while ((ch
= getopt_long(argc
, argv
, sopt
, lopt
, &opt_ind
)) != -1) {
310 flags
|= BDRV_O_SNAPSHOT
;
313 flags
|= BDRV_O_NOCACHE
| BDRV_O_CACHE_WB
;
319 li
= strtol(optarg
, &end
, 0);
321 errx(EXIT_FAILURE
, "Invalid port `%s'", optarg
);
323 if (li
< 1 || li
> 65535) {
324 errx(EXIT_FAILURE
, "Port out of range `%s'", optarg
);
329 dev_offset
= strtoll (optarg
, &end
, 0);
331 errx(EXIT_FAILURE
, "Invalid offset `%s'", optarg
);
333 if (dev_offset
< 0) {
334 errx(EXIT_FAILURE
, "Offset must be positive `%s'", optarg
);
338 nbdflags
|= NBD_FLAG_READ_ONLY
;
339 flags
&= ~BDRV_O_RDWR
;
342 partition
= strtol(optarg
, &end
, 0);
344 errx(EXIT_FAILURE
, "Invalid partition `%s'", optarg
);
345 if (partition
< 1 || partition
> 8)
346 errx(EXIT_FAILURE
, "Invalid partition %d", partition
);
350 if (sockpath
[0] != '/')
351 errx(EXIT_FAILURE
, "socket path must be absolute\n");
360 shared
= strtol(optarg
, &end
, 0);
362 errx(EXIT_FAILURE
, "Invalid shared device number '%s'", optarg
);
365 errx(EXIT_FAILURE
, "Shared device number must be greater than 0\n");
383 errx(EXIT_FAILURE
, "Try `%s --help' for more information.",
388 if ((argc
- optind
) != 1) {
389 errx(EXIT_FAILURE
, "Invalid number of argument.\n"
390 "Try `%s --help' for more information.",
395 fd
= open(argv
[optind
], O_RDWR
);
397 err(EXIT_FAILURE
, "Cannot open %s", argv
[optind
]);
403 printf("%s disconnected\n", argv
[optind
]);
408 if (device
&& !verbose
) {
413 if (qemu_pipe(stderr_fd
) == -1) {
414 err(EXIT_FAILURE
, "Error setting up communication pipe");
417 /* Now daemonize, but keep a communication channel open to
418 * print errors and exit with the proper status code.
423 ret
= qemu_daemon(0, 0);
425 /* Temporarily redirect stderr to the parent's pipe... */
426 dup2(stderr_fd
[1], STDERR_FILENO
);
428 err(EXIT_FAILURE
, "Failed to daemonize");
431 /* ... close the descriptor we inherited and go on. */
437 /* In the parent. Print error messages from the child until
438 * it closes the pipe.
441 buf
= g_malloc(1024);
442 while ((ret
= read(stderr_fd
[0], buf
, 1024)) > 0) {
444 ret
= qemu_write_full(STDERR_FILENO
, buf
, ret
);
450 err(EXIT_FAILURE
, "Cannot read from daemon");
453 /* Usually the daemon should not print any message.
454 * Exit with zero status in that case.
461 /* Open before spawning new threads. In the future, we may
462 * drop privileges after opening.
464 fd
= open(device
, O_RDWR
);
466 err(EXIT_FAILURE
, "Failed to open %s", device
);
469 if (sockpath
== NULL
) {
470 sockpath
= g_malloc(128);
471 snprintf(sockpath
, 128, SOCKET_PATH
, basename(device
));
476 atexit(bdrv_close_all
);
478 bs
= bdrv_new("hda");
479 srcpath
= argv
[optind
];
480 if ((ret
= bdrv_open(bs
, srcpath
, flags
, NULL
)) < 0) {
482 err(EXIT_FAILURE
, "Failed to bdrv_open '%s'", argv
[optind
]);
485 fd_size
= bs
->total_sectors
* 512;
487 if (partition
!= -1 &&
488 find_partition(bs
, partition
, &dev_offset
, &fd_size
)) {
489 err(EXIT_FAILURE
, "Could not find partition %d", partition
);
492 exp
= nbd_export_new(bs
, dev_offset
, fd_size
, nbdflags
);
493 sharing_fds
= g_malloc((shared
+ 1) * sizeof(int));
496 sharing_fds
[0] = unix_socket_incoming(sockpath
);
498 sharing_fds
[0] = tcp_socket_incoming(bindto
, port
);
501 if (sharing_fds
[0] == -1)
507 ret
= pthread_create(&client_thread
, NULL
, nbd_client_thread
, &fd
);
509 errx(EXIT_FAILURE
, "Failed to create client thread: %s",
513 /* Shut up GCC warnings. */
514 memset(&client_thread
, 0, sizeof(client_thread
));
517 max_fd
= sharing_fds
[0];
522 FD_SET(sigterm_fd
[0], &fds
);
523 for (i
= 0; i
< nb_fds
; i
++)
524 FD_SET(sharing_fds
[i
], &fds
);
527 ret
= select(max_fd
+ 1, &fds
, NULL
, NULL
, NULL
);
528 } while (ret
== -1 && errno
== EINTR
);
529 if (ret
== -1 || FD_ISSET(sigterm_fd
[0], &fds
)) {
533 if (FD_ISSET(sharing_fds
[0], &fds
))
535 for (i
= 1; i
< nb_fds
&& ret
; i
++) {
536 if (FD_ISSET(sharing_fds
[i
], &fds
)) {
537 if (nbd_trip(exp
, sharing_fds
[i
]) != 0) {
538 close(sharing_fds
[i
]);
540 sharing_fds
[i
] = sharing_fds
[nb_fds
];
546 /* new connection ? */
547 if (FD_ISSET(sharing_fds
[0], &fds
)) {
548 if (nb_fds
< shared
+ 1) {
549 sharing_fds
[nb_fds
] = accept(sharing_fds
[0],
550 (struct sockaddr
*)&addr
,
552 if (sharing_fds
[nb_fds
] != -1 &&
553 nbd_negotiate(exp
, sharing_fds
[nb_fds
]) != -1) {
554 if (sharing_fds
[nb_fds
] > max_fd
)
555 max_fd
= sharing_fds
[nb_fds
];
560 } while (persistent
|| nb_fds
> 1);
562 close(sharing_fds
[0]);
563 nbd_export_close(exp
);
571 pthread_join(client_thread
, &ret
);