2 * Open connection for network block device
4 * Copyright 1997,1998 Pavel Machek, distribute under GPL
5 * <pavel@atrey.karlin.mff.cuni.cz>
7 * Version 1.0 - 64bit issues should be fixed, now
8 * Version 1.1 - added bs (blocksize) option (Alexey Guzeev, aga@permonline.ru)
9 * Version 1.2 - I added new option '-d' to send the disconnect request
10 * Version 2.0 - Version synchronised with server
11 * Version 2.1 - Check for disconnection before INIT_PASSWD is received
12 * to make errormsg a bit more helpful in case the server can't
13 * open the exported file.
14 * 16/03/2010 - Add IPv6 support.
15 * Kitt Tientanopajai <kitt@kitty.in.th>
16 * Neutron Soutmun <neo.neutron@gmail.com>
17 * Suriya Soutmun <darksolar@gmail.com>
23 #include <sys/ioctl.h>
24 #include <sys/socket.h>
25 #include <sys/types.h>
27 #include <netinet/tcp.h>
28 #include <netinet/in.h>
34 #include <sys/mount.h>
41 #error I need GCC to work
44 #include <linux/ioctl.h>
45 #define MY_NAME "nbd_client"
48 int check_conn(char* devname, int do_print) {
54 if(!strncmp(devname, "/dev/", 5)) {
57 if((p=strchr(devname, 'p'))) {
58 /* We can't do checks on partitions. */
61 snprintf(buf, 256, "/sys/block/%s/pid", devname);
62 if((fd=open(buf, O_RDONLY))<0) {
69 len=read(fd, buf, 256);
71 if(do_print) printf("%s\n", buf);
75 int opennet(char *name, char* portstr, int sdp) {
77 struct addrinfo hints;
78 struct addrinfo *ai = NULL;
79 struct addrinfo *rp = NULL;
82 memset(&hints,'\0',sizeof(hints));
83 hints.ai_family = AF_UNSPEC;
84 hints.ai_socktype = SOCK_STREAM;
85 hints.ai_flags = AI_ADDRCONFIG | AI_NUMERICSERV;
86 hints.ai_protocol = IPPROTO_TCP;
88 e = getaddrinfo(name, portstr, &hints, &ai);
91 fprintf(stderr, "getaddrinfo failed: %s\n", gai_strerror(e));
98 if (ai->ai_family == AF_INET)
99 ai->ai_family = AF_INET_SDP;
100 else (ai->ai_family == AF_INET6)
101 ai->ai_family = AF_INET6_SDP;
103 err("Can't do SDP: I was not compiled with SDP support!");
107 for(rp = ai; rp != NULL; rp = rp->ai_next) {
108 sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
111 continue; /* error */
113 if(connect(sock, rp->ai_addr, rp->ai_addrlen) != -1)
118 err("Socket failed: %m");
126 void negotiate(int sock, u64 *rsize64, u32 *flags, char* name) {
129 char buf[256] = "\0\0\0\0\0\0\0\0\0";
131 printf("Negotiation: ");
132 if (read(sock, buf, 8) < 0)
135 err("Server closed connection");
136 if (strcmp(buf, INIT_PASSWD))
137 err("INIT_PASSWD bad");
139 if (read(sock, &magic, sizeof(magic)) < 0)
141 magic = ntohll(magic);
142 if (magic != cliserv_magic)
143 err("Not enough cliserv_magic");
148 uint64_t reserved = 0;
150 if(read(sock, &tmp, sizeof(uint16_t)) < 0) {
151 err("Failed reading flags: %m");
153 *flags = ((u32)ntohs(tmp)) << 16;
155 /* reserved for future use*/
156 write(sock, &reserved, sizeof(reserved));
158 /* Write the export name that we're after */
159 magic = ntohll(cliserv_magic);
160 write(sock, &magic, sizeof(magic));
161 opt = ntohl(NBD_OPT_EXPORT_NAME);
162 write(sock, &opt, sizeof(opt));
163 namesize = (u64)strlen(name);
164 namesize = ntohll(namesize);
165 write(sock, &namesize, sizeof(namesize));
166 write(sock, name, strlen(name));
169 if (read(sock, &size64, sizeof(size64)) < 0)
170 err("Failed/3: %m\n");
171 size64 = ntohll(size64);
173 #ifdef NBD_SET_SIZE_BLOCKS
174 if ((size64>>10) > (~0UL >> 1)) {
175 printf("size = %luMB", (unsigned long)(size64>>20));
176 err("Exported device is too big for me. Get 64-bit machine :-(\n");
178 printf("size = %luKB", (unsigned long)(size64>>10));
180 if (size64 > (~0UL >> 1)) {
181 printf("size = %luKB", (unsigned long)(size64>>10));
182 err("Exported device is too big. Get 64-bit machine or newer kernel :-(\n");
184 printf("size = %lu", (unsigned long)(size64));
188 if (read(sock, flags, sizeof(*flags)) < 0)
189 err("Failed/4: %m\n");
190 *flags = ntohl(*flags);
192 if(read(sock, &tmp, sizeof(tmp)) < 0)
193 err("Failed/4: %m\n");
194 *flags |= (uint32_t)ntohs(tmp);
197 if (read(sock, &buf, 124) < 0)
198 err("Failed/5: %m\n");
204 void setsizes(int nbd, u64 size64, int blocksize, u32 flags) {
206 int read_only = (flags & NBD_FLAG_READ_ONLY) ? 1 : 0;
208 #ifdef NBD_SET_SIZE_BLOCKS
209 if (size64/blocksize > (~0UL >> 1))
210 err("Device too large.\n");
213 if (ioctl(nbd, NBD_SET_BLKSIZE, (unsigned long)blocksize) < 0)
214 err("Ioctl/1.1a failed: %m\n");
215 size = (unsigned long)(size64/blocksize);
216 if ((er = ioctl(nbd, NBD_SET_SIZE_BLOCKS, size)) < 0)
217 err("Ioctl/1.1b failed: %m\n");
218 fprintf(stderr, "bs=%d, sz=%lu\n", blocksize, size);
221 if (size64 > (~0UL >> 1)) {
222 err("Device too large.\n");
224 size = (unsigned long)size64;
225 if (ioctl(nbd, NBD_SET_SIZE, size) < 0)
226 err("Ioctl NBD_SET_SIZE failed: %m\n");
230 ioctl(nbd, NBD_CLEAR_SOCK);
232 if (ioctl(nbd, BLKROSET, (unsigned long) &read_only) < 0)
233 err("Unable to set read-only attribute for device");
236 void set_timeout(int nbd, int timeout) {
238 #ifdef NBD_SET_TIMEOUT
239 if (ioctl(nbd, NBD_SET_TIMEOUT, (unsigned long)timeout) < 0)
240 err("Ioctl NBD_SET_TIMEOUT failed: %m\n");
241 fprintf(stderr, "timeout=%d\n", timeout);
243 err("Ioctl NBD_SET_TIMEOUT cannot be called when compiled on a system that does not support it\n");
248 void finish_sock(int sock, int nbd, int swap) {
249 if (ioctl(nbd, NBD_SET_SOCK, sock) < 0)
250 err("Ioctl NBD_SET_SOCK failed: %m\n");
253 mlockall(MCL_CURRENT | MCL_FUTURE);
256 void usage(char* errmsg, ...) {
260 va_start(ap, errmsg);
261 snprintf(tmp, 256, "ERROR: %s\n\n", errmsg);
262 vfprintf(stderr, errmsg, ap);
265 fprintf(stderr, "nbd-client version %s\n", PACKAGE_VERSION);
267 fprintf(stderr, "Usage: nbd-client host port nbd_device [-block-size|-b block size] [-timeout|-t timeout] [-swap|-s] [-sdp|-S] [-persist|-p] [-nofork|-n]\n");
268 fprintf(stderr, "Or : nbd-client -d nbd_device\n");
269 fprintf(stderr, "Or : nbd-client -c nbd_device\n");
270 fprintf(stderr, "Or : nbd-client -h|--help\n");
271 fprintf(stderr, "Default value for blocksize is 1024 (recommended for ethernet)\n");
272 fprintf(stderr, "Allowed values for blocksize are 512,1024,2048,4096\n"); /* will be checked in kernel :) */
273 fprintf(stderr, "Note, that kernel 2.4.2 and older ones do not work correctly with\n");
274 fprintf(stderr, "blocksizes other than 1024 without patches\n");
277 void disconnect(char* device) {
278 int nbd = open(device, O_RDWR);
281 err("Cannot open NBD: %m\nPlease ensure the 'nbd' module is loaded.");
282 printf("Disconnecting: que, ");
283 if (ioctl(nbd, NBD_CLEAR_QUE)< 0)
284 err("Ioctl failed: %m\n");
285 printf("disconnect, ");
286 #ifdef NBD_DISCONNECT
287 if (ioctl(nbd, NBD_DISCONNECT)<0)
288 err("Ioctl failed: %m\n");
291 fprintf(stderr, "Can't disconnect: I was not compiled with disconnect support!\n" );
294 if (ioctl(nbd, NBD_CLEAR_SOCK)<0)
295 err("Ioctl failed: %m\n");
299 int main(int argc, char *argv[]) {
315 struct option long_options[] = {
316 { "block-size", required_argument, NULL, 'b' },
317 { "check", required_argument, NULL, 'c' },
318 { "disconnect", required_argument, NULL, 'd' },
319 { "help", no_argument, NULL, 'h' },
320 { "name", required_argument, NULL, 'N' },
321 { "nofork", no_argument, NULL, 'n' },
322 { "persist", no_argument, NULL, 'p' },
323 { "sdp", no_argument, NULL, 'S' },
324 { "swap", no_argument, NULL, 's' },
325 { "timeout", required_argument, NULL, 't' },
331 while((c=getopt_long_only(argc, argv, "-b:c:d:hnN:pSst:", long_options, NULL))>=0) {
334 // non-option argument
335 if(strchr(optarg, '=')) {
336 // old-style 'bs=' or 'timeout='
338 fprintf(stderr, "WARNING: old-style command-line argument encountered. This is deprecated.\n");
339 if(!strncmp(optarg, "bs=", 3)) {
343 if(!strncmp(optarg, "timeout=", 8)) {
347 usage("unknown option %s encountered", optarg);
350 switch(nonspecial++) {
358 if(!strtol(optarg, NULL, 0)) {
359 // not parseable as a number, assume it's the device and we have a name
364 usage("port and name specified at the same time. This is not supported.");
374 usage("too many non-option arguments specified");
380 blocksize=(int)strtol(optarg, NULL, 0);
383 check_conn(optarg, 1);
397 usage("port and name specified at the same time. This is not supported.");
400 port = NBD_DEFAULT_PORT;
413 timeout=strtol(optarg, NULL, 0);
416 fprintf(stderr, "E: option eaten by 42 mice\n");
421 if((!port && !name) || !hostname || !nbddev) {
422 usage("not enough information specified");
426 nbd = open(nbddev, O_RDWR);
428 err("Cannot open NBD: %m\nPlease ensure the 'nbd' module is loaded.");
429 ++argv; --argc; /* skip device */
431 sock = opennet(hostname, port, sdp);
433 negotiate(sock, &size64, &flags, name);
434 setsizes(nbd, size64, blocksize, flags);
435 set_timeout(nbd, timeout);
436 finish_sock(sock, nbd, swap);
441 if(!nofork) daemon(0,0);
446 /* Due to a race, the kernel NBD driver cannot
447 * call for a reread of the partition table
448 * in the handling of the NBD_DO_IT ioctl().
449 * Therefore, this is done in the first open()
450 * of the device. We therefore make sure that
451 * the device is opened at least once after the
452 * connection was made. This has to be done in a
453 * separate process, since the NBD_DO_IT ioctl()
454 * does not return until the NBD device has
457 while(check_conn(nbddev, 0)) {
460 open(nbddev, O_RDONLY);
465 if (ioctl(nbd, NBD_DO_IT) < 0) {
466 fprintf(stderr, "Kernel call returned: %m");
468 /* The user probably did 'nbd-client -d' on us.
476 fprintf(stderr, " Reconnecting\n");
477 close(sock); close(nbd);
478 sock = opennet(hostname, port, sdp);
479 nbd = open(nbddev, O_RDWR);
480 negotiate(sock, &new_size, &new_flags, name);
481 if (size64 != new_size) {
482 err("Size of the device changed. Bye");
484 setsizes(nbd, size64, blocksize,
487 set_timeout(nbd, timeout);
488 finish_sock(sock,nbd,swap);
492 /* We're on 2.4. It's not clearly defined what exactly
493 * happened at this point. Probably best to quit, now
495 fprintf(stderr, "Kernel call returned.");
499 printf("Closing: que, ");
500 ioctl(nbd, NBD_CLEAR_QUE);
502 ioctl(nbd, NBD_CLEAR_SOCK);