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"
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 NBDExport
*exp
;
41 static char *sockpath
;
42 static bool sigterm_reported
;
43 static bool nbd_started
;
44 static int shared
= 1;
47 static void usage(const char *name
)
50 "Usage: %s [OPTIONS] FILE\n"
51 "QEMU Disk Network Block Device Server\n"
53 " -h, --help display this help and exit\n"
54 " -V, --version output version information and exit\n"
56 "Connection properties:\n"
57 " -p, --port=PORT port to listen on (default `%d')\n"
58 " -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
59 " -k, --socket=PATH path to the unix socket\n"
60 " (default '"SOCKET_PATH
"')\n"
61 " -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
62 " -t, --persistent don't exit on the last connection\n"
63 " -v, --verbose display extra debugging information\n"
65 "Exposing part of the image:\n"
66 " -o, --offset=OFFSET offset into the image\n"
67 " -P, --partition=NUM only expose partition NUM\n"
70 "Kernel NBD client support:\n"
71 " -c, --connect=DEV connect FILE to the local NBD device DEV\n"
72 " -d, --disconnect disconnect the specified device\n"
76 "Block device options:\n"
77 " -r, --read-only export read-only\n"
78 " -s, --snapshot use snapshot file\n"
79 " -n, --nocache disable host cache\n"
81 "Report bugs to <qemu-devel@nongnu.org>\n"
82 , name
, NBD_DEFAULT_PORT
, "DEVICE");
85 static void version(const char *name
)
89 "Written by Anthony Liguori.\n"
91 "Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>.\n"
92 "This is free software; see the source for copying conditions. There is NO\n"
93 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
97 struct partition_record
101 uint32_t start_cylinder
;
102 uint8_t start_sector
;
105 uint8_t end_cylinder
;
107 uint32_t start_sector_abs
;
108 uint32_t nb_sectors_abs
;
111 static void read_partition(uint8_t *p
, struct partition_record
*r
)
114 r
->start_head
= p
[1];
115 r
->start_cylinder
= p
[3] | ((p
[2] << 2) & 0x0300);
116 r
->start_sector
= p
[2] & 0x3f;
119 r
->end_cylinder
= p
[7] | ((p
[6] << 2) & 0x300);
120 r
->end_sector
= p
[6] & 0x3f;
121 r
->start_sector_abs
= p
[8] | p
[9] << 8 | p
[10] << 16 | p
[11] << 24;
122 r
->nb_sectors_abs
= p
[12] | p
[13] << 8 | p
[14] << 16 | p
[15] << 24;
125 static int find_partition(BlockDriverState
*bs
, int partition
,
126 off_t
*offset
, off_t
*size
)
128 struct partition_record mbr
[4];
134 if ((ret
= bdrv_read(bs
, 0, data
, 1)) < 0) {
136 err(EXIT_FAILURE
, "error while reading");
139 if (data
[510] != 0x55 || data
[511] != 0xaa) {
143 for (i
= 0; i
< 4; i
++) {
144 read_partition(&data
[446 + 16 * i
], &mbr
[i
]);
146 if (!mbr
[i
].nb_sectors_abs
)
149 if (mbr
[i
].system
== 0xF || mbr
[i
].system
== 0x5) {
150 struct partition_record ext
[4];
154 if ((ret
= bdrv_read(bs
, mbr
[i
].start_sector_abs
, data1
, 1)) < 0) {
156 err(EXIT_FAILURE
, "error while reading");
159 for (j
= 0; j
< 4; j
++) {
160 read_partition(&data1
[446 + 16 * j
], &ext
[j
]);
161 if (!ext
[j
].nb_sectors_abs
)
164 if ((ext_partnum
+ j
+ 1) == partition
) {
165 *offset
= (uint64_t)ext
[j
].start_sector_abs
<< 9;
166 *size
= (uint64_t)ext
[j
].nb_sectors_abs
<< 9;
171 } else if ((i
+ 1) == partition
) {
172 *offset
= (uint64_t)mbr
[i
].start_sector_abs
<< 9;
173 *size
= (uint64_t)mbr
[i
].nb_sectors_abs
<< 9;
181 static void termsig_handler(int signum
)
183 sigterm_reported
= true;
187 static void *show_parts(void *arg
)
192 /* linux just needs an open() to trigger
193 * the partition table update
194 * but remember to load the module with max_part != 0 :
195 * modprobe nbd max_part=63
197 nbd
= open(device
, O_RDWR
);
204 static void *nbd_client_thread(void *arg
)
212 pthread_t show_parts_thread
;
214 sock
= unix_socket_outgoing(sockpath
);
219 ret
= nbd_receive_negotiate(sock
, NULL
, &nbdflags
,
225 fd
= open(device
, O_RDWR
);
227 /* Linux-only, we can use %m in printf. */
228 fprintf(stderr
, "Failed to open %s: %m", device
);
232 ret
= nbd_init(fd
, sock
, nbdflags
, size
, blocksize
);
237 /* update partition table */
238 pthread_create(&show_parts_thread
, NULL
, show_parts
, device
);
241 fprintf(stderr
, "NBD device %s is now connected to %s\n",
244 /* Close stderr so that the qemu-nbd process exits. */
245 dup2(STDOUT_FILENO
, STDERR_FILENO
);
248 ret
= nbd_client(fd
);
253 kill(getpid(), SIGTERM
);
254 return (void *) EXIT_SUCCESS
;
257 kill(getpid(), SIGTERM
);
258 return (void *) EXIT_FAILURE
;
261 static int nbd_can_accept(void *opaque
)
263 return nb_fds
< shared
;
266 static void nbd_client_closed(NBDClient
*client
)
272 static void nbd_accept(void *opaque
)
274 int server_fd
= (uintptr_t) opaque
;
275 struct sockaddr_in addr
;
276 socklen_t addr_len
= sizeof(addr
);
278 int fd
= accept(server_fd
, (struct sockaddr
*)&addr
, &addr_len
);
280 if (fd
>= 0 && nbd_client_new(exp
, fd
, nbd_client_closed
)) {
285 int main(int argc
, char **argv
)
287 BlockDriverState
*bs
;
288 off_t dev_offset
= 0;
289 uint32_t nbdflags
= 0;
290 bool disconnect
= false;
291 const char *bindto
= "0.0.0.0";
293 int port
= NBD_DEFAULT_PORT
;
295 const char *sopt
= "hVb:o:p:rsnP:c:dvk:e:t";
296 struct option lopt
[] = {
297 { "help", 0, NULL
, 'h' },
298 { "version", 0, NULL
, 'V' },
299 { "bind", 1, NULL
, 'b' },
300 { "port", 1, NULL
, 'p' },
301 { "socket", 1, NULL
, 'k' },
302 { "offset", 1, NULL
, 'o' },
303 { "read-only", 0, NULL
, 'r' },
304 { "partition", 1, NULL
, 'P' },
305 { "connect", 1, NULL
, 'c' },
306 { "disconnect", 0, NULL
, 'd' },
307 { "snapshot", 0, NULL
, 's' },
308 { "nocache", 0, NULL
, 'n' },
309 { "shared", 1, NULL
, 'e' },
310 { "persistent", 0, NULL
, 't' },
311 { "verbose", 0, NULL
, 'v' },
318 int flags
= BDRV_O_RDWR
;
323 pthread_t client_thread
;
325 /* The client thread uses SIGTERM to interrupt the server. A signal
326 * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
328 struct sigaction sa_sigterm
;
329 memset(&sa_sigterm
, 0, sizeof(sa_sigterm
));
330 sa_sigterm
.sa_handler
= termsig_handler
;
331 sigaction(SIGTERM
, &sa_sigterm
, NULL
);
333 while ((ch
= getopt_long(argc
, argv
, sopt
, lopt
, &opt_ind
)) != -1) {
336 flags
|= BDRV_O_SNAPSHOT
;
339 flags
|= BDRV_O_NOCACHE
| BDRV_O_CACHE_WB
;
345 li
= strtol(optarg
, &end
, 0);
347 errx(EXIT_FAILURE
, "Invalid port `%s'", optarg
);
349 if (li
< 1 || li
> 65535) {
350 errx(EXIT_FAILURE
, "Port out of range `%s'", optarg
);
355 dev_offset
= strtoll (optarg
, &end
, 0);
357 errx(EXIT_FAILURE
, "Invalid offset `%s'", optarg
);
359 if (dev_offset
< 0) {
360 errx(EXIT_FAILURE
, "Offset must be positive `%s'", optarg
);
364 nbdflags
|= NBD_FLAG_READ_ONLY
;
365 flags
&= ~BDRV_O_RDWR
;
368 partition
= strtol(optarg
, &end
, 0);
370 errx(EXIT_FAILURE
, "Invalid partition `%s'", optarg
);
371 if (partition
< 1 || partition
> 8)
372 errx(EXIT_FAILURE
, "Invalid partition %d", partition
);
376 if (sockpath
[0] != '/')
377 errx(EXIT_FAILURE
, "socket path must be absolute\n");
386 shared
= strtol(optarg
, &end
, 0);
388 errx(EXIT_FAILURE
, "Invalid shared device number '%s'", optarg
);
391 errx(EXIT_FAILURE
, "Shared device number must be greater than 0\n");
409 errx(EXIT_FAILURE
, "Try `%s --help' for more information.",
414 if ((argc
- optind
) != 1) {
415 errx(EXIT_FAILURE
, "Invalid number of argument.\n"
416 "Try `%s --help' for more information.",
421 fd
= open(argv
[optind
], O_RDWR
);
423 err(EXIT_FAILURE
, "Cannot open %s", argv
[optind
]);
429 printf("%s disconnected\n", argv
[optind
]);
434 if (device
&& !verbose
) {
439 if (qemu_pipe(stderr_fd
) < 0) {
440 err(EXIT_FAILURE
, "Error setting up communication pipe");
443 /* Now daemonize, but keep a communication channel open to
444 * print errors and exit with the proper status code.
449 ret
= qemu_daemon(1, 0);
451 /* Temporarily redirect stderr to the parent's pipe... */
452 dup2(stderr_fd
[1], STDERR_FILENO
);
454 err(EXIT_FAILURE
, "Failed to daemonize");
457 /* ... close the descriptor we inherited and go on. */
463 /* In the parent. Print error messages from the child until
464 * it closes the pipe.
467 buf
= g_malloc(1024);
468 while ((ret
= read(stderr_fd
[0], buf
, 1024)) > 0) {
470 ret
= qemu_write_full(STDERR_FILENO
, buf
, ret
);
476 err(EXIT_FAILURE
, "Cannot read from daemon");
479 /* Usually the daemon should not print any message.
480 * Exit with zero status in that case.
486 if (device
!= NULL
&& sockpath
== NULL
) {
487 sockpath
= g_malloc(128);
488 snprintf(sockpath
, 128, SOCKET_PATH
, basename(device
));
492 atexit(bdrv_close_all
);
494 bs
= bdrv_new("hda");
495 srcpath
= argv
[optind
];
496 if ((ret
= bdrv_open(bs
, srcpath
, flags
, NULL
)) < 0) {
498 err(EXIT_FAILURE
, "Failed to bdrv_open '%s'", argv
[optind
]);
501 fd_size
= bdrv_getlength(bs
);
503 if (partition
!= -1) {
504 ret
= find_partition(bs
, partition
, &dev_offset
, &fd_size
);
507 err(EXIT_FAILURE
, "Could not find partition %d", partition
);
511 exp
= nbd_export_new(bs
, dev_offset
, fd_size
, nbdflags
);
514 fd
= unix_socket_incoming(sockpath
);
516 fd
= tcp_socket_incoming(bindto
, port
);
526 ret
= pthread_create(&client_thread
, NULL
, nbd_client_thread
, device
);
528 errx(EXIT_FAILURE
, "Failed to create client thread: %s",
532 /* Shut up GCC warnings. */
533 memset(&client_thread
, 0, sizeof(client_thread
));
536 qemu_init_main_loop();
537 qemu_set_fd_handler2(fd
, nbd_can_accept
, nbd_accept
, NULL
,
538 (void *)(uintptr_t)fd
);
540 /* now when the initialization is (almost) complete, chdir("/")
541 * to free any busy filesystems */
542 if (chdir("/") < 0) {
543 err(EXIT_FAILURE
, "Could not chdir to root directory");
547 main_loop_wait(false);
548 } while (!sigterm_reported
&& (persistent
|| !nbd_started
|| nb_fds
> 0));
550 nbd_export_close(exp
);
557 pthread_join(client_thread
, &ret
);