ba244ae48954f69a956b3ac62d4d4f6e3e368743
[nbd.git] / nbd-client.c
1 /*
2  * Open connection for network block device
3  *
4  * Copyright 1997,1998 Pavel Machek, distribute under GPL
5  *  <pavel@atrey.karlin.mff.cuni.cz>
6  *
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>
18  */
19
20 #include "config.h"
21 #include "lfs.h"
22
23 #include <sys/ioctl.h>
24 #include <sys/socket.h>
25 #include <sys/types.h>
26 #include <unistd.h>
27 #include <netinet/tcp.h>
28 #include <netinet/in.h>
29 #include <netdb.h>
30 #include <stdio.h>
31 #include <fcntl.h>
32 #include <syslog.h>
33 #include <stdlib.h>
34 #include <sys/mount.h>
35 #include <sys/mman.h>
36 #include <errno.h>
37 #include <getopt.h>
38 #include <stdarg.h>
39
40 #ifndef __GNUC__
41 #error I need GCC to work
42 #endif
43
44 #include <linux/ioctl.h>
45 #define MY_NAME "nbd_client"
46 #include "cliserv.h"
47
48 int check_conn(char* devname, int do_print) {
49         char buf[256];
50         char* p;
51         int fd;
52         int len;
53
54         if(!strncmp(devname, "/dev/", 5)) {
55                 devname+=5;
56         }
57         if((p=strchr(devname, 'p'))) {
58                 /* We can't do checks on partitions. */
59                 *p='\0';
60         }
61         snprintf(buf, 256, "/sys/block/%s/pid", devname);
62         if((fd=open(buf, O_RDONLY))<0) {
63                 if(errno==ENOENT) {
64                         return 1;
65                 } else {
66                         return 2;
67                 }
68         }
69         len=read(fd, buf, 256);
70         buf[len-1]='\0';
71         if(do_print) printf("%s\n", buf);
72         return 0;
73 }
74
75 int opennet(char *name, char* portstr, int sdp) {
76         int sock;
77         struct addrinfo hints;
78         struct addrinfo *ai = NULL;
79         struct addrinfo *rp = NULL;
80         int e;
81
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;
87
88         e = getaddrinfo(name, portstr, &hints, &ai);
89
90         if(e != 0) {
91                 fprintf(stderr, "getaddrinfo failed: %s\n", gai_strerror(e));
92                 freeaddrinfo(ai);
93                 exit(EXIT_FAILURE);
94         }
95
96         if(sdp) {
97 #ifdef WITH_SDP
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;
102 #else
103                 err("Can't do SDP: I was not compiled with SDP support!");
104 #endif
105         }
106
107         for(rp = ai; rp != NULL; rp = rp->ai_next) {
108                 sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
109
110                 if(sock == -1)
111                         continue;       /* error */
112
113                 if(connect(sock, rp->ai_addr, rp->ai_addrlen) != -1)
114                         break;          /* success */
115         }
116
117         if (rp == NULL)
118                 err("Socket failed: %m");
119
120         setmysockopt(sock);
121
122         freeaddrinfo(ai);
123         return sock;
124 }
125
126 void negotiate(int sock, u64 *rsize64, u32 *flags, char* name) {
127         u64 magic, size64;
128         uint16_t tmp;
129         char buf[256] = "\0\0\0\0\0\0\0\0\0";
130
131         printf("Negotiation: ");
132         if (read(sock, buf, 8) < 0)
133                 err("Failed/1: %m");
134         if (strlen(buf)==0)
135                 err("Server closed connection");
136         if (strcmp(buf, INIT_PASSWD))
137                 err("INIT_PASSWD bad");
138         printf(".");
139         if (read(sock, &magic, sizeof(magic)) < 0)
140                 err("Failed/2: %m");
141         magic = ntohll(magic);
142         if(name) {
143                 uint32_t opt;
144                 uint32_t namesize;
145                 uint32_t reserved = 0;
146
147                 if (magic != opts_magic)
148                         err("Not enough opts_magic");
149                 printf(".");
150                 if(read(sock, &tmp, sizeof(uint16_t)) < 0) {
151                         err("Failed reading flags: %m");
152                 }
153                 *flags = ((u32)ntohs(tmp)) << 16;
154
155                 /* reserved for future use*/
156                 write(sock, &reserved, sizeof(reserved));
157
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));
167         } else {
168                 if (magic != cliserv_magic)
169                         err("Not enough cliserv_magic");
170                 printf(".");
171         }
172
173         if (read(sock, &size64, sizeof(size64)) < 0)
174                 err("Failed/3: %m\n");
175         size64 = ntohll(size64);
176
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");
181         } else
182                 printf("size = %luKB", (unsigned long)(size64>>10));
183 #else
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");
187         } else
188                 printf("size = %lu", (unsigned long)(size64));
189 #endif
190
191         if(!name) {
192                 if (read(sock, flags, sizeof(*flags)) < 0)
193                         err("Failed/4: %m\n");
194                 *flags = ntohl(*flags);
195         } else {
196                 if(read(sock, &tmp, sizeof(tmp)) < 0)
197                         err("Failed/4: %m\n");
198                 *flags |= (uint32_t)ntohs(tmp);
199         }
200
201         if (read(sock, &buf, 124) < 0)
202                 err("Failed/5: %m\n");
203         printf("\n");
204
205         *rsize64 = size64;
206 }
207
208 void setsizes(int nbd, u64 size64, int blocksize, u32 flags) {
209         unsigned long size;
210         int read_only = (flags & NBD_FLAG_READ_ONLY) ? 1 : 0;
211
212 #ifdef NBD_SET_SIZE_BLOCKS
213         if (size64/blocksize > (~0UL >> 1))
214                 err("Device too large.\n");
215         else {
216                 int er;
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);
223         }
224 #else
225         if (size64 > (~0UL >> 1)) {
226                 err("Device too large.\n");
227         } else {
228                 size = (unsigned long)size64;
229                 if (ioctl(nbd, NBD_SET_SIZE, size) < 0)
230                         err("Ioctl NBD_SET_SIZE failed: %m\n");
231         }
232 #endif
233
234         ioctl(nbd, NBD_CLEAR_SOCK);
235
236         if (ioctl(nbd, BLKROSET, (unsigned long) &read_only) < 0)
237                 err("Unable to set read-only attribute for device");
238 }
239
240 void set_timeout(int nbd, int timeout) {
241         if (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);
246 #else
247                 err("Ioctl NBD_SET_TIMEOUT cannot be called when compiled on a system that does not support it\n");
248 #endif
249         }
250 }
251
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");
255
256         if (swap)
257                 mlockall(MCL_CURRENT | MCL_FUTURE);
258 }
259
260 void usage(char* errmsg, ...) {
261         if(errmsg) {
262                 char tmp[256];
263                 va_list ap;
264                 va_start(ap, errmsg);
265                 snprintf(tmp, 256, "ERROR: %s\n\n", errmsg);
266                 vfprintf(stderr, errmsg, ap);
267                 va_end(ap);
268         } else {
269                 fprintf(stderr, "nbd-client version %s\n", PACKAGE_VERSION);
270         }
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");
279 }
280
281 void disconnect(char* device) {
282         int nbd = open(device, O_RDWR);
283
284         if (nbd < 0)
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");
293         printf("sock, ");
294 #else
295         fprintf(stderr, "Can't disconnect: I was not compiled with disconnect support!\n" );
296         exit(1);
297 #endif
298         if (ioctl(nbd, NBD_CLEAR_SOCK)<0)
299                 err("Ioctl failed: %m\n");
300         printf("done\n");
301 }
302
303 int main(int argc, char *argv[]) {
304         char* port=NULL;
305         int sock, nbd;
306         int blocksize=1024;
307         char *hostname=NULL;
308         char *nbddev=NULL;
309         int swap=0;
310         int cont=0;
311         int timeout=0;
312         int sdp=0;
313         int nofork=0;
314         u64 size64;
315         u32 flags;
316         int c;
317         int nonspecial=0;
318         char* name=NULL;
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' },
330                 { 0, 0, 0, 0 }, 
331         };
332
333         logging();
334
335         while((c=getopt_long_only(argc, argv, "-b:c:d:hnN:pSst:", long_options, NULL))>=0) {
336                 switch(c) {
337                 case 1:
338                         // non-option argument
339                         if(strchr(optarg, '=')) {
340                                 // old-style 'bs=' or 'timeout='
341                                 // argument
342                                 fprintf(stderr, "WARNING: old-style command-line argument encountered. This is deprecated.\n");
343                                 if(!strncmp(optarg, "bs=", 3)) {
344                                         optarg+=3;
345                                         goto blocksize;
346                                 }
347                                 if(!strncmp(optarg, "timeout=", 8)) {
348                                         optarg+=8;
349                                         goto timeout;
350                                 }
351                                 usage("unknown option %s encountered", optarg);
352                                 exit(EXIT_FAILURE);
353                         }
354                         switch(nonspecial++) {
355                                 case 0:
356                                         // host
357                                         hostname=optarg;
358                                         break;
359                                 case 1:
360                                         // port
361                                         if(!strtol(optarg, NULL, 0)) {
362                                                 // not parseable as a number, assume it's the device and we have a name
363                                                 nbddev = optarg;
364                                                 nonspecial++;
365                                         } else {
366                                                 port = optarg;
367                                                 if(name) {
368                                                         usage("port and name specified at the same time. This is not supported.");
369                                                         exit(EXIT_FAILURE);
370                                                 }
371                                         }
372                                         break;
373                                 case 2:
374                                         // device
375                                         nbddev = optarg;
376                                         break;
377                                 default:
378                                         usage("too many non-option arguments specified");
379                                         exit(EXIT_FAILURE);
380                         }
381                         break;
382                 case 'b':
383                       blocksize:
384                         blocksize=(int)strtol(optarg, NULL, 0);
385                         break;
386                 case 'c':
387                         return check_conn(optarg, 1);
388                 case 'd':
389                         disconnect(optarg);
390                         exit(EXIT_SUCCESS);
391                 case 'h':
392                         usage(NULL);
393                         exit(EXIT_SUCCESS);
394                 case 'n':
395                         nofork=1;
396                         break;
397                 case 'N':
398                         name=optarg;
399                         if(port) {
400                                 usage("port and name specified at the same time. This is not supported.");
401                                 exit(EXIT_FAILURE);
402                         }
403                         port = NBD_DEFAULT_PORT;
404                         break;
405                 case 'p':
406                         cont=1;
407                         break;
408                 case 's':
409                         swap=1;
410                         break;
411                 case 'S':
412                         sdp=1;
413                         break;
414                 case 't':
415                       timeout:
416                         timeout=strtol(optarg, NULL, 0);
417                         break;
418                 default:
419                         fprintf(stderr, "E: option eaten by 42 mice\n");
420                         exit(EXIT_FAILURE);
421                 }
422         }
423
424         if((!port && !name) || !hostname || !nbddev) {
425                 usage("not enough information specified");
426                 exit(EXIT_FAILURE);
427         }
428
429         nbd = open(nbddev, O_RDWR);
430         if (nbd < 0)
431           err("Cannot open NBD: %m\nPlease ensure the 'nbd' module is loaded.");
432         ++argv; --argc; /* skip device */
433
434         sock = opennet(hostname, port, sdp);
435
436         negotiate(sock, &size64, &flags, name);
437         setsizes(nbd, size64, blocksize, flags);
438         set_timeout(nbd, timeout);
439         finish_sock(sock, nbd, swap);
440
441         /* Go daemon */
442         
443 #ifndef NOFORK
444         if(!nofork) daemon(0,0);
445 #endif
446         do {
447 #ifndef NOFORK
448                 if (fork()) {
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
458                          * disconnected.
459                          */
460                         while(check_conn(nbddev, 0)) {
461                                 sleep(1);
462                         }
463                         open(nbddev, O_RDONLY);
464                         exit(0);
465                 }
466 #endif
467
468                 if (ioctl(nbd, NBD_DO_IT) < 0) {
469                         fprintf(stderr, "Kernel call returned: %m");
470                         if(errno==EBADR) {
471                                 /* The user probably did 'nbd-client -d' on us.
472                                  * quit */
473                                 cont=0;
474                         } else {
475                                 if(cont) {
476                                         u64 new_size;
477                                         u32 new_flags;
478
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");
486                                         }
487                                         setsizes(nbd, size64, blocksize,
488                                                                 new_flags);
489
490                                         set_timeout(nbd, timeout);
491                                         finish_sock(sock,nbd,swap);
492                                 }
493                         }
494                 } else {
495                         /* We're on 2.4. It's not clearly defined what exactly
496                          * happened at this point. Probably best to quit, now
497                          */
498                         fprintf(stderr, "Kernel call returned.");
499                         cont=0;
500                 }
501         } while(cont);
502         printf("Closing: que, ");
503         ioctl(nbd, NBD_CLEAR_QUE);
504         printf("sock, ");
505         ioctl(nbd, NBD_CLEAR_SOCK);
506         printf("done\n");
507         return 0;
508 }