r3: Initial revision
[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
96 int authorized_client(char *name)
97 /* 0 - authorization refused, 1 - OK 
98   authorization file contains one line per machine, no wildcards
99 */
100 { FILE *f ;
101    
102   char line[LINELEN] ; 
103
104   if ((f=fopen(AUTH_FILE,"r"))==NULL)
105     { msg4(LOG_INFO,"Can't open authorization file %s (%s).",
106            AUTH_FILE,strerror(errno)) ;
107       return 1 ; 
108     }
109   
110   while (fgets(line,LINELEN,f)!=NULL) {
111     if (strncmp(line,name,strlen(name))==0) { fclose(f)  ; return 1 ; }
112   }
113   fclose(f) ;
114   return 0 ;
115 }
116
117
118 inline void readit(int f, void *buf, int len)
119 {
120         int res;
121         while (len > 0) {
122                 DEBUG("*");
123                 if ((res = read(f, buf, len)) <= 0)
124                         err("Read failed: %m");
125                 len -= res;
126                 buf += res;
127         }
128 }
129
130 inline void writeit(int f, void *buf, int len)
131 {
132         int res;
133         while (len > 0) {
134                 DEBUG("+");
135                 if ((res = write(f, buf, len)) <= 0)
136                         err("Write failed: %m");
137                 len -= res;
138                 buf += res;
139         }
140 }
141
142 int port;                       /* Port I'm listening at */
143 char *exportname;               /* File I'm exporting */
144 fsoffset_t exportsize = ~0, hunksize = ~0;      /* ...and its length */
145 int flags = 0;
146 int export[1024];
147 int difffile=-1 ;
148 u32 difffilelen=0 ; /* number of pages in difffile */
149 u32 *difmap=NULL ;
150 char clientname[256] ;
151
152
153 #define DIFFPAGESIZE 4096 /* diff file uses those chunks */
154
155 #define F_READONLY 1
156 #define F_MULTIFILE 2 
157 #define F_COPYONWRITE 4
158
159 void cmdline(int argc, char *argv[])
160 {
161         int i;
162
163         if (argc < 3) {
164                 printf("This is nbd-server version " VERSION "\n");     
165                 printf("Usage: port file_to_export [size][kKmM] [-r] [-m] [-c]\n"
166                        "        -r read only\n"
167                        "        -m multiple file\n"
168                        "        -c copy on write\n"
169                        "        if port is set to 0, stdin is used (for running from inetd)\n"
170                        "        if file_to_export contains '%%s', it is substituted with IP\n"
171                        "                address of machine trying to connect\n" );
172                 exit(0);
173         }
174         port = atoi(argv[1]);
175         for (i = 3; i < argc; i++) {
176                 if (*argv[i] == '-') {
177                         switch (argv[i][1]) {
178                         case 'r':
179                                 flags |= F_READONLY;
180                                 break;
181                         case 'm':
182                                 flags |= F_MULTIFILE;
183                                 hunksize = 1*GIGA;
184                                 break;
185                         case 'c': flags |=F_COPYONWRITE ;
186                                 break ;
187                         }
188                 } else {
189                         fsoffset_t es;
190                         int last = strlen(argv[i])-1;
191                         char suffix = argv[i][last];
192                         if (suffix == 'k' || suffix == 'K' ||
193                             suffix == 'm' || suffix == 'M')
194                                 argv[i][last] = '\0';
195                         es = (fsoffset_t)atol(argv[i]);
196                         switch (suffix) {
197                                 case 'm':
198                                 case 'M':  es <<= 10;
199                                 case 'k':
200                                 case 'K':  es <<= 10;
201                                 default :  break;
202                         }
203                         exportsize = es;
204                 }
205         }
206
207         exportname = argv[2];
208 }
209
210 void connectme(int port)
211 {
212         struct sockaddr_in addrin;
213         int addrinlen = sizeof(addrin);
214         int net, sock, newpid;
215
216         if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
217                 err("socket: %m");
218
219         DEBUG("Waiting for connections... bind, ");
220         addrin.sin_family = AF_INET;
221         addrin.sin_port = htons(port);
222         addrin.sin_addr.s_addr = 0;
223         if (bind(sock, (struct sockaddr *) &addrin, addrinlen) < 0)
224                 err("bind: %m");
225         DEBUG("listen, ");
226         if (listen(sock, 1) < 0)
227                 err("listen: %m");
228         DEBUG("accept, ");
229         for(;;) { /* infinite loop */
230           if ((net = accept(sock, (struct sockaddr *) &addrin, &addrinlen)) < 0)
231             err("accept: %m");
232
233           set_peername(net,clientname) ;
234           if (!authorized_client(clientname)) {
235             msg2(LOG_INFO,"Unauthorized client") ;
236             close(net) ;
237             continue ;
238           }
239           msg2(LOG_INFO,"Authorized client") ;
240           if ((newpid=fork())<0) {
241             msg3(LOG_INFO,"Could not fork (%s)",strerror(errno)) ;
242             close(net) ;
243             continue ;
244           }
245           if (newpid>0) { /* parent */
246             close(net) ; continue ; }
247           /* child */
248           close(sock) ;
249           msg2(LOG_INFO,"Starting to serve") ;
250           serveconnection(net) ;        
251         }
252 }
253
254 #define SEND writeit( net, &reply, sizeof( reply ));
255 #define ERROR { reply.error = htonl(-1); SEND; reply.error = 0; lastpoint = -1; }
256
257 fsoffset_t lastpoint = -1;
258
259 void maybeseek(int handle, fsoffset_t a)
260 {
261         if (a > exportsize)
262                 err("Can not happen\n");
263         if (lastpoint != a) {
264 #if     defined(HAVE_LLSEEK) && !defined(FS_32BIT)
265                 if (llseek(handle, a, SEEK_SET) < 0)
266 #else
267                 if (lseek(handle, (long)a, SEEK_SET) < 0)
268 #endif
269                         err("Can not seek locally!\n");
270                 lastpoint = a;
271         } else {
272                 DEBUG("@");
273         }
274 }
275
276 void myseek(int handle,fsoffset_t a)
277 {
278 #if HAVE_LLSEEK && !defined(FS_32BIT)
279   if (llseek(handle, a, SEEK_SET) < 0)
280 #else
281   if (lseek(handle, (long)a, SEEK_SET) < 0)
282 #endif 
283     err("Can not seek locally!\n");
284 }
285
286 char pagebuf[DIFFPAGESIZE] ;
287
288
289 int rawexpread(fsoffset_t a, char *buf, int len)
290 {
291   maybeseek(export[a/hunksize], a%hunksize);
292   return (read(export[a/hunksize], buf, len) != len);
293 }
294
295 int expread(fsoffset_t a, char *buf, int len)
296 { int rdlen ; fsoffset_t mapcnt,mapl,maph ;
297   fsoffset_t pagestart; int offset ;
298  
299   if (flags & F_COPYONWRITE) {
300     DEBUG3("Asked to read %d bytes at %lu.\n",len,(unsigned long)a) ;
301
302     mapl=a/DIFFPAGESIZE ; maph=(a+len-1)/DIFFPAGESIZE ;
303
304     for (mapcnt=mapl;mapcnt<=maph;mapcnt++) {
305       pagestart=mapcnt*DIFFPAGESIZE ;
306       offset=a-pagestart ;
307       rdlen=(len<DIFFPAGESIZE-offset) ? len : DIFFPAGESIZE-offset ;
308       if (difmap[mapcnt]!=(u32)(-1)) { /* the block is already there */
309         DEBUG3("Page %d is at %ld\n",(int)mapcnt,(long int)difmap[mapcnt]) ;
310         myseek(difffile,difmap[mapcnt]*DIFFPAGESIZE+offset) ;
311         if (read(difffile, buf, rdlen) != rdlen) return -1 ;
312       } else { /* the block is not there */
313         DEBUG2("Page %d is not here, we read the original one\n",
314               (int)mapcnt) ;
315         if (rawexpread(a,buf,rdlen)) return -1 ;
316       }
317       len-=rdlen ; a+=rdlen ; buf+=rdlen ;
318     }
319   } else return rawexpread(a,buf,len) ;
320   return 0 ;
321 }
322
323 int rawexpwrite(fsoffset_t a, char *buf, int len)
324 {
325         maybeseek(export[a/hunksize], a%hunksize);
326         return (write(export[a/hunksize], buf, len) != len);
327 }
328
329
330 int expwrite(fsoffset_t a, char *buf, int len)
331 {  u32 mapcnt,mapl,maph ; int wrlen,rdlen ; 
332    fsoffset_t pagestart ; int offset ;
333
334   if (flags & F_COPYONWRITE) {
335     DEBUG3("Asked to write %d bytes at %lu.\n",len,(unsigned long)a) ;
336
337     mapl=a/DIFFPAGESIZE ; maph=(a+len-1)/DIFFPAGESIZE ;
338
339     for (mapcnt=mapl;mapcnt<=maph;mapcnt++) {
340       pagestart=mapcnt*DIFFPAGESIZE ;
341       offset=a-pagestart ;
342       wrlen=(len<DIFFPAGESIZE-offset) ? len : DIFFPAGESIZE-offset ;
343
344       if (difmap[mapcnt]!=(u32)(-1)) { /* the block is already there */
345         DEBUG3("Page %d is at %ld\n",mapcnt,(long)difmap[mapcnt]) ;
346         myseek(difffile,difmap[mapcnt]*DIFFPAGESIZE+offset) ;
347         if (write(difffile, buf, wrlen) != wrlen) return -1 ;
348       } else { /* the block is not there */
349         myseek(difffile,difffilelen*DIFFPAGESIZE) ;
350         difmap[mapcnt]=difffilelen++ ;
351         DEBUG3("Page %d is not here, we put it at %ld\n",
352               mapcnt,(long)difmap[mapcnt]) ;
353
354         rdlen=DIFFPAGESIZE ;
355         if (rdlen+pagestart%hunksize>hunksize) 
356           rdlen=hunksize-(pagestart%hunksize) ;
357         if (rawexpread(pagestart,pagebuf,rdlen)) return -1 ;
358         memcpy(pagebuf+offset,buf,wrlen) ;
359         if (write(difffile,pagebuf,DIFFPAGESIZE)!=DIFFPAGESIZE) return -1 ;
360       }                                             
361       len-=wrlen ; a+=wrlen ; buf+=wrlen ;
362     }
363   } else return(rawexpwrite(a,buf,len)); 
364   return 0 ;
365 }
366
367 int mainloop(int net)
368 {
369         struct nbd_request request;
370         struct nbd_reply reply;
371         char zeros[300];
372         int i = 0;
373         fsoffset_t size_host;
374
375         memset(zeros, 0, 290);
376         if (write(net, INIT_PASSWD, 8) < 0)
377                 err("Negotiation failed: %m");
378 #ifndef FS_32BIT
379         cliserv_magic = htonll(cliserv_magic);
380 #endif
381         if (write(net, &cliserv_magic, sizeof(cliserv_magic)) < 0)
382                 err("Negotiation failed: %m");
383         size_host = htonll(exportsize);
384 #ifdef  FS_32BIT
385         if (write(net, zeros, 4) < 0 || write(net, &size_host, 4) < 0)
386 #else
387         if (write(net, &size_host, 8) < 0)
388 #endif
389                 err("Negotiation failed: %m");
390         if (write(net, zeros, 128) < 0)
391                 err("Negotiation failed: %m");
392
393         DEBUG("Entering request loop!\n");
394         reply.magic = htonl(NBD_REPLY_MAGIC);
395         reply.error = 0;
396         while (1) {
397                 char buf[20480];
398                 int len;
399
400 #ifdef DODBG
401                 i++;
402                 printf("%d: ", i);
403 #endif
404
405                 readit(net, &request, sizeof(request));
406                 request.from = ntohll(request.from);
407                 request.type = ntohl(request.type);
408
409                 if (request.type==2) { /* Disconnect request */
410                   if (difmap) free(difmap) ;
411                   if (difffile>=0) { 
412                      close(difffile) ; unlink(difffilename) ; }
413                   err("Disconnect request received.") ;
414                 }
415
416                 len = ntohl(request.len);
417
418                 if (request.magic != htonl(NBD_REQUEST_MAGIC))
419                         err("Not enough magic.");
420                 if (len > 10240)
421                         err("Request too big!");
422 #ifdef DODBG
423                 printf("%s from %d (%d) len %d, ", (request.type ? "WRITE" : "READ"),
424                        (int) request.from, (int) request.from / 512, len);
425 #endif
426                 memcpy(reply.handle, request.handle, sizeof(reply.handle));
427                 if (((request.from + len) > exportsize) ||
428                     ((flags & F_READONLY) && request.type)) {
429                         DEBUG("[RANGE!]");
430                         ERROR;
431                         continue;
432                 }
433                 if (request.type==1) {  /* WRITE */
434                         DEBUG("wr: net->buf, ");
435                         readit(net, buf, len);
436                         DEBUG("buf->exp, ");
437                         if (expwrite(request.from, buf, len)) {
438                                 DEBUG("Write failed: %m" );
439                                 ERROR;
440                                 continue;
441                         }
442                         lastpoint += len;
443                         SEND;
444                         continue;
445                 }
446                 /* READ */
447
448                 DEBUG("exp->buf, ");
449                 if (expread(request.from, buf + sizeof(struct nbd_reply), len)) {
450                         lastpoint = -1;
451                         DEBUG("Read failed: %m");
452                         ERROR;
453                         continue;
454                 }
455                 lastpoint += len;
456
457                 DEBUG("buf->net, ");
458                 memcpy(buf, &reply, sizeof(struct nbd_reply));
459                 writeit(net, buf, len + sizeof(struct nbd_reply));
460                 DEBUG("OK!\n");
461         }
462 }
463
464 char exportname2[1024];
465
466 void set_peername(int net,char *clientname)
467 {
468         struct sockaddr_in addrin;
469         int addrinlen = sizeof( addrin );
470         char *peername ;
471
472         if (getpeername( net, (struct sockaddr *) &addrin, &addrinlen ) < 0)
473                 err("getsockname failed: %m");
474         peername = inet_ntoa(addrin.sin_addr);
475         sprintf(exportname2, exportname, peername);
476
477         msg4(LOG_INFO, "connect from %s, assigned file is %s", peername, exportname2);
478         strncpy(clientname,peername,255) ;
479 }
480
481 fsoffset_t size_autodetect(int export)
482 {
483         fsoffset_t es;
484         DEBUG("looking for export size with lseek SEEK_END\n");
485         if ((int)(es = lseek(export, 0, SEEK_END)) == -1 || es == 0) {
486                 struct stat stat_buf = { 0, } ;
487                 int error;
488                 DEBUG("looking for export size with fstat\n");
489                 if ((error = fstat(export, &stat_buf)) == -1 || stat_buf.st_size == 0 ) {
490                         DEBUG("looking for export size with ioctl BLKGETSIZE\n");
491 #ifdef BLKGETSIZE
492                         if(ioctl(export, BLKGETSIZE, &es) || es == 0) {
493 #else
494                         if(1){
495 #endif
496                                 err("Could not find size of exported block device: %m");
497                         } else {
498                                 es *= 512; /* assume blocksize 512 */
499                         }
500                 } else {
501                         es = stat_buf.st_size;
502                 }
503         }
504         return es;
505 }
506
507 int main(int argc, char *argv[])
508 {
509         int net;
510         fsoffset_t i;
511
512         if (sizeof( struct nbd_request )!=28) {
513                 fprintf(stderr,"Bad size of structure. Alignment problems?\n");
514                 exit(-1) ;
515         }
516         logging();
517         cmdline(argc, argv);
518         
519         if (!port) return 1 ;
520         connectme(port); /* serve infinitely */
521         return 0 ;
522 }
523
524
525 void serveconnection(int net) 
526 {   
527   u64 i ;
528
529   for (i=0; i<exportsize; i+=hunksize) {
530     char exportname3[1024];
531     
532     sprintf(exportname3, exportname2, i/hunksize);
533     printf( "Opening %s\n", exportname3 );
534     if ((export[i/hunksize] = open(exportname3, (flags & F_READONLY) ? O_RDONLY : O_RDWR)) == -1)
535       err("Could not open exported file: %m");
536     }
537         
538     if (exportsize == (u64)~0) {
539       exportsize = size_autodetect(export[0]);
540     }
541     if (exportsize > (~0UL >> 1))
542 #ifdef HAVE_LLSEEK
543     if ((exportsize >> 10) > (~0UL >> 1))
544       msg3(LOG_INFO, "size of exported file/device is %luMB",
545                (unsigned long)(exportsize >> 20));
546     else
547       msg3(LOG_INFO, "size of exported file/device is %luKB",
548            (unsigned long)(exportsize >> 10));
549 #else
550     err("Size of exported file is too big\n");
551 #endif
552     else
553       msg3(LOG_INFO, "size of exported file/device is %lu",
554                        (unsigned long)exportsize);
555
556     if (flags & F_COPYONWRITE) {
557       sprintf(difffilename,"%s-%s-%d.diff",exportname2,clientname,
558               (int)getpid()) ;
559       msg3(LOG_INFO,"About to create map and diff file %s",difffilename) ;
560       difffile=open(difffilename,O_RDWR | O_CREAT | O_TRUNC,0600) ;
561       if (difffile<0) err("Could not create diff file (%m)") ;
562       if ((difmap=calloc(exportsize/DIFFPAGESIZE,sizeof(u32)))==NULL)
563           err("Could not allocate memory") ;
564       for (i=0;i<exportsize/DIFFPAGESIZE;i++) difmap[i]=(u32)-1 ;         
565     }
566     
567     setmysockopt(net);
568       
569     mainloop(net);
570 }