2 * Network Block Device - server
4 * Copyright 1996-1998 Pavel Machek, distribute under GPL
5 * <pavel@atrey.karlin.mff.cuni.cz>
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>.
19 #define GIGA (1*1024*1024*1024)
21 #include <sys/types.h>
22 #include <sys/socket.h>
24 #include <netinet/tcp.h>
25 #include <netinet/in.h> /* sockaddr_in, htons, in_addr */
26 #include <netdb.h> /* hostent, gethostby*, getservby* */
33 #include <arpa/inet.h>
38 #define MY_NAME "nbd_server"
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"
47 /* Deep magic: ioctl.h defines _IO macro (at least on linux) */
50 /* Debugging macros, now nothing goes to syslog unless you say 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)
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)
62 #include <sys/ioctl.h>
63 #include <sys/mount.h> /* For BLKGETSIZE */
66 typedef u32 fsoffset_t;
70 typedef u64 fsoffset_t;
76 #define DEBUG( a ) printf( a )
77 #define DEBUG2( a,b ) printf( a,b )
78 #define DEBUG3( a,b,c ) printf( a,b,c )
82 #define DEBUG3( a,b,c )
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);
90 void serveconnection(int net);
91 void set_peername(int net,char *clientname);
94 char difffilename[256];
95 unsigned int timeout = 0;
97 int authorized_client(char *name)
98 /* 0 - authorization refused, 1 - OK
99 authorization file contains one line per machine, no wildcards
105 if ((f=fopen(AUTH_FILE,"r"))==NULL)
106 { msg4(LOG_INFO,"Can't open authorization file %s (%s).",
107 AUTH_FILE,strerror(errno)) ;
111 while (fgets(line,LINELEN,f)!=NULL) {
112 if (strncmp(line,name,strlen(name))==0) { fclose(f) ; return 1 ; }
119 inline void readit(int f, void *buf, int len)
124 if ((res = read(f, buf, len)) <= 0)
125 err("Read failed: %m");
131 inline void writeit(int f, void *buf, int len)
136 if ((res = write(f, buf, len)) <= 0)
137 err("Write failed: %m");
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 */
149 u32 difffilelen=0 ; /* number of pages in difffile */
151 char clientname[256] ;
154 #define DIFFPAGESIZE 4096 /* diff file uses those chunks */
157 #define F_MULTIFILE 2
158 #define F_COPYONWRITE 4
160 void cmdline(int argc, char *argv[])
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"
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" );
176 port = atoi(argv[1]);
177 for (i = 3; i < argc; i++) {
178 if (*argv[i] == '-') {
179 switch (argv[i][1]) {
184 flags |= F_MULTIFILE;
187 case 'c': flags |=F_COPYONWRITE;
191 timeout = atoi(argv[i+1]);
194 fprintf(stderr, "timeout requires argument\n");
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]);
217 exportname = argv[2];
220 void connectme(int port)
222 struct sockaddr_in addrin;
223 int addrinlen = sizeof(addrin);
224 int net, sock, newpid;
231 if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
234 /* lose the pesky "Address already in use" error message */
235 if (setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) {
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)
246 if (listen(sock, 1) < 0)
249 for(;;) { /* infinite loop */
250 if ((net = accept(sock, (struct sockaddr *) &addrin, &addrinlen)) < 0)
253 set_peername(net,clientname) ;
254 if (!authorized_client(clientname)) {
255 msg2(LOG_INFO,"Unauthorized client") ;
259 msg2(LOG_INFO,"Authorized client") ;
260 if ((newpid=fork())<0) {
261 msg3(LOG_INFO,"Could not fork (%s)",strerror(errno)) ;
265 if (newpid>0) { /* parent */
266 close(net) ; continue ; }
269 msg2(LOG_INFO,"Starting to serve") ;
270 serveconnection(net) ;
274 #define SEND writeit( net, &reply, sizeof( reply ));
275 #define ERROR { reply.error = htonl(-1); SEND; reply.error = 0; lastpoint = -1; }
277 fsoffset_t lastpoint = -1;
279 void maybeseek(int handle, fsoffset_t a)
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)
287 if (lseek(handle, (long)a, SEEK_SET) < 0)
289 err("Can not seek locally!\n");
296 void myseek(int handle,fsoffset_t a)
298 #if HAVE_LLSEEK && !defined(FS_32BIT)
299 if (llseek(handle, a, SEEK_SET) < 0)
301 if (lseek(handle, (long)a, SEEK_SET) < 0)
303 err("Can not seek locally!\n");
306 char pagebuf[DIFFPAGESIZE] ;
309 int rawexpread(fsoffset_t a, char *buf, int len)
311 maybeseek(export[a/hunksize], a%hunksize);
312 return (read(export[a/hunksize], buf, len) != len);
315 int expread(fsoffset_t a, char *buf, int len)
316 { int rdlen ; fsoffset_t mapcnt,mapl,maph ;
317 fsoffset_t pagestart; int offset ;
319 if (flags & F_COPYONWRITE) {
320 DEBUG3("Asked to read %d bytes at %lu.\n",len,(unsigned long)a) ;
322 mapl=a/DIFFPAGESIZE ; maph=(a+len-1)/DIFFPAGESIZE ;
324 for (mapcnt=mapl;mapcnt<=maph;mapcnt++) {
325 pagestart=mapcnt*DIFFPAGESIZE ;
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",
335 if (rawexpread(a,buf,rdlen)) return -1 ;
337 len-=rdlen ; a+=rdlen ; buf+=rdlen ;
339 } else return rawexpread(a,buf,len) ;
343 int rawexpwrite(fsoffset_t a, char *buf, int len)
345 maybeseek(export[a/hunksize], a%hunksize);
346 return (write(export[a/hunksize], buf, len) != len);
350 int expwrite(fsoffset_t a, char *buf, int len)
351 { u32 mapcnt,mapl,maph ; int wrlen,rdlen ;
352 fsoffset_t pagestart ; int offset ;
354 if (flags & F_COPYONWRITE) {
355 DEBUG3("Asked to write %d bytes at %lu.\n",len,(unsigned long)a) ;
357 mapl=a/DIFFPAGESIZE ; maph=(a+len-1)/DIFFPAGESIZE ;
359 for (mapcnt=mapl;mapcnt<=maph;mapcnt++) {
360 pagestart=mapcnt*DIFFPAGESIZE ;
362 wrlen=(len<DIFFPAGESIZE-offset) ? len : DIFFPAGESIZE-offset ;
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]) ;
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 ;
381 len-=wrlen ; a+=wrlen ; buf+=wrlen ;
383 } else return(rawexpwrite(a,buf,len));
387 int mainloop(int net)
389 struct nbd_request request;
390 struct nbd_reply reply;
393 fsoffset_t size_host;
395 memset(zeros, 0, 290);
396 if (write(net, INIT_PASSWD, 8) < 0)
397 err("Negotiation failed: %m");
399 cliserv_magic = htonll(cliserv_magic);
401 if (write(net, &cliserv_magic, sizeof(cliserv_magic)) < 0)
402 err("Negotiation failed: %m");
403 size_host = htonll(exportsize);
405 if (write(net, zeros, 4) < 0 || write(net, &size_host, 4) < 0)
407 if (write(net, &size_host, 8) < 0)
409 err("Negotiation failed: %m");
410 if (write(net, zeros, 128) < 0)
411 err("Negotiation failed: %m");
413 DEBUG("Entering request loop!\n");
414 reply.magic = htonl(NBD_REPLY_MAGIC);
417 #define BUFSIZE (1024*1024)
428 readit(net, &request, sizeof(request));
429 request.from = ntohll(request.from);
430 request.type = ntohl(request.type);
432 if (request.type==2) { /* Disconnect request */
433 if (difmap) free(difmap) ;
435 close(difffile) ; unlink(difffilename) ; }
436 err("Disconnect request received.") ;
439 len = ntohl(request.len);
441 if (request.magic != htonl(NBD_REQUEST_MAGIC))
442 err("Not enough magic.");
444 err("Request too big!");
446 printf("%s from %d (%d) len %d, ", (request.type ? "WRITE" : "READ"),
447 (int) request.from, (int) request.from / 512, len);
449 memcpy(reply.handle, request.handle, sizeof(reply.handle));
450 if (((request.from + len) > exportsize) ||
451 ((flags & F_READONLY) && request.type)) {
456 if (request.type==1) { /* WRITE */
457 DEBUG("wr: net->buf, ");
458 readit(net, buf, len);
460 if (expwrite(request.from, buf, len)) {
461 DEBUG("Write failed: %m" );
472 if (expread(request.from, buf + sizeof(struct nbd_reply), len)) {
474 DEBUG("Read failed: %m");
481 memcpy(buf, &reply, sizeof(struct nbd_reply));
482 writeit(net, buf, len + sizeof(struct nbd_reply));
487 char exportname2[1024];
489 void set_peername(int net,char *clientname)
491 struct sockaddr_in addrin;
492 int addrinlen = sizeof( addrin );
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);
500 msg4(LOG_INFO, "connect from %s, assigned file is %s", peername, exportname2);
501 strncpy(clientname,peername,255) ;
504 fsoffset_t size_autodetect(int export)
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;
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");
516 if(ioctl(export, BLKGETSIZE, &es) || es == 0) {
520 err("Could not find size of exported block device: %m");
522 es *= 512; /* assume blocksize 512 */
525 es = stat_buf.st_size;
531 int main(int argc, char *argv[])
536 if (sizeof( struct nbd_request )!=28) {
537 fprintf(stderr,"Bad size of structure. Alignment problems?\n");
543 if (!port) return 1 ;
544 connectme(port); /* serve infinitely */
549 void serveconnection(int net)
553 for (i=0; i<exportsize; i+=hunksize) {
554 char exportname3[1024];
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");
562 if (exportsize == (u64)~0) {
563 exportsize = size_autodetect(export[0]);
565 if (exportsize > (~0UL >> 1))
567 if ((exportsize >> 10) > (~0UL >> 1))
568 msg3(LOG_INFO, "size of exported file/device is %luMB",
569 (unsigned long)(exportsize >> 20));
571 msg3(LOG_INFO, "size of exported file/device is %luKB",
572 (unsigned long)(exportsize >> 10));
574 err("Size of exported file is too big\n");
577 msg3(LOG_INFO, "size of exported file/device is %lu",
578 (unsigned long)exportsize);
580 if (flags & F_COPYONWRITE) {
581 sprintf(difffilename,"%s-%s-%d.diff",exportname2,clientname,
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 ;