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
23 #define GIGA (1*1024*1024*1024)
25 #include <sys/types.h>
26 #include <sys/socket.h>
28 #include <netinet/tcp.h>
29 #include <netinet/in.h> /* sockaddr_in, htons, in_addr */
30 #include <netdb.h> /* hostent, gethostby*, getservby* */
37 #include <arpa/inet.h>
42 #define MY_NAME "nbd_server"
44 /* Authorization file should contain lines with IP addresses of
45 clients authorized to use the server. If it does not exist,
46 access is permitted. */
47 #define AUTH_FILE "nbd_server.allow"
51 /* Deep magic: ioctl.h defines _IO macro (at least on linux) */
54 /* Debugging macros, now nothing goes to syslog unless you say ISSERVER */
56 #define msg2(a,b) syslog(a,b)
57 #define msg3(a,b,c) syslog(a,b,c)
58 #define msg4(a,b,c,d) syslog(a,b,c,d)
60 #define msg2(a,b) do { fprintf(stderr,b) ; fputs("\n",stderr) ; } while(0)
61 #define msg3(a,b,c) do { fprintf(stderr,b,c); fputs("\n",stderr) ; } while(0)
62 #define msg4(a,b,c,d) do { fprintf(stderr,b,c,d); fputs("\n",stderr) ; } while(0)
66 #include <sys/ioctl.h>
67 #include <sys/mount.h> /* For BLKGETSIZE */
70 typedef u32 fsoffset_t;
74 typedef u64 fsoffset_t;
80 #define DEBUG( a ) printf( a )
81 #define DEBUG2( a,b ) printf( a,b )
82 #define DEBUG3( a,b,c ) printf( a,b,c )
86 #define DEBUG3( a,b,c )
89 #if defined(HAVE_LLSEEK) && !defined(sun)
90 /* Solaris already has llseek defined in unistd.h */
91 extern long long llseek(unsigned int, long long, unsigned int);
94 void serveconnection(int net);
95 void set_peername(int net,char *clientname);
98 char difffilename[256];
99 unsigned int timeout = 0;
101 int authorized_client(char *name)
102 /* 0 - authorization refused, 1 - OK
103 authorization file contains one line per machine, no wildcards
109 if ((f=fopen(AUTH_FILE,"r"))==NULL)
110 { msg4(LOG_INFO,"Can't open authorization file %s (%s).",
111 AUTH_FILE,strerror(errno)) ;
115 while (fgets(line,LINELEN,f)!=NULL) {
116 if (strncmp(line,name,strlen(name))==0) { fclose(f) ; return 1 ; }
123 inline void readit(int f, void *buf, int len)
128 if ((res = read(f, buf, len)) <= 0)
129 err("Read failed: %m");
135 inline void writeit(int f, void *buf, int len)
140 if ((res = write(f, buf, len)) <= 0)
141 err("Write failed: %m");
147 int port; /* Port I'm listening at */
148 char *exportname; /* File I'm exporting */
149 fsoffset_t exportsize = (fsoffset_t)-1; /* ...and its length */
150 fsoffset_t hunksize = (fsoffset_t)-1;
154 u32 difffilelen=0 ; /* number of pages in difffile */
156 char clientname[256] ;
159 #define DIFFPAGESIZE 4096 /* diff file uses those chunks */
162 #define F_MULTIFILE 2
163 #define F_COPYONWRITE 4
165 void cmdline(int argc, char *argv[])
170 printf("This is nbd-server version " VERSION "\n");
171 printf("Usage: port file_to_export [size][kKmM] [-r] [-m] [-c] [-a timeout_sec]\n"
173 " -m multiple file\n"
174 " -c copy on write\n"
175 " -a maximum idle seconds, terminates when idle time exceeded\n"
176 " if port is set to 0, stdin is used (for running from inetd)\n"
177 " if file_to_export contains '%%s', it is substituted with IP\n"
178 " address of machine trying to connect\n" );
181 port = atoi(argv[1]);
182 for (i = 3; i < argc; i++) {
183 if (*argv[i] == '-') {
184 switch (argv[i][1]) {
189 flags |= F_MULTIFILE;
192 case 'c': flags |=F_COPYONWRITE;
196 timeout = atoi(argv[i+1]);
199 fprintf(stderr, "timeout requires argument\n");
205 int last = strlen(argv[i])-1;
206 char suffix = argv[i][last];
207 if (suffix == 'k' || suffix == 'K' ||
208 suffix == 'm' || suffix == 'M')
209 argv[i][last] = '\0';
210 es = (fsoffset_t)atol(argv[i]);
222 exportname = argv[2];
225 void connectme(int port)
227 struct sockaddr_in addrin;
228 int addrinlen = sizeof(addrin);
229 int net, sock, newpid;
236 if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
239 /* lose the pesky "Address already in use" error message */
240 if (setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) {
244 DEBUG("Waiting for connections... bind, ");
245 addrin.sin_family = AF_INET;
246 addrin.sin_port = htons(port);
247 addrin.sin_addr.s_addr = 0;
248 if (bind(sock, (struct sockaddr *) &addrin, addrinlen) < 0)
251 if (listen(sock, 1) < 0)
254 for(;;) { /* infinite loop */
255 if ((net = accept(sock, (struct sockaddr *) &addrin, &addrinlen)) < 0)
258 set_peername(net,clientname) ;
259 if (!authorized_client(clientname)) {
260 msg2(LOG_INFO,"Unauthorized client") ;
264 msg2(LOG_INFO,"Authorized client") ;
265 if ((newpid=fork())<0) {
266 msg3(LOG_INFO,"Could not fork (%s)",strerror(errno)) ;
270 if (newpid>0) { /* parent */
271 close(net) ; continue ; }
274 msg2(LOG_INFO,"Starting to serve") ;
275 serveconnection(net) ;
279 #define SEND writeit( net, &reply, sizeof( reply ));
280 #define ERROR { reply.error = htonl(-1); SEND; reply.error = 0; lastpoint = -1; }
282 fsoffset_t lastpoint = (fsoffset_t)-1;
284 void maybeseek(int handle, fsoffset_t a)
287 err("Can not happen\n");
288 if (lastpoint != a) {
289 #if defined(HAVE_LLSEEK) && !defined(FS_32BIT)
290 if (llseek(handle, a, SEEK_SET) < 0)
292 if (lseek(handle, (long)a, SEEK_SET) < 0)
294 err("Can not seek locally!\n");
301 void myseek(int handle,fsoffset_t a)
303 #if HAVE_LLSEEK && !defined(FS_32BIT)
304 if (llseek(handle, a, SEEK_SET) < 0)
306 if (lseek(handle, (long)a, SEEK_SET) < 0)
308 err("Can not seek locally!\n");
311 char pagebuf[DIFFPAGESIZE] ;
314 int rawexpread(fsoffset_t a, char *buf, int len)
316 maybeseek(export[a/hunksize], a%hunksize);
317 return (read(export[a/hunksize], buf, len) != len);
320 int expread(fsoffset_t a, char *buf, int len)
323 fsoffset_t mapcnt, mapl, maph, pagestart;
325 if (flags & F_COPYONWRITE) {
326 DEBUG3("Asked to read %d bytes at %Lu.\n", len, (unsigned long long)a);
328 mapl=a/DIFFPAGESIZE ; maph=(a+len-1)/DIFFPAGESIZE ;
330 for (mapcnt=mapl;mapcnt<=maph;mapcnt++) {
331 pagestart=mapcnt*DIFFPAGESIZE ;
333 rdlen=(len<DIFFPAGESIZE-offset) ? len : DIFFPAGESIZE-offset ;
334 if (difmap[mapcnt]!=(u32)(-1)) { /* the block is already there */
335 DEBUG3("Page %Lu is at %lu\n", (unsigned long long)mapcnt,
336 (unsigned long)difmap[mapcnt]);
337 myseek(difffile,difmap[mapcnt]*DIFFPAGESIZE+offset) ;
338 if (read(difffile, buf, rdlen) != rdlen) return -1 ;
339 } else { /* the block is not there */
340 DEBUG2("Page %Lu is not here, we read the original one\n",
341 (unsigned long long)mapcnt) ;
342 if (rawexpread(a,buf,rdlen)) return -1 ;
344 len-=rdlen ; a+=rdlen ; buf+=rdlen ;
346 } else return rawexpread(a,buf,len) ;
350 int rawexpwrite(fsoffset_t a, char *buf, int len)
352 maybeseek(export[a/hunksize], a%hunksize);
353 return (write(export[a/hunksize], buf, len) != len);
357 int expwrite(fsoffset_t a, char *buf, int len)
358 { u32 mapcnt,mapl,maph ; int wrlen,rdlen ;
359 fsoffset_t pagestart ; int offset ;
361 if (flags & F_COPYONWRITE) {
362 DEBUG3("Asked to write %d bytes at %Lu.\n", len, (unsigned long long)a);
364 mapl=a/DIFFPAGESIZE ; maph=(a+len-1)/DIFFPAGESIZE ;
366 for (mapcnt=mapl;mapcnt<=maph;mapcnt++) {
367 pagestart=mapcnt*DIFFPAGESIZE ;
369 wrlen=(len<DIFFPAGESIZE-offset) ? len : DIFFPAGESIZE-offset ;
371 if (difmap[mapcnt]!=(u32)(-1)) { /* the block is already there */
372 DEBUG3("Page %Lu is at %lu\n", (unsigned long long)mapcnt,
373 (unsigned long)difmap[mapcnt]) ;
374 myseek(difffile,difmap[mapcnt]*DIFFPAGESIZE+offset) ;
375 if (write(difffile, buf, wrlen) != wrlen) return -1 ;
376 } else { /* the block is not there */
377 myseek(difffile,difffilelen*DIFFPAGESIZE) ;
378 difmap[mapcnt]=difffilelen++ ;
379 DEBUG3("Page %Lu is not here, we put it at %lu\n",
380 (unsigned long long)mapcnt,
381 (unsigned long)difmap[mapcnt]);
383 if (rdlen+pagestart%hunksize>hunksize)
384 rdlen=hunksize-(pagestart%hunksize) ;
385 if (rawexpread(pagestart,pagebuf,rdlen)) return -1 ;
386 memcpy(pagebuf+offset,buf,wrlen) ;
387 if (write(difffile,pagebuf,DIFFPAGESIZE)!=DIFFPAGESIZE) return -1 ;
389 len-=wrlen ; a+=wrlen ; buf+=wrlen ;
391 } else return(rawexpwrite(a,buf,len));
395 int mainloop(int net)
397 struct nbd_request request;
398 struct nbd_reply reply;
401 fsoffset_t size_host;
403 memset(zeros, 0, 290);
404 if (write(net, INIT_PASSWD, 8) < 0)
405 err("Negotiation failed: %m");
407 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);
413 if (write(net, zeros, 4) < 0 || write(net, &size_host, 4) < 0)
415 if (write(net, &size_host, 8) < 0)
417 err("Negotiation failed: %m");
418 if (write(net, zeros, 128) < 0)
419 err("Negotiation failed: %m");
421 DEBUG("Entering request loop!\n");
422 reply.magic = htonl(NBD_REPLY_MAGIC);
425 #define BUFSIZE (1024*1024)
436 readit(net, &request, sizeof(request));
437 request.from = ntohll(request.from);
438 request.type = ntohl(request.type);
440 if (request.type==2) { /* Disconnect request */
441 if (difmap) free(difmap) ;
443 close(difffile) ; unlink(difffilename) ; }
444 err("Disconnect request received.") ;
447 len = ntohl(request.len);
449 if (request.magic != htonl(NBD_REQUEST_MAGIC))
450 err("Not enough magic.");
452 err("Request too big!");
454 printf("%s from %Lu (%Lu) len %d, ", request.type ? "WRITE" :
455 "READ", (unsigned long long)request.from,
456 (unsigned long long)request.from / 512, len);
458 memcpy(reply.handle, request.handle, sizeof(reply.handle));
459 if (((request.from + len) > exportsize) ||
460 ((flags & F_READONLY) && request.type)) {
465 if (request.type==1) { /* WRITE */
466 DEBUG("wr: net->buf, ");
467 readit(net, buf, len);
469 if (expwrite(request.from, buf, len)) {
470 DEBUG("Write failed: %m" );
481 if (expread(request.from, buf + sizeof(struct nbd_reply), len)) {
483 DEBUG("Read failed: %m");
490 memcpy(buf, &reply, sizeof(struct nbd_reply));
491 writeit(net, buf, len + sizeof(struct nbd_reply));
496 char exportname2[1024];
498 void set_peername(int net,char *clientname)
500 struct sockaddr_in addrin;
501 int addrinlen = sizeof( addrin );
504 if (getpeername( net, (struct sockaddr *) &addrin, &addrinlen ) < 0)
505 err("getsockname failed: %m");
506 peername = inet_ntoa(addrin.sin_addr);
507 sprintf(exportname2, exportname, peername);
509 msg4(LOG_INFO, "connect from %s, assigned file is %s", peername, exportname2);
510 strncpy(clientname,peername,255) ;
513 fsoffset_t size_autodetect(int export)
517 struct stat stat_buf;
520 DEBUG("looking for export size with lseek SEEK_END\n");
521 es = (fsoffset_t)lseek(export, 0, SEEK_END);
522 if ((signed long long)es > 0LL)
525 DEBUG("looking for export size with fstat\n");
526 stat_buf.st_size = 0;
527 error = fstat(export, &stat_buf);
528 if (!error && stat_buf.st_size > 0)
529 return (fsoffset_t)stat_buf.st_size;
532 DEBUG("looking for export size with ioctl BLKGETSIZE\n");
533 if (!ioctl(export, BLKGETSIZE, &es32) && es32) {
534 es = (fsoffset_t)es32 * (fsoffset_t)512;
538 err("Could not find size of exported block device: %m");
539 return (fsoffset_t)-1;
542 int main(int argc, char *argv[])
547 if (sizeof( struct nbd_request )!=28) {
548 fprintf(stderr,"Bad size of structure. Alignment problems?\n");
554 if (!port) return 1 ;
555 connectme(port); /* serve infinitely */
560 void serveconnection(int net)
564 for (i=0; i<exportsize; i+=hunksize) {
565 char exportname3[1024];
567 sprintf(exportname3, exportname2, i/hunksize);
568 printf( "Opening %s\n", exportname3 );
569 if ((export[i/hunksize] = open(exportname3, (flags & F_READONLY) ? O_RDONLY : O_RDWR)) == -1)
570 err("Could not open exported file: %m");
573 if (exportsize == (fsoffset_t)-1) {
574 exportsize = size_autodetect(export[0]);
576 if (exportsize > ((fsoffset_t)-1 >> 1)) {
578 if ((exportsize >> 10) > ((fsoffset_t)-1 >> 1))
579 msg3(LOG_INFO, "size of exported file/device is %LuMB",
580 (unsigned long long)(exportsize >> 20));
582 msg3(LOG_INFO, "size of exported file/device is %LuKB",
583 (unsigned long long)(exportsize >> 10));
586 err("Size of exported file is too big\n");
590 msg3(LOG_INFO, "size of exported file/device is %Lu",
591 (unsigned long long)exportsize);
593 if (flags & F_COPYONWRITE) {
594 sprintf(difffilename,"%s-%s-%d.diff",exportname2,clientname,
596 msg3(LOG_INFO,"About to create map and diff file %s",difffilename) ;
597 difffile=open(difffilename,O_RDWR | O_CREAT | O_TRUNC,0600) ;
598 if (difffile<0) err("Could not create diff file (%m)") ;
599 if ((difmap=calloc(exportsize/DIFFPAGESIZE,sizeof(u32)))==NULL)
600 err("Could not allocate memory") ;
601 for (i=0;i<exportsize/DIFFPAGESIZE;i++) difmap[i]=(u32)-1 ;