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