Whitespace fixes
[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
39 #ifndef __GNUC__
40 #error I need GCC to work
41 #endif
42
43 #include <linux/ioctl.h>
44 #define MY_NAME "nbd_client"
45 #include "cliserv.h"
46
47 int check_conn(char* devname, int do_print) {
48         char buf[256];
49         char* p;
50         int fd;
51         int len;
52
53         if(!strncmp(devname, "/dev/", 5)) {
54                 devname+=5;
55         }
56         if((p=strchr(devname, 'p'))) {
57                 /* We can't do checks on partitions. */
58                 *p='\0';
59         }
60         snprintf(buf, 256, "/sys/block/%s/pid", devname);
61         if((fd=open(buf, O_RDONLY))<0) {
62                 if(errno==ENOENT) {
63                         return 1;
64                 } else {
65                         return 2;
66                 }
67         }
68         len=read(fd, buf, 256);
69         buf[len-1]='\0';
70         if(do_print) printf("%s\n", buf);
71         return 0;
72 }
73
74 int opennet(char *name, int port, int sdp) {
75         int sock;
76         char portstr[6];
77         struct addrinfo hints;
78         struct addrinfo *ai = NULL;
79         struct addrinfo *rp = NULL;
80         int e;
81
82         snprintf(portstr, sizeof(portstr), "%d", port);
83
84         memset(&hints,'\0',sizeof(hints));
85         hints.ai_family = AF_UNSPEC;
86         hints.ai_socktype = SOCK_STREAM;
87         hints.ai_flags = AI_ADDRCONFIG | AI_NUMERICSERV;
88         hints.ai_protocol = IPPROTO_TCP;
89
90         e = getaddrinfo(name, portstr, &hints, &ai);
91
92         if(e != 0) {
93                 fprintf(stderr, "getaddrinfo failed: %s\n", gai_strerror(e));
94                 freeaddrinfo(ai);
95                 exit(EXIT_FAILURE);
96         }
97
98         if(sdp) {
99 #ifdef WITH_SDP
100                 if (ai->ai_family == AF_INET)
101                         ai->ai_family = AF_INET_SDP;
102                 else (ai->ai_family == AF_INET6)
103                         ai->ai_family = AF_INET6_SDP;
104 #else
105                 err("Can't do SDP: I was not compiled with SDP support!");
106 #endif
107         }
108
109         for(rp = ai; rp != NULL; rp = rp->ai_next) {
110                 sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
111
112                 if(sock == -1)
113                         continue;       /* error */
114
115                 if(connect(sock, rp->ai_addr, rp->ai_addrlen) != -1)
116                         break;          /* success */
117         }
118
119         if (rp == NULL)
120                 err("Socket failed: %m");
121
122         setmysockopt(sock);
123
124         freeaddrinfo(ai);
125         return sock;
126 }
127
128 void negotiate(int sock, u64 *rsize64, u32 *flags) {
129         u64 magic, size64;
130         char buf[256] = "\0\0\0\0\0\0\0\0\0";
131
132         printf("Negotiation: ");
133         if (read(sock, buf, 8) < 0)
134                 err("Failed/1: %m");
135         if (strlen(buf)==0)
136                 err("Server closed connection");
137         if (strcmp(buf, INIT_PASSWD))
138                 err("INIT_PASSWD bad");
139         printf(".");
140         if (read(sock, &magic, sizeof(magic)) < 0)
141                 err("Failed/2: %m");
142         magic = ntohll(magic);
143         if (magic != cliserv_magic)
144                 err("Not enough cliserv_magic");
145         printf(".");
146
147         if (read(sock, &size64, sizeof(size64)) < 0)
148                 err("Failed/3: %m\n");
149         size64 = ntohll(size64);
150
151 #ifdef NBD_SET_SIZE_BLOCKS
152         if ((size64>>10) > (~0UL >> 1)) {
153                 printf("size = %luMB", (unsigned long)(size64>>20));
154                 err("Exported device is too big for me. Get 64-bit machine :-(\n");
155         } else
156                 printf("size = %luKB", (unsigned long)(size64>>10));
157 #else
158         if (size64 > (~0UL >> 1)) {
159                 printf("size = %luKB", (unsigned long)(size64>>10));
160                 err("Exported device is too big. Get 64-bit machine or newer kernel :-(\n");
161         } else
162                 printf("size = %lu", (unsigned long)(size64));
163 #endif
164
165         if (read(sock, flags, sizeof(*flags)) < 0)
166                 err("Failed/4: %m\n");
167         *flags = ntohl(*flags);
168
169         if (read(sock, &buf, 124) < 0)
170                 err("Failed/5: %m\n");
171         printf("\n");
172
173         *rsize64 = size64;
174 }
175
176 void setsizes(int nbd, u64 size64, int blocksize, u32 flags) {
177         unsigned long size;
178         int read_only = (flags & NBD_FLAG_READ_ONLY) ? 1 : 0;
179
180 #ifdef NBD_SET_SIZE_BLOCKS
181         if (size64/blocksize > (~0UL >> 1))
182                 err("Device too large.\n");
183         else {
184                 int er;
185                 if (ioctl(nbd, NBD_SET_BLKSIZE, (unsigned long)blocksize) < 0)
186                         err("Ioctl/1.1a failed: %m\n");
187                 size = (unsigned long)(size64/blocksize);
188                 if ((er = ioctl(nbd, NBD_SET_SIZE_BLOCKS, size)) < 0)
189                         err("Ioctl/1.1b failed: %m\n");
190                 fprintf(stderr, "bs=%d, sz=%lu\n", blocksize, size);
191         }
192 #else
193         if (size64 > (~0UL >> 1)) {
194                 err("Device too large.\n");
195         } else {
196                 size = (unsigned long)size64;
197                 if (ioctl(nbd, NBD_SET_SIZE, size) < 0)
198                         err("Ioctl NBD_SET_SIZE failed: %m\n");
199         }
200 #endif
201
202         ioctl(nbd, NBD_CLEAR_SOCK);
203
204         if (ioctl(nbd, BLKROSET, (unsigned long) &read_only) < 0)
205                 err("Unable to set read-only attribute for device");
206 }
207
208 void set_timeout(int nbd, int timeout) {
209         if (timeout) {
210 #ifdef NBD_SET_TIMEOUT
211                 if (ioctl(nbd, NBD_SET_TIMEOUT, (unsigned long)timeout) < 0)
212                         err("Ioctl NBD_SET_TIMEOUT failed: %m\n");
213                 fprintf(stderr, "timeout=%d\n", timeout);
214 #else
215                 err("Ioctl NBD_SET_TIMEOUT cannot be called when compiled on a system that does not support it\n");
216 #endif
217         }
218 }
219
220 void finish_sock(int sock, int nbd, int swap) {
221         if (ioctl(nbd, NBD_SET_SOCK, sock) < 0)
222                 err("Ioctl NBD_SET_SOCK failed: %m\n");
223
224         if (swap)
225                 mlockall(MCL_CURRENT | MCL_FUTURE);
226 }
227
228 void usage(void) {
229         fprintf(stderr, "nbd-client version %s\n", PACKAGE_VERSION);
230         fprintf(stderr, "Usage: nbd-client [bs=blocksize] [timeout=sec] host port nbd_device [-swap] [-sdp] [-persist] [-nofork]\n");
231         fprintf(stderr, "Or   : nbd-client -d nbd_device\n");
232         fprintf(stderr, "Or   : nbd-client -c nbd_device\n");
233         fprintf(stderr, "Default value for blocksize is 1024 (recommended for ethernet)\n");
234         fprintf(stderr, "Allowed values for blocksize are 512,1024,2048,4096\n"); /* will be checked in kernel :) */
235         fprintf(stderr, "Note, that kernel 2.4.2 and older ones do not work correctly with\n");
236         fprintf(stderr, "blocksizes other than 1024 without patches\n");
237 }
238
239 void disconnect(char* device) {
240         int nbd = open(device, O_RDWR);
241
242         if (nbd < 0)
243                 err("Cannot open NBD: %m\nPlease ensure the 'nbd' module is loaded.");
244         printf("Disconnecting: que, ");
245         if (ioctl(nbd, NBD_CLEAR_QUE)< 0)
246                 err("Ioctl failed: %m\n");
247         printf("disconnect, ");
248 #ifdef NBD_DISCONNECT
249         if (ioctl(nbd, NBD_DISCONNECT)<0)
250                 err("Ioctl failed: %m\n");
251         printf("sock, ");
252 #else
253         fprintf(stderr, "Can't disconnect: I was not compiled with disconnect support!\n" );
254         exit(1);
255 #endif
256         if (ioctl(nbd, NBD_CLEAR_SOCK)<0)
257                 err("Ioctl failed: %m\n");
258         printf("done\n");
259 }
260
261 int main(int argc, char *argv[]) {
262         int port=0;
263         int sock, nbd;
264         int blocksize=1024;
265         char *hostname=NULL;
266         char *nbddev=NULL;
267         int swap=0;
268         int cont=0;
269         int timeout=0;
270         int sdp=0;
271         int nofork=0;
272         u64 size64;
273         u32 flags;
274         int i, c;
275         int nonspecial=0;
276         struct option long_options[] = {
277                 { "block-size", required_argument, NULL, 'b' },
278                 { "check", required_argument, NULL, 'c' },
279                 { "disconnect", required_argument, NULL, 'd' },
280                 { "help", no_argument, NULL, 'h' },
281                 { "nofork", no_argument, NULL, 'n' },
282                 { "persist", no_argument, NULL, 'p' },
283                 { "sdp", no_argument, NULL, 'S' },
284                 { "swap", no_argument, NULL, 's' },
285                 { "timeout", required_argument, NULL, 't' },
286         };
287
288         logging();
289
290         while((c=getopt_long_only(argc, argv, "-b:c:d:hnpSst:", long_options, NULL))>=0) {
291                 switch(c) {
292                 case 1:
293                         // non-option argument
294                         if(strchr(optarg, '=')) {
295                                 // old-style 'bs=' or 'timeout='
296                                 // argument
297                                 fprintf(stderr, "WARNING: old-style command-line argument encountered. This is deprecated.\n");
298                                 if(!strncmp(optarg, "bs=", 3)) {
299                                         optarg+=3;
300                                         goto blocksize;
301                                 }
302                                 if(!strncmp(optarg, "timeout=", 8)) {
303                                         optarg+=8;
304                                         goto timeout;
305                                 }
306                                 fprintf(stderr, "ERROR: unknown option %s encountered\n", optarg);
307                                 exit(EXIT_FAILURE);
308                         }
309                         switch(nonspecial++) {
310                                 case 0:
311                                         // host
312                                         hostname=optarg;
313                                         break;
314                                 case 1:
315                                         // port
316                                         port = strtol(optarg, NULL, 0);
317                                         break;
318                                 case 2:
319                                         // device
320                                         nbddev = optarg;
321                                         break;
322                                 default:
323                                         fprintf(stderr, "ERROR: too many non-option arguments specified\n");
324                                         exit(EXIT_FAILURE);
325                         }
326                         break;
327                 case 'b':
328                       blocksize:
329                         blocksize=(int)strtol(optarg, NULL, 0);
330                         break;
331                 case 'c':
332                         check_conn(optarg, 1);
333                         exit(EXIT_SUCCESS);
334                 case 'd':
335                         disconnect(optarg);
336                         exit(EXIT_SUCCESS);
337                 case 'h':
338                         usage();
339                         exit(EXIT_SUCCESS);
340                 case 'n':
341                         nofork=1;
342                         break;
343                 case 'p':
344                         cont=1;
345                         break;
346                 case 's':
347                         swap=1;
348                         break;
349                 case 'S':
350                         sdp=1;
351                         break;
352                 case 't':
353                       timeout:
354                         timeout=strtol(optarg, NULL, 0);
355                         break;
356                 default:
357                         fprintf(stderr, "E: option eaten by 42 mice\n");
358                         exit(EXIT_FAILURE);
359                 }
360         }
361
362         if(!port || !hostname || !nbddev) {
363                 usage();
364                 exit(EXIT_FAILURE);
365         }
366
367         nbd = open(nbddev, O_RDWR);
368         if (nbd < 0)
369           err("Cannot open NBD: %m\nPlease ensure the 'nbd' module is loaded.");
370         ++argv; --argc; /* skip device */
371
372         sock = opennet(hostname, port, sdp);
373
374         negotiate(sock, &size64, &flags);
375         setsizes(nbd, size64, blocksize, flags);
376         set_timeout(nbd, timeout);
377         finish_sock(sock, nbd, swap);
378
379         /* Go daemon */
380         
381 #ifndef NOFORK
382         if(!nofork) daemon(0,0);
383 #endif
384         do {
385 #ifndef NOFORK
386                 if (fork()) {
387                         /* Due to a race, the kernel NBD driver cannot
388                          * call for a reread of the partition table
389                          * in the handling of the NBD_DO_IT ioctl().
390                          * Therefore, this is done in the first open()
391                          * of the device. We therefore make sure that
392                          * the device is opened at least once after the
393                          * connection was made. This has to be done in a
394                          * separate process, since the NBD_DO_IT ioctl()
395                          * does not return until the NBD device has
396                          * disconnected.
397                          */
398                         while(check_conn(nbddev, 0)) {
399                                 sleep(1);
400                         }
401                         open(nbddev, O_RDONLY);
402                         exit(0);
403                 }
404 #endif
405
406                 if (ioctl(nbd, NBD_DO_IT) < 0) {
407                         fprintf(stderr, "Kernel call returned: %m");
408                         if(errno==EBADR) {
409                                 /* The user probably did 'nbd-client -d' on us.
410                                  * quit */
411                                 cont=0;
412                         } else {
413                                 if(cont) {
414                                         u64 new_size;
415                                         u32 new_flags;
416
417                                         fprintf(stderr, " Reconnecting\n");
418                                         close(sock); close(nbd);
419                                         sock = opennet(hostname, port, sdp);
420                                         nbd = open(nbddev, O_RDWR);
421                                         negotiate(sock, &new_size, &new_flags);
422                                         if (size64 != new_size) {
423                                                 err("Size of the device changed. Bye");
424                                         }
425                                         setsizes(nbd, size64, blocksize,
426                                                                 new_flags);
427
428                                         set_timeout(nbd, timeout);
429                                         finish_sock(sock,nbd,swap);
430                                 }
431                         }
432                 } else {
433                         /* We're on 2.4. It's not clearly defined what exactly
434                          * happened at this point. Probably best to quit, now
435                          */
436                         fprintf(stderr, "Kernel call returned.");
437                         cont=0;
438                 }
439         } while(cont);
440         printf("Closing: que, ");
441         ioctl(nbd, NBD_CLEAR_QUE);
442         printf("sock, ");
443         ioctl(nbd, NBD_CLEAR_SOCK);
444         printf("done\n");
445         return 0;
446 }