r21: Client and server version both set to 2.0 so they are now in step with each...
[nbd.git] / nbd-server.c
1 /*
2  * Network Block Device - server
3  *
4  * Copyright 1996-1998 Pavel Machek, distribute under GPL
5  *  <pavel@atrey.karlin.mff.cuni.cz>
6  * Copyright 2002 Anton Altaparmakov <aia21@cam.ac.uk>
7  *
8  * Version 1.0 - hopefully 64-bit-clean
9  * Version 1.1 - merging enhancements from Josh Parsons, <josh@coombs.anu.edu.au>
10  * Version 1.2 - autodetect size of block devices, thanx to Peter T. Breuer" <ptb@it.uc3m.es>
11  * Version 1.5 - can compile on Unix systems that don't have 64 bit integer
12  *      type, or don't have 64 bit file offsets by defining FS_32BIT
13  *      in compile options for nbd-server *only*. This can be done
14  *      with make FSCHOICE=-DFS_32BIT nbd-server. (I don't have the
15  *      original autoconf input file, or I would make it a configure
16  *      option.) Ken Yap <ken@nlc.net.au>.
17  * Version 1.6 - fix autodetection of block device size and really make 64 bit
18  *      clean on 32 bit machines. Anton Altaparmakov <aia21@cam.ac.uk>
19  * Version 2.0 - Version synchronised with client
20  */
21
22 #define VERSION "2.0"
23 #define GIGA (1*1024*1024*1024)
24
25 #include <sys/types.h>
26 #include <sys/socket.h>
27 #include <sys/stat.h>
28 #include <netinet/tcp.h>
29 #include <netinet/in.h>         /* sockaddr_in, htons, in_addr */
30 #include <netdb.h>              /* hostent, gethostby*, getservby* */
31 #include <syslog.h>
32 #include <unistd.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <fcntl.h>
37 #include <arpa/inet.h>
38 #include <strings.h>
39
40 #define _IO(a,b)
41 // #define ISSERVER
42 #define MY_NAME "nbd_server"
43
44 /* Authorization file should contain lines with IP addresses of 
45    clients authorized to use the server. If it does not exist,
46    access is permitted. */
47 #define AUTH_FILE "nbd_server.allow"
48
49 #include "cliserv.h"
50 #undef _IO
51 /* Deep magic: ioctl.h defines _IO macro (at least on linux) */
52
53
54 /* Debugging macros, now nothing goes to syslog unless you say ISSERVER */
55 #ifdef ISSERVER
56 #define msg2(a,b) syslog(a,b)
57 #define msg3(a,b,c) syslog(a,b,c)
58 #define msg4(a,b,c,d) syslog(a,b,c,d)
59 #else
60 #define msg2(a,b) do { fprintf(stderr,b) ; fputs("\n",stderr) ; } while(0) 
61 #define msg3(a,b,c) do { fprintf(stderr,b,c); fputs("\n",stderr) ; } while(0) 
62 #define msg4(a,b,c,d) do { fprintf(stderr,b,c,d); fputs("\n",stderr) ; } while(0)
63 #endif
64
65
66 #include <sys/ioctl.h>
67 #include <sys/mount.h>          /* For BLKGETSIZE */
68
69 #ifdef  FS_32BIT
70 typedef u32             fsoffset_t;
71 #define htonll          htonl
72 #define ntohll          ntohl
73 #else
74 typedef u64             fsoffset_t;
75 #endif
76
77
78 //#define DODBG
79 #ifdef DODBG
80 #define DEBUG( a ) printf( a )
81 #define DEBUG2( a,b ) printf( a,b )
82 #define DEBUG3( a,b,c ) printf( a,b,c )
83 #else
84 #define DEBUG( a )
85 #define DEBUG2( a,b ) 
86 #define DEBUG3( a,b,c ) 
87 #endif
88
89 #if     defined(HAVE_LLSEEK) && !defined(sun)
90 /* Solaris already has llseek defined in unistd.h */
91 extern long long llseek(unsigned int, long long, unsigned int);
92 #endif
93
94 void serveconnection(int net);
95 void set_peername(int net,char *clientname);
96
97 #define LINELEN 256 
98 char difffilename[256];
99 unsigned int timeout = 0;
100
101 int authorized_client(char *name)
102 /* 0 - authorization refused, 1 - OK 
103   authorization file contains one line per machine, no wildcards
104 */
105 { FILE *f ;
106    
107   char line[LINELEN] ; 
108
109   if ((f=fopen(AUTH_FILE,"r"))==NULL)
110     { msg4(LOG_INFO,"Can't open authorization file %s (%s).",
111            AUTH_FILE,strerror(errno)) ;
112       return 1 ; 
113     }
114   
115   while (fgets(line,LINELEN,f)!=NULL) {
116     if (strncmp(line,name,strlen(name))==0) { fclose(f)  ; return 1 ; }
117   }
118   fclose(f) ;
119   return 0 ;
120 }
121
122
123 inline void readit(int f, void *buf, int len)
124 {
125         int res;
126         while (len > 0) {
127                 DEBUG("*");
128                 if ((res = read(f, buf, len)) <= 0)
129                         err("Read failed: %m");
130                 len -= res;
131                 buf += res;
132         }
133 }
134
135 inline void writeit(int f, void *buf, int len)
136 {
137         int res;
138         while (len > 0) {
139                 DEBUG("+");
140                 if ((res = write(f, buf, len)) <= 0)
141                         err("Write failed: %m");
142                 len -= res;
143                 buf += res;
144         }
145 }
146
147 int port;                       /* Port I'm listening at */
148 char *exportname;               /* File I'm exporting */
149 fsoffset_t exportsize = (fsoffset_t)-1; /* ...and its length */
150 fsoffset_t hunksize = (fsoffset_t)-1;
151 int flags = 0;
152 int export[1024];
153 int difffile=-1 ;
154 u32 difffilelen=0 ; /* number of pages in difffile */
155 u32 *difmap=NULL ;
156 char clientname[256] ;
157
158
159 #define DIFFPAGESIZE 4096 /* diff file uses those chunks */
160
161 #define F_READONLY 1
162 #define F_MULTIFILE 2 
163 #define F_COPYONWRITE 4
164
165 void cmdline(int argc, char *argv[])
166 {
167         int i;
168
169         if (argc < 3) {
170                 printf("This is nbd-server version " VERSION "\n");     
171                 printf("Usage: port file_to_export [size][kKmM] [-r] [-m] [-c] [-a timeout_sec]\n"
172                        "        -r read only\n"
173                        "        -m multiple file\n"
174                        "        -c copy on write\n"
175                        "        -a maximum idle seconds, terminates when idle time exceeded\n"
176                        "        if port is set to 0, stdin is used (for running from inetd)\n"
177                        "        if file_to_export contains '%%s', it is substituted with IP\n"
178                        "                address of machine trying to connect\n" );
179                 exit(0);
180         }
181         port = atoi(argv[1]);
182         for (i = 3; i < argc; i++) {
183                 if (*argv[i] == '-') {
184                         switch (argv[i][1]) {
185                         case 'r':
186                                 flags |= F_READONLY;
187                                 break;
188                         case 'm':
189                                 flags |= F_MULTIFILE;
190                                 hunksize = 1*GIGA;
191                                 break;
192                         case 'c': flags |=F_COPYONWRITE;
193                                 break;
194                         case 'a': 
195                                 if (i+1<argc) {
196                                         timeout = atoi(argv[i+1]);
197                                         i++;
198                                 } else {
199                                         fprintf(stderr, "timeout requires argument\n");
200                                         exit(1);
201                                 }
202                         }
203                 } else {
204                         fsoffset_t es;
205                         int last = strlen(argv[i])-1;
206                         char suffix = argv[i][last];
207                         if (suffix == 'k' || suffix == 'K' ||
208                             suffix == 'm' || suffix == 'M')
209                                 argv[i][last] = '\0';
210                         es = (fsoffset_t)atol(argv[i]);
211                         switch (suffix) {
212                                 case 'm':
213                                 case 'M':  es <<= 10;
214                                 case 'k':
215                                 case 'K':  es <<= 10;
216                                 default :  break;
217                         }
218                         exportsize = es;
219                 }
220         }
221
222         exportname = argv[2];
223 }
224
225 void connectme(int port)
226 {
227         struct sockaddr_in addrin;
228         int addrinlen = sizeof(addrin);
229         int net, sock, newpid;
230 #ifndef sun
231         int yes=1;
232 #else
233         char yes='1';
234 #endif
235
236         if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
237                 err("socket: %m");
238
239         /* lose the pesky "Address already in use" error message */
240         if (setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) {
241                 err("setsockopt");
242         }
243
244         DEBUG("Waiting for connections... bind, ");
245         addrin.sin_family = AF_INET;
246         addrin.sin_port = htons(port);
247         addrin.sin_addr.s_addr = 0;
248         if (bind(sock, (struct sockaddr *) &addrin, addrinlen) < 0)
249                 err("bind: %m");
250         DEBUG("listen, ");
251         if (listen(sock, 1) < 0)
252                 err("listen: %m");
253         DEBUG("accept, ");
254         for(;;) { /* infinite loop */
255           if ((net = accept(sock, (struct sockaddr *) &addrin, &addrinlen)) < 0)
256             err("accept: %m");
257
258           set_peername(net,clientname) ;
259           if (!authorized_client(clientname)) {
260             msg2(LOG_INFO,"Unauthorized client") ;
261             close(net) ;
262             continue ;
263           }
264           msg2(LOG_INFO,"Authorized client") ;
265           if ((newpid=fork())<0) {
266             msg3(LOG_INFO,"Could not fork (%s)",strerror(errno)) ;
267             close(net) ;
268             continue ;
269           }
270           if (newpid>0) { /* parent */
271             close(net) ; continue ; }
272           /* child */
273           close(sock) ;
274           msg2(LOG_INFO,"Starting to serve") ;
275           serveconnection(net) ;        
276         }
277 }
278
279 #define SEND writeit( net, &reply, sizeof( reply ));
280 #define ERROR { reply.error = htonl(-1); SEND; reply.error = 0; lastpoint = -1; }
281
282 fsoffset_t lastpoint = (fsoffset_t)-1;
283
284 void maybeseek(int handle, fsoffset_t a)
285 {
286         if (a > exportsize)
287                 err("Can not happen\n");
288         if (lastpoint != a) {
289 #if     defined(HAVE_LLSEEK) && !defined(FS_32BIT)
290                 if (llseek(handle, a, SEEK_SET) < 0)
291 #else
292                 if (lseek(handle, (long)a, SEEK_SET) < 0)
293 #endif
294                         err("Can not seek locally!\n");
295                 lastpoint = a;
296         } else {
297                 DEBUG("@");
298         }
299 }
300
301 void myseek(int handle,fsoffset_t a)
302 {
303 #if HAVE_LLSEEK && !defined(FS_32BIT)
304   if (llseek(handle, a, SEEK_SET) < 0)
305 #else
306   if (lseek(handle, (long)a, SEEK_SET) < 0)
307 #endif 
308     err("Can not seek locally!\n");
309 }
310
311 char pagebuf[DIFFPAGESIZE] ;
312
313
314 int rawexpread(fsoffset_t a, char *buf, int len)
315 {
316   maybeseek(export[a/hunksize], a%hunksize);
317   return (read(export[a/hunksize], buf, len) != len);
318 }
319
320 int expread(fsoffset_t a, char *buf, int len)
321 {
322         int rdlen, offset;
323         fsoffset_t mapcnt, mapl, maph, pagestart;
324  
325   if (flags & F_COPYONWRITE) {
326     DEBUG3("Asked to read %d bytes at %Lu.\n", len, (unsigned long long)a);
327
328     mapl=a/DIFFPAGESIZE ; maph=(a+len-1)/DIFFPAGESIZE ;
329
330     for (mapcnt=mapl;mapcnt<=maph;mapcnt++) {
331       pagestart=mapcnt*DIFFPAGESIZE ;
332       offset=a-pagestart ;
333       rdlen=(len<DIFFPAGESIZE-offset) ? len : DIFFPAGESIZE-offset ;
334       if (difmap[mapcnt]!=(u32)(-1)) { /* the block is already there */
335         DEBUG3("Page %Lu is at %lu\n", (unsigned long long)mapcnt,
336                         (unsigned long)difmap[mapcnt]);
337         myseek(difffile,difmap[mapcnt]*DIFFPAGESIZE+offset) ;
338         if (read(difffile, buf, rdlen) != rdlen) return -1 ;
339       } else { /* the block is not there */
340         DEBUG2("Page %Lu is not here, we read the original one\n",
341                         (unsigned long long)mapcnt) ;
342         if (rawexpread(a,buf,rdlen)) return -1 ;
343       }
344       len-=rdlen ; a+=rdlen ; buf+=rdlen ;
345     }
346   } else return rawexpread(a,buf,len) ;
347   return 0 ;
348 }
349
350 int rawexpwrite(fsoffset_t a, char *buf, int len)
351 {
352         maybeseek(export[a/hunksize], a%hunksize);
353         return (write(export[a/hunksize], buf, len) != len);
354 }
355
356
357 int expwrite(fsoffset_t a, char *buf, int len)
358 {  u32 mapcnt,mapl,maph ; int wrlen,rdlen ; 
359    fsoffset_t pagestart ; int offset ;
360
361   if (flags & F_COPYONWRITE) {
362     DEBUG3("Asked to write %d bytes at %Lu.\n", len, (unsigned long long)a);
363
364     mapl=a/DIFFPAGESIZE ; maph=(a+len-1)/DIFFPAGESIZE ;
365
366     for (mapcnt=mapl;mapcnt<=maph;mapcnt++) {
367       pagestart=mapcnt*DIFFPAGESIZE ;
368       offset=a-pagestart ;
369       wrlen=(len<DIFFPAGESIZE-offset) ? len : DIFFPAGESIZE-offset ;
370
371       if (difmap[mapcnt]!=(u32)(-1)) { /* the block is already there */
372         DEBUG3("Page %Lu is at %lu\n", (unsigned long long)mapcnt,
373                         (unsigned long)difmap[mapcnt]) ;
374         myseek(difffile,difmap[mapcnt]*DIFFPAGESIZE+offset) ;
375         if (write(difffile, buf, wrlen) != wrlen) return -1 ;
376       } else { /* the block is not there */
377         myseek(difffile,difffilelen*DIFFPAGESIZE) ;
378         difmap[mapcnt]=difffilelen++ ;
379         DEBUG3("Page %Lu is not here, we put it at %lu\n",
380                         (unsigned long long)mapcnt,
381                         (unsigned long)difmap[mapcnt]);
382         rdlen=DIFFPAGESIZE ;
383         if (rdlen+pagestart%hunksize>hunksize) 
384           rdlen=hunksize-(pagestart%hunksize) ;
385         if (rawexpread(pagestart,pagebuf,rdlen)) return -1 ;
386         memcpy(pagebuf+offset,buf,wrlen) ;
387         if (write(difffile,pagebuf,DIFFPAGESIZE)!=DIFFPAGESIZE) return -1 ;
388       }                                             
389       len-=wrlen ; a+=wrlen ; buf+=wrlen ;
390     }
391   } else return(rawexpwrite(a,buf,len)); 
392   return 0 ;
393 }
394
395 int mainloop(int net)
396 {
397         struct nbd_request request;
398         struct nbd_reply reply;
399         char zeros[300];
400         int i = 0;
401         fsoffset_t size_host;
402
403         memset(zeros, 0, 290);
404         if (write(net, INIT_PASSWD, 8) < 0)
405                 err("Negotiation failed: %m");
406 #ifndef FS_32BIT
407         cliserv_magic = htonll(cliserv_magic);
408 #endif
409         if (write(net, &cliserv_magic, sizeof(cliserv_magic)) < 0)
410                 err("Negotiation failed: %m");
411         size_host = htonll(exportsize);
412 #ifdef  FS_32BIT
413         if (write(net, zeros, 4) < 0 || write(net, &size_host, 4) < 0)
414 #else
415         if (write(net, &size_host, 8) < 0)
416 #endif
417                 err("Negotiation failed: %m");
418         if (write(net, zeros, 128) < 0)
419                 err("Negotiation failed: %m");
420
421         DEBUG("Entering request loop!\n");
422         reply.magic = htonl(NBD_REPLY_MAGIC);
423         reply.error = 0;
424         while (1) {
425 #define BUFSIZE (1024*1024)
426                 char buf[BUFSIZE];
427                 int len;
428
429 #ifdef DODBG
430                 i++;
431                 printf("%d: ", i);
432 #endif
433
434                 if (timeout) 
435                         alarm(timeout);
436                 readit(net, &request, sizeof(request));
437                 request.from = ntohll(request.from);
438                 request.type = ntohl(request.type);
439
440                 if (request.type==2) { /* Disconnect request */
441                   if (difmap) free(difmap) ;
442                   if (difffile>=0) { 
443                      close(difffile) ; unlink(difffilename) ; }
444                   err("Disconnect request received.") ;
445                 }
446
447                 len = ntohl(request.len);
448
449                 if (request.magic != htonl(NBD_REQUEST_MAGIC))
450                         err("Not enough magic.");
451                 if (len > BUFSIZE)
452                         err("Request too big!");
453 #ifdef DODBG
454                 printf("%s from %Lu (%Lu) len %d, ", request.type ? "WRITE" :
455                                 "READ", (unsigned long long)request.from,
456                                 (unsigned long long)request.from / 512, len);
457 #endif
458                 memcpy(reply.handle, request.handle, sizeof(reply.handle));
459                 if (((request.from + len) > exportsize) ||
460                     ((flags & F_READONLY) && request.type)) {
461                         DEBUG("[RANGE!]");
462                         ERROR;
463                         continue;
464                 }
465                 if (request.type==1) {  /* WRITE */
466                         DEBUG("wr: net->buf, ");
467                         readit(net, buf, len);
468                         DEBUG("buf->exp, ");
469                         if (expwrite(request.from, buf, len)) {
470                                 DEBUG("Write failed: %m" );
471                                 ERROR;
472                                 continue;
473                         }
474                         lastpoint += len;
475                         SEND;
476                         continue;
477                 }
478                 /* READ */
479
480                 DEBUG("exp->buf, ");
481                 if (expread(request.from, buf + sizeof(struct nbd_reply), len)) {
482                         lastpoint = -1;
483                         DEBUG("Read failed: %m");
484                         ERROR;
485                         continue;
486                 }
487                 lastpoint += len;
488
489                 DEBUG("buf->net, ");
490                 memcpy(buf, &reply, sizeof(struct nbd_reply));
491                 writeit(net, buf, len + sizeof(struct nbd_reply));
492                 DEBUG("OK!\n");
493         }
494 }
495
496 char exportname2[1024];
497
498 void set_peername(int net,char *clientname)
499 {
500         struct sockaddr_in addrin;
501         int addrinlen = sizeof( addrin );
502         char *peername ;
503
504         if (getpeername( net, (struct sockaddr *) &addrin, &addrinlen ) < 0)
505                 err("getsockname failed: %m");
506         peername = inet_ntoa(addrin.sin_addr);
507         sprintf(exportname2, exportname, peername);
508
509         msg4(LOG_INFO, "connect from %s, assigned file is %s", peername, exportname2);
510         strncpy(clientname,peername,255) ;
511 }
512
513 fsoffset_t size_autodetect(int export)
514 {
515         fsoffset_t es;
516         u32 es32;
517         struct stat stat_buf;
518         int error;
519
520         DEBUG("looking for export size with lseek SEEK_END\n");
521         es = (fsoffset_t)lseek(export, 0, SEEK_END);
522         if ((signed long long)es > 0LL)
523                 return es;
524
525         DEBUG("looking for export size with fstat\n");
526         stat_buf.st_size = 0;
527         error = fstat(export, &stat_buf);
528         if (!error && stat_buf.st_size > 0)
529                 return (fsoffset_t)stat_buf.st_size;
530
531 #ifdef BLKGETSIZE
532         DEBUG("looking for export size with ioctl BLKGETSIZE\n");
533         if (!ioctl(export, BLKGETSIZE, &es32) && es32) {
534                 es = (fsoffset_t)es32 * (fsoffset_t)512;
535                 return es;
536         }
537 #endif
538         err("Could not find size of exported block device: %m");
539         return (fsoffset_t)-1;
540 }
541
542 int main(int argc, char *argv[])
543 {
544         int net;
545         fsoffset_t i;
546
547         if (sizeof( struct nbd_request )!=28) {
548                 fprintf(stderr,"Bad size of structure. Alignment problems?\n");
549                 exit(-1) ;
550         }
551         logging();
552         cmdline(argc, argv);
553         
554         if (!port) return 1 ;
555         connectme(port); /* serve infinitely */
556         return 0 ;
557 }
558
559
560 void serveconnection(int net) 
561 {   
562   u64 i ;
563
564   for (i=0; i<exportsize; i+=hunksize) {
565     char exportname3[1024];
566     
567     sprintf(exportname3, exportname2, i/hunksize);
568     printf( "Opening %s\n", exportname3 );
569     if ((export[i/hunksize] = open(exportname3, (flags & F_READONLY) ? O_RDONLY : O_RDWR)) == -1)
570       err("Could not open exported file: %m");
571     }
572         
573     if (exportsize == (fsoffset_t)-1) {
574         exportsize = size_autodetect(export[0]);
575     }
576     if (exportsize > ((fsoffset_t)-1 >> 1)) {
577 #ifdef HAVE_LLSEEK
578         if ((exportsize >> 10) > ((fsoffset_t)-1 >> 1))
579                 msg3(LOG_INFO, "size of exported file/device is %LuMB",
580                                 (unsigned long long)(exportsize >> 20));
581         else
582                 msg3(LOG_INFO, "size of exported file/device is %LuKB",
583                                 (unsigned long long)(exportsize >> 10));
584     }
585 #else
586         err("Size of exported file is too big\n");
587     }
588 #endif
589     else
590         msg3(LOG_INFO, "size of exported file/device is %Lu",
591                         (unsigned long long)exportsize);
592
593     if (flags & F_COPYONWRITE) {
594       sprintf(difffilename,"%s-%s-%d.diff",exportname2,clientname,
595               (int)getpid()) ;
596       msg3(LOG_INFO,"About to create map and diff file %s",difffilename) ;
597       difffile=open(difffilename,O_RDWR | O_CREAT | O_TRUNC,0600) ;
598       if (difffile<0) err("Could not create diff file (%m)") ;
599       if ((difmap=calloc(exportsize/DIFFPAGESIZE,sizeof(u32)))==NULL)
600           err("Could not allocate memory") ;
601       for (i=0;i<exportsize/DIFFPAGESIZE;i++) difmap[i]=(u32)-1 ;         
602     }
603     
604     setmysockopt(net);
605       
606     mainloop(net);
607 }