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>
40 #include <linux/ioctl.h>
41 #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 if (write(sock, &reserved, sizeof(reserved)) < 0)
157 err("Failed/2.1: %m");
159 /* Write the export name that we're after */
160 magic = ntohll(opts_magic);
161 if (write(sock, &magic, sizeof(magic)) < 0)
162 err("Failed/2.2: %m");
163 opt = ntohl(NBD_OPT_EXPORT_NAME);
164 if (write(sock, &opt, sizeof(opt)) < 0)
165 err("Failed/2.3: %m");
166 namesize = (u32)strlen(name);
167 namesize = ntohl(namesize);
168 if (write(sock, &namesize, sizeof(namesize)) < 0)
169 err("Failed/2.4: %m");
170 if (write(sock, name, strlen(name)) < 0)
171 err("Failed/2.4: %m");
173 if (magic != cliserv_magic)
174 err("Not enough cliserv_magic");
178 if (read(sock, &size64, sizeof(size64)) < 0)
179 err("Failed/3: %m\n");
180 size64 = ntohll(size64);
182 #ifdef NBD_SET_SIZE_BLOCKS
183 if ((size64>>12) > (uint64_t)~0UL) {
184 printf("size = %luMB", (unsigned long)(size64>>20));
185 err("Exported device is too big for me. Get 64-bit machine :-(\n");
187 printf("size = %luMB", (unsigned long)(size64>>20));
189 if (size64 > (~0UL >> 1)) {
190 printf("size = %luKB", (unsigned long)(size64>>10));
191 err("Exported device is too big. Get 64-bit machine or newer kernel :-(\n");
193 printf("size = %lu", (unsigned long)(size64));
197 if (read(sock, flags, sizeof(*flags)) < 0)
198 err("Failed/4: %m\n");
199 *flags = ntohl(*flags);
201 if(read(sock, &tmp, sizeof(tmp)) < 0)
202 err("Failed/4: %m\n");
203 *flags |= (uint32_t)ntohs(tmp);
206 if (read(sock, &buf, 124) < 0)
207 err("Failed/5: %m\n");
213 void setsizes(int nbd, u64 size64, int blocksize, u32 flags) {
215 int read_only = (flags & NBD_FLAG_READ_ONLY) ? 1 : 0;
217 #ifdef NBD_SET_SIZE_BLOCKS
218 if (size64>>12 > (uint64_t)~0UL)
219 err("Device too large.\n");
222 if (ioctl(nbd, NBD_SET_BLKSIZE, 4096UL) < 0)
223 err("Ioctl/1.1a failed: %m\n");
224 size = (unsigned long)(size64>>12);
225 if ((er = ioctl(nbd, NBD_SET_SIZE_BLOCKS, size)) < 0)
226 err("Ioctl/1.1b failed: %m\n");
227 if (ioctl(nbd, NBD_SET_BLKSIZE, (unsigned long)blocksize) < 0)
228 err("Ioctl/1.1c failed: %m\n");
229 fprintf(stderr, "bs=%d, sz=%llu bytes\n", blocksize, 4096ULL*size);
232 if (size64 > (~0UL >> 1)) {
233 err("Device too large.\n");
235 size = (unsigned long)size64;
236 if (ioctl(nbd, NBD_SET_SIZE, size) < 0)
237 err("Ioctl NBD_SET_SIZE failed: %m\n");
241 ioctl(nbd, NBD_CLEAR_SOCK);
243 if (ioctl(nbd, BLKROSET, (unsigned long) &read_only) < 0)
244 err("Unable to set read-only attribute for device");
247 void set_timeout(int nbd, int timeout) {
249 #ifdef NBD_SET_TIMEOUT
250 if (ioctl(nbd, NBD_SET_TIMEOUT, (unsigned long)timeout) < 0)
251 err("Ioctl NBD_SET_TIMEOUT failed: %m\n");
252 fprintf(stderr, "timeout=%d\n", timeout);
254 err("Ioctl NBD_SET_TIMEOUT cannot be called when compiled on a system that does not support it\n");
259 void finish_sock(int sock, int nbd, int swap) {
260 if (ioctl(nbd, NBD_SET_SOCK, sock) < 0)
261 err("Ioctl NBD_SET_SOCK failed: %m\n");
264 mlockall(MCL_CURRENT | MCL_FUTURE);
267 void usage(char* errmsg, ...) {
271 va_start(ap, errmsg);
272 snprintf(tmp, 256, "ERROR: %s\n\n", errmsg);
273 vfprintf(stderr, errmsg, ap);
276 fprintf(stderr, "nbd-client version %s\n", PACKAGE_VERSION);
278 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");
279 fprintf(stderr, "Or : nbd-client -d nbd_device\n");
280 fprintf(stderr, "Or : nbd-client -c nbd_device\n");
281 fprintf(stderr, "Or : nbd-client -h|--help\n");
282 fprintf(stderr, "Default value for blocksize is 1024 (recommended for ethernet)\n");
283 fprintf(stderr, "Allowed values for blocksize are 512,1024,2048,4096\n"); /* will be checked in kernel :) */
284 fprintf(stderr, "Note, that kernel 2.4.2 and older ones do not work correctly with\n");
285 fprintf(stderr, "blocksizes other than 1024 without patches\n");
288 void disconnect(char* device) {
289 int nbd = open(device, O_RDWR);
292 err("Cannot open NBD: %m\nPlease ensure the 'nbd' module is loaded.");
293 printf("Disconnecting: que, ");
294 if (ioctl(nbd, NBD_CLEAR_QUE)< 0)
295 err("Ioctl failed: %m\n");
296 printf("disconnect, ");
297 #ifdef NBD_DISCONNECT
298 if (ioctl(nbd, NBD_DISCONNECT)<0)
299 err("Ioctl failed: %m\n");
302 fprintf(stderr, "Can't disconnect: I was not compiled with disconnect support!\n" );
305 if (ioctl(nbd, NBD_CLEAR_SOCK)<0)
306 err("Ioctl failed: %m\n");
310 int main(int argc, char *argv[]) {
326 struct option long_options[] = {
327 { "block-size", required_argument, NULL, 'b' },
328 { "check", required_argument, NULL, 'c' },
329 { "disconnect", required_argument, NULL, 'd' },
330 { "help", no_argument, NULL, 'h' },
331 { "name", required_argument, NULL, 'N' },
332 { "nofork", no_argument, NULL, 'n' },
333 { "persist", no_argument, NULL, 'p' },
334 { "sdp", no_argument, NULL, 'S' },
335 { "swap", no_argument, NULL, 's' },
336 { "timeout", required_argument, NULL, 't' },
342 while((c=getopt_long_only(argc, argv, "-b:c:d:hnN:pSst:", long_options, NULL))>=0) {
345 // non-option argument
346 if(strchr(optarg, '=')) {
347 // old-style 'bs=' or 'timeout='
349 fprintf(stderr, "WARNING: old-style command-line argument encountered. This is deprecated.\n");
350 if(!strncmp(optarg, "bs=", 3)) {
354 if(!strncmp(optarg, "timeout=", 8)) {
358 usage("unknown option %s encountered", optarg);
361 switch(nonspecial++) {
368 if(!strtol(optarg, NULL, 0)) {
369 // not parseable as a number, assume it's the device and we have a name
375 usage("port and name specified at the same time. This is not supported.");
385 usage("too many non-option arguments specified");
391 blocksize=(int)strtol(optarg, NULL, 0);
394 return check_conn(optarg, 1);
407 usage("port and name specified at the same time. This is not supported.");
410 port = NBD_DEFAULT_PORT;
423 timeout=strtol(optarg, NULL, 0);
426 fprintf(stderr, "E: option eaten by 42 mice\n");
431 if((!port && !name) || !hostname || !nbddev) {
432 usage("not enough information specified");
436 nbd = open(nbddev, O_RDWR);
438 err("Cannot open NBD: %m\nPlease ensure the 'nbd' module is loaded.");
439 ++argv; --argc; /* skip device */
441 sock = opennet(hostname, port, sdp);
443 negotiate(sock, &size64, &flags, name);
444 setsizes(nbd, size64, blocksize, flags);
445 set_timeout(nbd, timeout);
446 finish_sock(sock, nbd, swap);
453 err("Cannot detach from terminal");
459 /* Due to a race, the kernel NBD driver cannot
460 * call for a reread of the partition table
461 * in the handling of the NBD_DO_IT ioctl().
462 * Therefore, this is done in the first open()
463 * of the device. We therefore make sure that
464 * the device is opened at least once after the
465 * connection was made. This has to be done in a
466 * separate process, since the NBD_DO_IT ioctl()
467 * does not return until the NBD device has
470 while(check_conn(nbddev, 0)) {
473 open(nbddev, O_RDONLY);
478 if (ioctl(nbd, NBD_DO_IT) < 0) {
479 fprintf(stderr, "Kernel call returned: %m");
481 /* The user probably did 'nbd-client -d' on us.
489 fprintf(stderr, " Reconnecting\n");
490 close(sock); close(nbd);
491 sock = opennet(hostname, port, sdp);
492 nbd = open(nbddev, O_RDWR);
493 negotiate(sock, &new_size, &new_flags, name);
494 if (size64 != new_size) {
495 err("Size of the device changed. Bye");
497 setsizes(nbd, size64, blocksize,
500 set_timeout(nbd, timeout);
501 finish_sock(sock,nbd,swap);
505 /* We're on 2.4. It's not clearly defined what exactly
506 * happened at this point. Probably best to quit, now
508 fprintf(stderr, "Kernel call returned.");
512 printf("Closing: que, ");
513 ioctl(nbd, NBD_CLEAR_QUE);
515 ioctl(nbd, NBD_CLEAR_SOCK);