fix build with non-gcc compiler
[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 #include <linux/ioctl.h>
41 #define MY_NAME "nbd_client"
42 #include "cliserv.h"
43
44 int check_conn(char* devname, int do_print) {
45         char buf[256];
46         char* p;
47         int fd;
48         int len;
49
50         if(!strncmp(devname, "/dev/", 5)) {
51                 devname+=5;
52         }
53         if((p=strchr(devname, 'p'))) {
54                 /* We can't do checks on partitions. */
55                 *p='\0';
56         }
57         snprintf(buf, 256, "/sys/block/%s/pid", devname);
58         if((fd=open(buf, O_RDONLY))<0) {
59                 if(errno==ENOENT) {
60                         return 1;
61                 } else {
62                         return 2;
63                 }
64         }
65         len=read(fd, buf, 256);
66         buf[len-1]='\0';
67         if(do_print) printf("%s\n", buf);
68         return 0;
69 }
70
71 int opennet(char *name, char* portstr, int sdp) {
72         int sock;
73         struct addrinfo hints;
74         struct addrinfo *ai = NULL;
75         struct addrinfo *rp = NULL;
76         int e;
77
78         memset(&hints,'\0',sizeof(hints));
79         hints.ai_family = AF_UNSPEC;
80         hints.ai_socktype = SOCK_STREAM;
81         hints.ai_flags = AI_ADDRCONFIG | AI_NUMERICSERV;
82         hints.ai_protocol = IPPROTO_TCP;
83
84         e = getaddrinfo(name, portstr, &hints, &ai);
85
86         if(e != 0) {
87                 fprintf(stderr, "getaddrinfo failed: %s\n", gai_strerror(e));
88                 freeaddrinfo(ai);
89                 exit(EXIT_FAILURE);
90         }
91
92         if(sdp) {
93 #ifdef WITH_SDP
94                 if (ai->ai_family == AF_INET)
95                         ai->ai_family = AF_INET_SDP;
96                 else (ai->ai_family == AF_INET6)
97                         ai->ai_family = AF_INET6_SDP;
98 #else
99                 err("Can't do SDP: I was not compiled with SDP support!");
100 #endif
101         }
102
103         for(rp = ai; rp != NULL; rp = rp->ai_next) {
104                 sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
105
106                 if(sock == -1)
107                         continue;       /* error */
108
109                 if(connect(sock, rp->ai_addr, rp->ai_addrlen) != -1)
110                         break;          /* success */
111         }
112
113         if (rp == NULL)
114                 err("Socket failed: %m");
115
116         setmysockopt(sock);
117
118         freeaddrinfo(ai);
119         return sock;
120 }
121
122 void negotiate(int sock, u64 *rsize64, u32 *flags, char* name) {
123         u64 magic, size64;
124         uint16_t tmp;
125         char buf[256] = "\0\0\0\0\0\0\0\0\0";
126
127         printf("Negotiation: ");
128         if (read(sock, buf, 8) < 0)
129                 err("Failed/1: %m");
130         if (strlen(buf)==0)
131                 err("Server closed connection");
132         if (strcmp(buf, INIT_PASSWD))
133                 err("INIT_PASSWD bad");
134         printf(".");
135         if (read(sock, &magic, sizeof(magic)) < 0)
136                 err("Failed/2: %m");
137         magic = ntohll(magic);
138         if(name) {
139                 uint32_t opt;
140                 uint32_t namesize;
141                 uint32_t reserved = 0;
142
143                 if (magic != opts_magic)
144                         err("Not enough opts_magic");
145                 printf(".");
146                 if(read(sock, &tmp, sizeof(uint16_t)) < 0) {
147                         err("Failed reading flags: %m");
148                 }
149                 *flags = ((u32)ntohs(tmp)) << 16;
150
151                 /* reserved for future use*/
152                 write(sock, &reserved, sizeof(reserved));
153
154                 /* Write the export name that we're after */
155                 magic = ntohll(opts_magic);
156                 write(sock, &magic, sizeof(magic));
157                 opt = ntohl(NBD_OPT_EXPORT_NAME);
158                 write(sock, &opt, sizeof(opt));
159                 namesize = (u32)strlen(name);
160                 namesize = ntohl(namesize);
161                 write(sock, &namesize, sizeof(namesize));
162                 write(sock, name, strlen(name));
163         } else {
164                 if (magic != cliserv_magic)
165                         err("Not enough cliserv_magic");
166                 printf(".");
167         }
168
169         if (read(sock, &size64, sizeof(size64)) < 0)
170                 err("Failed/3: %m\n");
171         size64 = ntohll(size64);
172
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");
177         } else
178                 printf("size = %luKB", (unsigned long)(size64>>10));
179 #else
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");
183         } else
184                 printf("size = %lu", (unsigned long)(size64));
185 #endif
186
187         if(!name) {
188                 if (read(sock, flags, sizeof(*flags)) < 0)
189                         err("Failed/4: %m\n");
190                 *flags = ntohl(*flags);
191         } else {
192                 if(read(sock, &tmp, sizeof(tmp)) < 0)
193                         err("Failed/4: %m\n");
194                 *flags |= (uint32_t)ntohs(tmp);
195         }
196
197         if (read(sock, &buf, 124) < 0)
198                 err("Failed/5: %m\n");
199         printf("\n");
200
201         *rsize64 = size64;
202 }
203
204 void setsizes(int nbd, u64 size64, int blocksize, u32 flags) {
205         unsigned long size;
206         int read_only = (flags & NBD_FLAG_READ_ONLY) ? 1 : 0;
207
208 #ifdef NBD_SET_SIZE_BLOCKS
209         if (size64/blocksize > (~0UL >> 1))
210                 err("Device too large.\n");
211         else {
212                 int er;
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);
219         }
220 #else
221         if (size64 > (~0UL >> 1)) {
222                 err("Device too large.\n");
223         } else {
224                 size = (unsigned long)size64;
225                 if (ioctl(nbd, NBD_SET_SIZE, size) < 0)
226                         err("Ioctl NBD_SET_SIZE failed: %m\n");
227         }
228 #endif
229
230         ioctl(nbd, NBD_CLEAR_SOCK);
231
232         if (ioctl(nbd, BLKROSET, (unsigned long) &read_only) < 0)
233                 err("Unable to set read-only attribute for device");
234 }
235
236 void set_timeout(int nbd, int timeout) {
237         if (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);
242 #else
243                 err("Ioctl NBD_SET_TIMEOUT cannot be called when compiled on a system that does not support it\n");
244 #endif
245         }
246 }
247
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");
251
252         if (swap)
253                 mlockall(MCL_CURRENT | MCL_FUTURE);
254 }
255
256 void usage(char* errmsg, ...) {
257         if(errmsg) {
258                 char tmp[256];
259                 va_list ap;
260                 va_start(ap, errmsg);
261                 snprintf(tmp, 256, "ERROR: %s\n\n", errmsg);
262                 vfprintf(stderr, errmsg, ap);
263                 va_end(ap);
264         } else {
265                 fprintf(stderr, "nbd-client version %s\n", PACKAGE_VERSION);
266         }
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] [-name|-N name]\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");
275 }
276
277 void disconnect(char* device) {
278         int nbd = open(device, O_RDWR);
279
280         if (nbd < 0)
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");
289         printf("sock, ");
290 #else
291         fprintf(stderr, "Can't disconnect: I was not compiled with disconnect support!\n" );
292         exit(1);
293 #endif
294         if (ioctl(nbd, NBD_CLEAR_SOCK)<0)
295                 err("Ioctl failed: %m\n");
296         printf("done\n");
297 }
298
299 int main(int argc, char *argv[]) {
300         char* port=NULL;
301         int sock, nbd;
302         int blocksize=1024;
303         char *hostname=NULL;
304         char *nbddev=NULL;
305         int swap=0;
306         int cont=0;
307         int timeout=0;
308         int sdp=0;
309         int nofork=0;
310         u64 size64;
311         u32 flags;
312         int c;
313         int nonspecial=0;
314         char* name=NULL;
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' },
326                 { 0, 0, 0, 0 }, 
327         };
328
329         logging();
330
331         while((c=getopt_long_only(argc, argv, "-b:c:d:hnN:pSst:", long_options, NULL))>=0) {
332                 switch(c) {
333                 case 1:
334                         // non-option argument
335                         if(strchr(optarg, '=')) {
336                                 // old-style 'bs=' or 'timeout='
337                                 // argument
338                                 fprintf(stderr, "WARNING: old-style command-line argument encountered. This is deprecated.\n");
339                                 if(!strncmp(optarg, "bs=", 3)) {
340                                         optarg+=3;
341                                         goto blocksize;
342                                 }
343                                 if(!strncmp(optarg, "timeout=", 8)) {
344                                         optarg+=8;
345                                         goto timeout;
346                                 }
347                                 usage("unknown option %s encountered", optarg);
348                                 exit(EXIT_FAILURE);
349                         }
350                         switch(nonspecial++) {
351                                 case 0:
352                                         // host
353                                         hostname=optarg;
354                                         break;
355                                 case 1:
356                                         // port
357                                         if(!strtol(optarg, NULL, 0)) {
358                                                 // not parseable as a number, assume it's the device and we have a name
359                                                 nbddev = optarg;
360                                                 nonspecial++;
361                                         } else {
362                                                 port = optarg;
363                                                 if(name) {
364                                                         usage("port and name specified at the same time. This is not supported.");
365                                                         exit(EXIT_FAILURE);
366                                                 }
367                                         }
368                                         break;
369                                 case 2:
370                                         // device
371                                         nbddev = optarg;
372                                         break;
373                                 default:
374                                         usage("too many non-option arguments specified");
375                                         exit(EXIT_FAILURE);
376                         }
377                         break;
378                 case 'b':
379                       blocksize:
380                         blocksize=(int)strtol(optarg, NULL, 0);
381                         break;
382                 case 'c':
383                         return check_conn(optarg, 1);
384                 case 'd':
385                         disconnect(optarg);
386                         exit(EXIT_SUCCESS);
387                 case 'h':
388                         usage(NULL);
389                         exit(EXIT_SUCCESS);
390                 case 'n':
391                         nofork=1;
392                         break;
393                 case 'N':
394                         name=optarg;
395                         if(port) {
396                                 usage("port and name specified at the same time. This is not supported.");
397                                 exit(EXIT_FAILURE);
398                         }
399                         port = NBD_DEFAULT_PORT;
400                         break;
401                 case 'p':
402                         cont=1;
403                         break;
404                 case 's':
405                         swap=1;
406                         break;
407                 case 'S':
408                         sdp=1;
409                         break;
410                 case 't':
411                       timeout:
412                         timeout=strtol(optarg, NULL, 0);
413                         break;
414                 default:
415                         fprintf(stderr, "E: option eaten by 42 mice\n");
416                         exit(EXIT_FAILURE);
417                 }
418         }
419
420         if((!port && !name) || !hostname || !nbddev) {
421                 usage("not enough information specified");
422                 exit(EXIT_FAILURE);
423         }
424
425         nbd = open(nbddev, O_RDWR);
426         if (nbd < 0)
427           err("Cannot open NBD: %m\nPlease ensure the 'nbd' module is loaded.");
428         ++argv; --argc; /* skip device */
429
430         sock = opennet(hostname, port, sdp);
431
432         negotiate(sock, &size64, &flags, name);
433         setsizes(nbd, size64, blocksize, flags);
434         set_timeout(nbd, timeout);
435         finish_sock(sock, nbd, swap);
436
437         /* Go daemon */
438         
439 #ifndef NOFORK
440         if(!nofork) daemon(0,0);
441 #endif
442         do {
443 #ifndef NOFORK
444                 if (fork()) {
445                         /* Due to a race, the kernel NBD driver cannot
446                          * call for a reread of the partition table
447                          * in the handling of the NBD_DO_IT ioctl().
448                          * Therefore, this is done in the first open()
449                          * of the device. We therefore make sure that
450                          * the device is opened at least once after the
451                          * connection was made. This has to be done in a
452                          * separate process, since the NBD_DO_IT ioctl()
453                          * does not return until the NBD device has
454                          * disconnected.
455                          */
456                         while(check_conn(nbddev, 0)) {
457                                 sleep(1);
458                         }
459                         open(nbddev, O_RDONLY);
460                         exit(0);
461                 }
462 #endif
463
464                 if (ioctl(nbd, NBD_DO_IT) < 0) {
465                         fprintf(stderr, "Kernel call returned: %m");
466                         if(errno==EBADR) {
467                                 /* The user probably did 'nbd-client -d' on us.
468                                  * quit */
469                                 cont=0;
470                         } else {
471                                 if(cont) {
472                                         u64 new_size;
473                                         u32 new_flags;
474
475                                         fprintf(stderr, " Reconnecting\n");
476                                         close(sock); close(nbd);
477                                         sock = opennet(hostname, port, sdp);
478                                         nbd = open(nbddev, O_RDWR);
479                                         negotiate(sock, &new_size, &new_flags, name);
480                                         if (size64 != new_size) {
481                                                 err("Size of the device changed. Bye");
482                                         }
483                                         setsizes(nbd, size64, blocksize,
484                                                                 new_flags);
485
486                                         set_timeout(nbd, timeout);
487                                         finish_sock(sock,nbd,swap);
488                                 }
489                         }
490                 } else {
491                         /* We're on 2.4. It's not clearly defined what exactly
492                          * happened at this point. Probably best to quit, now
493                          */
494                         fprintf(stderr, "Kernel call returned.");
495                         cont=0;
496                 }
497         } while(cont);
498         printf("Closing: que, ");
499         ioctl(nbd, NBD_CLEAR_QUE);
500         printf("sock, ");
501         ioctl(nbd, NBD_CLEAR_SOCK);
502         printf("done\n");
503         return 0;
504 }