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);
145 uint32_t reserved = 0;
147 if (magic != opts_magic)
148 err("Not enough opts_magic");
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(opts_magic);
160 write(sock, &magic, sizeof(magic));
161 opt = ntohl(NBD_OPT_EXPORT_NAME);
162 write(sock, &opt, sizeof(opt));
163 namesize = (u32)strlen(name);
164 namesize = ntohl(namesize);
165 write(sock, &namesize, sizeof(namesize));
166 write(sock, name, strlen(name));
168 if (magic != cliserv_magic)
169 err("Not enough cliserv_magic");
173 if (read(sock, &size64, sizeof(size64)) < 0)
174 err("Failed/3: %m\n");
175 size64 = ntohll(size64);
177 #ifdef NBD_SET_SIZE_BLOCKS
178 if ((size64>>10) > (~0UL >> 1)) {
179 printf("size = %luMB", (unsigned long)(size64>>20));
180 err("Exported device is too big for me. Get 64-bit machine :-(\n");
182 printf("size = %luKB", (unsigned long)(size64>>10));
184 if (size64 > (~0UL >> 1)) {
185 printf("size = %luKB", (unsigned long)(size64>>10));
186 err("Exported device is too big. Get 64-bit machine or newer kernel :-(\n");
188 printf("size = %lu", (unsigned long)(size64));
192 if (read(sock, flags, sizeof(*flags)) < 0)
193 err("Failed/4: %m\n");
194 *flags = ntohl(*flags);
196 if(read(sock, &tmp, sizeof(tmp)) < 0)
197 err("Failed/4: %m\n");
198 *flags |= (uint32_t)ntohs(tmp);
201 if (read(sock, &buf, 124) < 0)
202 err("Failed/5: %m\n");
208 void setsizes(int nbd, u64 size64, int blocksize, u32 flags) {
210 int read_only = (flags & NBD_FLAG_READ_ONLY) ? 1 : 0;
212 #ifdef NBD_SET_SIZE_BLOCKS
213 if (size64/blocksize > (~0UL >> 1))
214 err("Device too large.\n");
217 if (ioctl(nbd, NBD_SET_BLKSIZE, (unsigned long)blocksize) < 0)
218 err("Ioctl/1.1a failed: %m\n");
219 size = (unsigned long)(size64/blocksize);
220 if ((er = ioctl(nbd, NBD_SET_SIZE_BLOCKS, size)) < 0)
221 err("Ioctl/1.1b failed: %m\n");
222 fprintf(stderr, "bs=%d, sz=%lu\n", blocksize, size);
225 if (size64 > (~0UL >> 1)) {
226 err("Device too large.\n");
228 size = (unsigned long)size64;
229 if (ioctl(nbd, NBD_SET_SIZE, size) < 0)
230 err("Ioctl NBD_SET_SIZE failed: %m\n");
234 ioctl(nbd, NBD_CLEAR_SOCK);
236 if (ioctl(nbd, BLKROSET, (unsigned long) &read_only) < 0)
237 err("Unable to set read-only attribute for device");
240 void set_timeout(int nbd, int timeout) {
242 #ifdef NBD_SET_TIMEOUT
243 if (ioctl(nbd, NBD_SET_TIMEOUT, (unsigned long)timeout) < 0)
244 err("Ioctl NBD_SET_TIMEOUT failed: %m\n");
245 fprintf(stderr, "timeout=%d\n", timeout);
247 err("Ioctl NBD_SET_TIMEOUT cannot be called when compiled on a system that does not support it\n");
252 void finish_sock(int sock, int nbd, int swap) {
253 if (ioctl(nbd, NBD_SET_SOCK, sock) < 0)
254 err("Ioctl NBD_SET_SOCK failed: %m\n");
257 mlockall(MCL_CURRENT | MCL_FUTURE);
260 void usage(char* errmsg, ...) {
264 va_start(ap, errmsg);
265 snprintf(tmp, 256, "ERROR: %s\n\n", errmsg);
266 vfprintf(stderr, errmsg, ap);
269 fprintf(stderr, "nbd-client version %s\n", PACKAGE_VERSION);
271 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] [-name|-N name]\n");
272 fprintf(stderr, "Or : nbd-client -d nbd_device\n");
273 fprintf(stderr, "Or : nbd-client -c nbd_device\n");
274 fprintf(stderr, "Or : nbd-client -h|--help\n");
275 fprintf(stderr, "Default value for blocksize is 1024 (recommended for ethernet)\n");
276 fprintf(stderr, "Allowed values for blocksize are 512,1024,2048,4096\n"); /* will be checked in kernel :) */
277 fprintf(stderr, "Note, that kernel 2.4.2 and older ones do not work correctly with\n");
278 fprintf(stderr, "blocksizes other than 1024 without patches\n");
281 void disconnect(char* device) {
282 int nbd = open(device, O_RDWR);
285 err("Cannot open NBD: %m\nPlease ensure the 'nbd' module is loaded.");
286 printf("Disconnecting: que, ");
287 if (ioctl(nbd, NBD_CLEAR_QUE)< 0)
288 err("Ioctl failed: %m\n");
289 printf("disconnect, ");
290 #ifdef NBD_DISCONNECT
291 if (ioctl(nbd, NBD_DISCONNECT)<0)
292 err("Ioctl failed: %m\n");
295 fprintf(stderr, "Can't disconnect: I was not compiled with disconnect support!\n" );
298 if (ioctl(nbd, NBD_CLEAR_SOCK)<0)
299 err("Ioctl failed: %m\n");
303 int main(int argc, char *argv[]) {
319 struct option long_options[] = {
320 { "block-size", required_argument, NULL, 'b' },
321 { "check", required_argument, NULL, 'c' },
322 { "disconnect", required_argument, NULL, 'd' },
323 { "help", no_argument, NULL, 'h' },
324 { "name", required_argument, NULL, 'N' },
325 { "nofork", no_argument, NULL, 'n' },
326 { "persist", no_argument, NULL, 'p' },
327 { "sdp", no_argument, NULL, 'S' },
328 { "swap", no_argument, NULL, 's' },
329 { "timeout", required_argument, NULL, 't' },
335 while((c=getopt_long_only(argc, argv, "-b:c:d:hnN:pSst:", long_options, NULL))>=0) {
338 // non-option argument
339 if(strchr(optarg, '=')) {
340 // old-style 'bs=' or 'timeout='
342 fprintf(stderr, "WARNING: old-style command-line argument encountered. This is deprecated.\n");
343 if(!strncmp(optarg, "bs=", 3)) {
347 if(!strncmp(optarg, "timeout=", 8)) {
351 usage("unknown option %s encountered", optarg);
354 switch(nonspecial++) {
361 if(!strtol(optarg, NULL, 0)) {
362 // not parseable as a number, assume it's the device and we have a name
368 usage("port and name specified at the same time. This is not supported.");
378 usage("too many non-option arguments specified");
384 blocksize=(int)strtol(optarg, NULL, 0);
387 return check_conn(optarg, 1);
400 usage("port and name specified at the same time. This is not supported.");
403 port = NBD_DEFAULT_PORT;
416 timeout=strtol(optarg, NULL, 0);
419 fprintf(stderr, "E: option eaten by 42 mice\n");
424 if((!port && !name) || !hostname || !nbddev) {
425 usage("not enough information specified");
429 nbd = open(nbddev, O_RDWR);
431 err("Cannot open NBD: %m\nPlease ensure the 'nbd' module is loaded.");
432 ++argv; --argc; /* skip device */
434 sock = opennet(hostname, port, sdp);
436 negotiate(sock, &size64, &flags, name);
437 setsizes(nbd, size64, blocksize, flags);
438 set_timeout(nbd, timeout);
439 finish_sock(sock, nbd, swap);
444 if(!nofork) daemon(0,0);
449 /* Due to a race, the kernel NBD driver cannot
450 * call for a reread of the partition table
451 * in the handling of the NBD_DO_IT ioctl().
452 * Therefore, this is done in the first open()
453 * of the device. We therefore make sure that
454 * the device is opened at least once after the
455 * connection was made. This has to be done in a
456 * separate process, since the NBD_DO_IT ioctl()
457 * does not return until the NBD device has
460 while(check_conn(nbddev, 0)) {
463 open(nbddev, O_RDONLY);
468 if (ioctl(nbd, NBD_DO_IT) < 0) {
469 fprintf(stderr, "Kernel call returned: %m");
471 /* The user probably did 'nbd-client -d' on us.
479 fprintf(stderr, " Reconnecting\n");
480 close(sock); close(nbd);
481 sock = opennet(hostname, port, sdp);
482 nbd = open(nbddev, O_RDWR);
483 negotiate(sock, &new_size, &new_flags, name);
484 if (size64 != new_size) {
485 err("Size of the device changed. Bye");
487 setsizes(nbd, size64, blocksize,
490 set_timeout(nbd, timeout);
491 finish_sock(sock,nbd,swap);
495 /* We're on 2.4. It's not clearly defined what exactly
496 * happened at this point. Probably best to quit, now
498 fprintf(stderr, "Kernel call returned.");
502 printf("Closing: que, ");
503 ioctl(nbd, NBD_CLEAR_QUE);
505 ioctl(nbd, NBD_CLEAR_SOCK);