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