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