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