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