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>
22 #define GIGA (1*1024*1024*1024)
24 #include <sys/types.h>
25 #include <sys/socket.h>
27 #include <netinet/tcp.h>
28 #include <netinet/in.h> /* sockaddr_in, htons, in_addr */
29 #include <netdb.h> /* hostent, gethostby*, getservby* */
36 #include <arpa/inet.h>
41 #define MY_NAME "nbd_server"
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"
50 /* Deep magic: ioctl.h defines _IO macro (at least on linux) */
53 /* Debugging macros, now nothing goes to syslog unless you say 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)
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)
65 #include <sys/ioctl.h>
66 #include <sys/mount.h> /* For BLKGETSIZE */
69 typedef u32 fsoffset_t;
73 typedef u64 fsoffset_t;
79 #define DEBUG( a ) printf( a )
80 #define DEBUG2( a,b ) printf( a,b )
81 #define DEBUG3( a,b,c ) printf( a,b,c )
85 #define DEBUG3( a,b,c )
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);
93 void serveconnection(int net);
94 void set_peername(int net,char *clientname);
97 char difffilename[256];
98 unsigned int timeout = 0;
100 int authorized_client(char *name)
101 /* 0 - authorization refused, 1 - OK
102 authorization file contains one line per machine, no wildcards
108 if ((f=fopen(AUTH_FILE,"r"))==NULL)
109 { msg4(LOG_INFO,"Can't open authorization file %s (%s).",
110 AUTH_FILE,strerror(errno)) ;
114 while (fgets(line,LINELEN,f)!=NULL) {
115 if (strncmp(line,name,strlen(name))==0) { fclose(f) ; return 1 ; }
122 inline void readit(int f, void *buf, int len)
127 if ((res = read(f, buf, len)) <= 0)
128 err("Read failed: %m");
134 inline void writeit(int f, void *buf, int len)
139 if ((res = write(f, buf, len)) <= 0)
140 err("Write failed: %m");
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;
153 u32 difffilelen=0 ; /* number of pages in difffile */
155 char clientname[256] ;
158 #define DIFFPAGESIZE 4096 /* diff file uses those chunks */
161 #define F_MULTIFILE 2
162 #define F_COPYONWRITE 4
164 void cmdline(int argc, char *argv[])
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"
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" );
180 port = atoi(argv[1]);
181 for (i = 3; i < argc; i++) {
182 if (*argv[i] == '-') {
183 switch (argv[i][1]) {
188 flags |= F_MULTIFILE;
191 case 'c': flags |=F_COPYONWRITE;
195 timeout = atoi(argv[i+1]);
198 fprintf(stderr, "timeout requires argument\n");
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]);
221 exportname = argv[2];
224 void connectme(int port)
226 struct sockaddr_in addrin;
227 int addrinlen = sizeof(addrin);
228 int net, sock, newpid;
235 if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
238 /* lose the pesky "Address already in use" error message */
239 if (setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) {
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)
250 if (listen(sock, 1) < 0)
253 for(;;) { /* infinite loop */
254 if ((net = accept(sock, (struct sockaddr *) &addrin, &addrinlen)) < 0)
257 set_peername(net,clientname) ;
258 if (!authorized_client(clientname)) {
259 msg2(LOG_INFO,"Unauthorized client") ;
263 msg2(LOG_INFO,"Authorized client") ;
264 if ((newpid=fork())<0) {
265 msg3(LOG_INFO,"Could not fork (%s)",strerror(errno)) ;
269 if (newpid>0) { /* parent */
270 close(net) ; continue ; }
273 msg2(LOG_INFO,"Starting to serve") ;
274 serveconnection(net) ;
278 #define SEND writeit( net, &reply, sizeof( reply ));
279 #define ERROR { reply.error = htonl(-1); SEND; reply.error = 0; lastpoint = -1; }
281 fsoffset_t lastpoint = (fsoffset_t)-1;
283 void maybeseek(int handle, fsoffset_t a)
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)
291 if (lseek(handle, (long)a, SEEK_SET) < 0)
293 err("Can not seek locally!\n");
300 void myseek(int handle,fsoffset_t a)
302 #if HAVE_LLSEEK && !defined(FS_32BIT)
303 if (llseek(handle, a, SEEK_SET) < 0)
305 if (lseek(handle, (long)a, SEEK_SET) < 0)
307 err("Can not seek locally!\n");
310 char pagebuf[DIFFPAGESIZE] ;
313 int rawexpread(fsoffset_t a, char *buf, int len)
315 maybeseek(export[a/hunksize], a%hunksize);
316 return (read(export[a/hunksize], buf, len) != len);
319 int expread(fsoffset_t a, char *buf, int len)
322 fsoffset_t mapcnt, mapl, maph, pagestart;
324 if (flags & F_COPYONWRITE) {
325 DEBUG3("Asked to read %d bytes at %Lu.\n", len, (unsigned long long)a);
327 mapl=a/DIFFPAGESIZE ; maph=(a+len-1)/DIFFPAGESIZE ;
329 for (mapcnt=mapl;mapcnt<=maph;mapcnt++) {
330 pagestart=mapcnt*DIFFPAGESIZE ;
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 ;
343 len-=rdlen ; a+=rdlen ; buf+=rdlen ;
345 } else return rawexpread(a,buf,len) ;
349 int rawexpwrite(fsoffset_t a, char *buf, int len)
351 maybeseek(export[a/hunksize], a%hunksize);
352 return (write(export[a/hunksize], buf, len) != len);
356 int expwrite(fsoffset_t a, char *buf, int len)
357 { u32 mapcnt,mapl,maph ; int wrlen,rdlen ;
358 fsoffset_t pagestart ; int offset ;
360 if (flags & F_COPYONWRITE) {
361 DEBUG3("Asked to write %d bytes at %Lu.\n", len, (unsigned long long)a);
363 mapl=a/DIFFPAGESIZE ; maph=(a+len-1)/DIFFPAGESIZE ;
365 for (mapcnt=mapl;mapcnt<=maph;mapcnt++) {
366 pagestart=mapcnt*DIFFPAGESIZE ;
368 wrlen=(len<DIFFPAGESIZE-offset) ? len : DIFFPAGESIZE-offset ;
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]);
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 ;
388 len-=wrlen ; a+=wrlen ; buf+=wrlen ;
390 } else return(rawexpwrite(a,buf,len));
394 int mainloop(int net)
396 struct nbd_request request;
397 struct nbd_reply reply;
400 fsoffset_t size_host;
402 memset(zeros, 0, 290);
403 if (write(net, INIT_PASSWD, 8) < 0)
404 err("Negotiation failed: %m");
406 cliserv_magic = htonll(cliserv_magic);
408 if (write(net, &cliserv_magic, sizeof(cliserv_magic)) < 0)
409 err("Negotiation failed: %m");
410 size_host = htonll(exportsize);
412 if (write(net, zeros, 4) < 0 || write(net, &size_host, 4) < 0)
414 if (write(net, &size_host, 8) < 0)
416 err("Negotiation failed: %m");
417 if (write(net, zeros, 128) < 0)
418 err("Negotiation failed: %m");
420 DEBUG("Entering request loop!\n");
421 reply.magic = htonl(NBD_REPLY_MAGIC);
424 #define BUFSIZE (1024*1024)
435 readit(net, &request, sizeof(request));
436 request.from = ntohll(request.from);
437 request.type = ntohl(request.type);
439 if (request.type==2) { /* Disconnect request */
440 if (difmap) free(difmap) ;
442 close(difffile) ; unlink(difffilename) ; }
443 err("Disconnect request received.") ;
446 len = ntohl(request.len);
448 if (request.magic != htonl(NBD_REQUEST_MAGIC))
449 err("Not enough magic.");
451 err("Request too big!");
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);
457 memcpy(reply.handle, request.handle, sizeof(reply.handle));
458 if (((request.from + len) > exportsize) ||
459 ((flags & F_READONLY) && request.type)) {
464 if (request.type==1) { /* WRITE */
465 DEBUG("wr: net->buf, ");
466 readit(net, buf, len);
468 if (expwrite(request.from, buf, len)) {
469 DEBUG("Write failed: %m" );
480 if (expread(request.from, buf + sizeof(struct nbd_reply), len)) {
482 DEBUG("Read failed: %m");
489 memcpy(buf, &reply, sizeof(struct nbd_reply));
490 writeit(net, buf, len + sizeof(struct nbd_reply));
495 char exportname2[1024];
497 void set_peername(int net,char *clientname)
499 struct sockaddr_in addrin;
500 int addrinlen = sizeof( addrin );
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);
508 msg4(LOG_INFO, "connect from %s, assigned file is %s", peername, exportname2);
509 strncpy(clientname,peername,255) ;
512 fsoffset_t size_autodetect(int export)
516 struct stat stat_buf;
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)
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;
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;
537 err("Could not find size of exported block device: %m");
538 return (fsoffset_t)-1;
541 int main(int argc, char *argv[])
546 if (sizeof( struct nbd_request )!=28) {
547 fprintf(stderr,"Bad size of structure. Alignment problems?\n");
553 if (!port) return 1 ;
554 connectme(port); /* serve infinitely */
559 void serveconnection(int net)
563 for (i=0; i<exportsize; i+=hunksize) {
564 char exportname3[1024];
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");
572 if (exportsize == (fsoffset_t)-1) {
573 exportsize = size_autodetect(export[0]);
575 if (exportsize > ((fsoffset_t)-1 >> 1)) {
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));
581 msg3(LOG_INFO, "size of exported file/device is %LuKB",
582 (unsigned long long)(exportsize >> 10));
585 err("Size of exported file is too big\n");
589 msg3(LOG_INFO, "size of exported file/device is %Lu",
590 (unsigned long long)exportsize);
592 if (flags & F_COPYONWRITE) {
593 sprintf(difffilename,"%s-%s-%d.diff",exportname2,clientname,
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 ;