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