2 * Network Block Device - server
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>
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>
32 #define GIGA (1*1024*1024*1024)
34 #include <sys/types.h>
35 #include <sys/socket.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* */
48 #include <arpa/inet.h>
53 #define MY_NAME "nbd_server"
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"
62 /* Deep magic: ioctl.h defines _IO macro (at least on linux) */
65 /* Debugging macros, now nothing goes to syslog unless you say 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)
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)
77 #include <sys/ioctl.h>
78 #include <sys/mount.h> /* For BLKGETSIZE */
82 #define DEBUG( a ) printf( a )
83 #define DEBUG2( a,b ) printf( a,b )
84 #define DEBUG3( a,b,c ) printf( a,b,c )
88 #define DEBUG3( a,b,c )
91 void serveconnection(int net);
92 void set_peername(int net,char *clientname);
95 char difffilename[256];
96 unsigned int timeout = 0;
99 int authorized_client(char *name)
100 /* 0 - authorization refused, 1 - OK
101 authorization file contains one line per machine, no wildcards
107 if ((f=fopen(AUTH_FILE,"r"))==NULL)
108 { msg4(LOG_INFO,"Can't open authorization file %s (%s).",
109 AUTH_FILE,strerror(errno)) ;
113 while (fgets(line,LINELEN,f)!=NULL) {
114 if (strncmp(line,name,strlen(name))==0) { fclose(f) ; return 1 ; }
121 inline void readit(int f, void *buf, int len)
126 if ((res = read(f, buf, len)) <= 0)
127 err("Read failed: %m");
133 inline void writeit(int f, void *buf, int len)
138 if ((res = send(f, buf, len, 0)) <= 0)
139 err("Send failed: %m");
145 /* This is starting to get ugly. If someone knows a better way to find
146 * the maximum value of a signed type *without* relying on overflow
147 * (doing so breaks on 64bit architectures), that would be nice.
149 #define OFFT_MAX (((((off_t)1)<<((sizeof(off_t)-1)*8))-1)<<7)+127
150 int port; /* Port I'm listening at */
151 char *exportname; /* File I'm exporting */
152 off_t exportsize = OFFT_MAX; /* ...and its length */
153 off_t hunksize = OFFT_MAX;
157 u32 difffilelen=0 ; /* number of pages in difffile */
159 char clientname[256] ;
162 #define DIFFPAGESIZE 4096 /* diff file uses those chunks */
165 #define F_MULTIFILE 2
166 #define F_COPYONWRITE 4
168 void cmdline(int argc, char *argv[])
173 printf("This is nbd-server version " VERSION "\n");
174 printf("Usage: port file_to_export [size][kKmM] [-r] [-m] [-c] [-a timeout_sec]\n"
176 " -m multiple file\n"
177 " -c copy on write\n"
178 " -a maximum idle seconds, terminates when idle time exceeded\n"
179 " if port is set to 0, stdin is used (for running from inetd)\n"
180 " if file_to_export contains '%%s', it is substituted with IP\n"
181 " address of machine trying to connect\n" );
184 port = atoi(argv[1]);
185 for (i = 3; i < argc; i++) {
186 if (*argv[i] == '-') {
187 switch (argv[i][1]) {
192 flags |= F_MULTIFILE;
195 case 'c': flags |=F_COPYONWRITE;
199 timeout = atoi(argv[i+1]);
202 fprintf(stderr, "timeout requires argument\n");
208 int last = strlen(argv[i])-1;
209 char suffix = argv[i][last];
210 if (suffix == 'k' || suffix == 'K' ||
211 suffix == 'm' || suffix == 'M')
212 argv[i][last] = '\0';
213 es = (off_t)atol(argv[i]);
225 exportname = argv[2];
228 void sigchld_handler(int s)
230 while(wait(NULL) > 0);
233 void connectme(int port)
235 struct sockaddr_in addrin;
237 int addrinlen = sizeof(addrin);
238 int net, sock, newpid;
245 if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
248 /* lose the pesky "Address already in use" error message */
249 if (setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) {
253 DEBUG("Waiting for connections... bind, ");
254 addrin.sin_family = AF_INET;
255 addrin.sin_port = htons(port);
256 addrin.sin_addr.s_addr = 0;
257 if (bind(sock, (struct sockaddr *) &addrin, addrinlen) < 0)
260 if (listen(sock, 1) < 0)
263 sa.sa_handler = sigchld_handler;
264 sigemptyset(&sa.sa_mask);
265 sa.sa_flags = SA_RESTART;
266 if(sigaction(SIGCHLD, &sa, NULL) == -1)
267 err("sigaction: %m");
268 for(;;) { /* infinite loop */
269 if ((net = accept(sock, (struct sockaddr *) &addrin, &addrinlen)) < 0)
272 set_peername(net,clientname) ;
273 if (!authorized_client(clientname)) {
274 msg2(LOG_INFO,"Unauthorized client") ;
278 msg2(LOG_INFO,"Authorized client") ;
280 if ((newpid=fork())<0) {
281 msg3(LOG_INFO,"Could not fork (%s)",strerror(errno)) ;
285 if (newpid>0) { /* parent */
286 close(net) ; continue ; }
290 msg2(LOG_INFO,"Starting to serve") ;
291 serveconnection(net) ;
295 #define SEND writeit( net, &reply, sizeof( reply ));
296 #define ERROR { reply.error = htonl(-1); SEND; reply.error = 0; lastpoint = -1; }
298 off_t lastpoint = (off_t)-1;
300 void maybeseek(int handle, off_t a)
303 err("Can not happen\n");
304 if (lastpoint != a) {
305 if (lseek(handle, a, SEEK_SET) < 0)
306 err("Can not seek locally!\n");
313 void myseek(int handle,off_t a)
315 if (lseek(handle, a, SEEK_SET) < 0)
316 err("Can not seek locally!\n");
319 char pagebuf[DIFFPAGESIZE];
321 int rawexpread(off_t a, char *buf, int len)
323 maybeseek(export[a/hunksize], a%hunksize);
324 return (read(export[a/hunksize], buf, len) != len);
327 int expread(off_t a, char *buf, int len)
330 off_t mapcnt, mapl, maph, pagestart;
332 if (!(flags & F_COPYONWRITE))
333 return rawexpread(a, buf, len);
334 DEBUG3("Asked to read %d bytes at %Lu.\n", len, (unsigned long long)a);
336 mapl=a/DIFFPAGESIZE; maph=(a+len-1)/DIFFPAGESIZE;
338 for (mapcnt=mapl;mapcnt<=maph;mapcnt++) {
339 pagestart=mapcnt*DIFFPAGESIZE;
341 rdlen=(len<DIFFPAGESIZE-offset) ? len : DIFFPAGESIZE-offset;
342 if (difmap[mapcnt]!=(u32)(-1)) { /* the block is already there */
343 DEBUG3("Page %Lu is at %lu\n", (unsigned long long)mapcnt,
344 (unsigned long)difmap[mapcnt]);
345 myseek(difffile, difmap[mapcnt]*DIFFPAGESIZE+offset);
346 if (read(difffile, buf, rdlen) != rdlen) return -1;
347 } else { /* the block is not there */
348 DEBUG2("Page %Lu is not here, we read the original one\n",
349 (unsigned long long)mapcnt);
350 return rawexpread(a, buf, rdlen);
352 len-=rdlen; a+=rdlen; buf+=rdlen;
357 int rawexpwrite(off_t a, char *buf, int len)
359 maybeseek(export[a/hunksize], a%hunksize);
360 return (write(export[a/hunksize], buf, len) != len);
364 int expwrite(off_t a, char *buf, int len)
366 u32 mapcnt,mapl,maph ; int wrlen,rdlen ;
367 off_t pagestart ; int offset ;
369 if (!(flags & F_COPYONWRITE))
370 return(rawexpwrite(a,buf,len));
371 DEBUG3("Asked to write %d bytes at %Lu.\n", len, (unsigned long long)a);
373 mapl=a/DIFFPAGESIZE ; maph=(a+len-1)/DIFFPAGESIZE ;
375 for (mapcnt=mapl;mapcnt<=maph;mapcnt++) {
376 pagestart=mapcnt*DIFFPAGESIZE ;
378 wrlen=(len<DIFFPAGESIZE-offset) ? len : DIFFPAGESIZE-offset ;
380 if (difmap[mapcnt]!=(u32)(-1)) { /* the block is already there */
381 DEBUG3("Page %Lu is at %lu\n", (unsigned long long)mapcnt,
382 (unsigned long)difmap[mapcnt]) ;
383 myseek(difffile,difmap[mapcnt]*DIFFPAGESIZE+offset) ;
384 if (write(difffile, buf, wrlen) != wrlen) return -1 ;
385 } else { /* the block is not there */
386 myseek(difffile,difffilelen*DIFFPAGESIZE) ;
387 difmap[mapcnt]=difffilelen++ ;
388 DEBUG3("Page %Lu is not here, we put it at %lu\n",
389 (unsigned long long)mapcnt,
390 (unsigned long)difmap[mapcnt]);
392 if (rdlen+pagestart%hunksize>hunksize)
393 rdlen=hunksize-(pagestart%hunksize) ;
394 if (rawexpread(pagestart,pagebuf,rdlen)) return -1 ;
395 memcpy(pagebuf+offset,buf,wrlen) ;
396 if (write(difffile,pagebuf,DIFFPAGESIZE)!=DIFFPAGESIZE) return -1 ;
398 len-=wrlen ; a+=wrlen ; buf+=wrlen ;
403 int mainloop(int net)
405 struct nbd_request request;
406 struct nbd_reply reply;
411 memset(zeros, 0, 290);
412 if (write(net, INIT_PASSWD, 8) < 0)
413 err("Negotiation failed: %m");
414 cliserv_magic = htonll(cliserv_magic);
415 if (write(net, &cliserv_magic, sizeof(cliserv_magic)) < 0)
416 err("Negotiation failed: %m");
417 size_host = htonll(exportsize);
418 if (write(net, &size_host, 8) < 0)
419 err("Negotiation failed: %m");
420 if (write(net, zeros, 128) < 0)
421 err("Negotiation failed: %m");
423 DEBUG("Entering request loop!\n");
424 reply.magic = htonl(NBD_REPLY_MAGIC);
427 #define BUFSIZE (1024*1024)
438 readit(net, &request, sizeof(request));
439 request.from = ntohll(request.from);
440 request.type = ntohl(request.type);
442 if (request.type==2) { /* Disconnect request */
443 if (difmap) free(difmap) ;
445 close(difffile) ; unlink(difffilename) ; }
446 err("Disconnect request received.") ;
449 len = ntohl(request.len);
451 if (request.magic != htonl(NBD_REQUEST_MAGIC))
452 err("Not enough magic.");
454 err("Request too big!");
456 printf("%s from %Lu (%Lu) len %d, ", request.type ? "WRITE" :
457 "READ", (unsigned long long)request.from,
458 (unsigned long long)request.from / 512, len);
460 memcpy(reply.handle, request.handle, sizeof(reply.handle));
461 if ((request.from + len) > (OFFT_MAX)) {
462 DEBUG("[Number too large!]");
466 if ((((off_t)request.from + len) > exportsize) ||
467 ((flags & F_READONLY) && request.type)) {
472 if (request.type==1) { /* WRITE */
473 DEBUG("wr: net->buf, ");
474 readit(net, buf, len);
476 if ((autoreadonly == 1) || expwrite(request.from, buf, len)) {
477 DEBUG("Write failed: %m" );
489 if (expread(request.from, buf + sizeof(struct nbd_reply), len)) {
491 DEBUG("Read failed: %m");
498 memcpy(buf, &reply, sizeof(struct nbd_reply));
499 writeit(net, buf, len + sizeof(struct nbd_reply));
504 char exportname2[1024];
506 void set_peername(int net,char *clientname)
508 struct sockaddr_in addrin;
509 int addrinlen = sizeof( addrin );
512 if (getpeername( net, (struct sockaddr *) &addrin, &addrinlen ) < 0)
513 err("getsockname failed: %m");
514 peername = inet_ntoa(addrin.sin_addr);
515 sprintf(exportname2, exportname, peername);
517 msg4(LOG_INFO, "connect from %s, assigned file is %s", peername, exportname2);
518 strncpy(clientname,peername,255) ;
521 off_t size_autodetect(int export)
525 struct stat stat_buf;
528 DEBUG("looking for export size with lseek SEEK_END\n");
529 es = lseek(export, (off_t)0, SEEK_END);
530 if (es > ((off_t)0)) {
533 DEBUG2("lseek failed: %d", errno==EBADF?1:(errno==ESPIPE?2:(errno==EINVAL?3:4)));
536 DEBUG("looking for export size with fstat\n");
537 stat_buf.st_size = 0;
538 error = fstat(export, &stat_buf);
539 if (!error && stat_buf.st_size > 0) {
540 return (off_t)stat_buf.st_size;
542 err("fstat failed: %m");
546 DEBUG("looking for export size with ioctl BLKGETSIZE\n");
547 if (!ioctl(export, BLKGETSIZE, &es32) && es32) {
548 es = (off_t)es32 * (off_t)512;
552 err("Could not find size of exported block device: %m");
556 int main(int argc, char *argv[])
561 if (sizeof( struct nbd_request )!=28) {
562 fprintf(stderr,"Bad size of structure. Alignment problems?\n");
568 if (!port) return 1 ;
569 connectme(port); /* serve infinitely */
574 void serveconnection(int net)
578 for (i=0; i<exportsize; i+=hunksize) {
579 char exportname3[1024];
581 sprintf(exportname3, exportname2, i/hunksize);
582 printf( "Opening %s\n", exportname3 );
583 if ((export[i/hunksize] = open(exportname3, (flags & F_READONLY) ? O_RDONLY : O_RDWR)) == -1) {
584 /* Read WRITE ACCESS was requested by media is only read only */
587 if ((export[i/hunksize] = open(exportname3, O_RDONLY)) == -1)
588 err("Could not open exported file: %m");
592 if (exportsize == (off_t)OFFT_MAX) {
593 exportsize = size_autodetect(export[0]);
595 if (exportsize > (off_t)OFFT_MAX) {
596 err("Size of exported file is too big\n");
599 msg3(LOG_INFO, "size of exported file/device is %Lu",
600 (unsigned long long)exportsize);
602 if (flags & F_COPYONWRITE) {
603 sprintf(difffilename,"%s-%s-%d.diff",exportname2,clientname,
605 msg3(LOG_INFO,"About to create map and diff file %s",difffilename) ;
606 difffile=open(difffilename,O_RDWR | O_CREAT | O_TRUNC,0600) ;
607 if (difffile<0) err("Could not create diff file (%m)") ;
608 if ((difmap=calloc(exportsize/DIFFPAGESIZE,sizeof(u32)))==NULL)
609 err("Could not allocate memory") ;
610 for (i=0;i<exportsize/DIFFPAGESIZE;i++) difmap[i]=(u32)-1 ;