2 * Network Block Device - server
4 * Copyright 1996-1998 Pavel Machek, distribute under GPL
5 * <pavel@atrey.karlin.mff.cuni.cz>
6 * Copyright 2001-2004 Wouter Verhelst <wouter@debian.org>
7 * Copyright 2002 Anton Altaparmakov <aia21@cam.ac.uk>
9 * Version 1.0 - hopefully 64-bit-clean
10 * Version 1.1 - merging enhancements from Josh Parsons, <josh@coombs.anu.edu.au>
11 * Version 1.2 - autodetect size of block devices, thanx to Peter T. Breuer" <ptb@it.uc3m.es>
12 * Version 1.5 - can compile on Unix systems that don't have 64 bit integer
13 * type, or don't have 64 bit file offsets by defining FS_32BIT
14 * in compile options for nbd-server *only*. This can be done
15 * with make FSCHOICE=-DFS_32BIT nbd-server. (I don't have the
16 * original autoconf input file, or I would make it a configure
17 * option.) Ken Yap <ken@nlc.net.au>.
18 * Version 1.6 - fix autodetection of block device size and really make 64 bit
19 * clean on 32 bit machines. Anton Altaparmakov <aia21@cam.ac.uk>
20 * Version 2.0 - Version synchronised with client
21 * Version 2.1 - Reap zombie client processes when they exit. Removed
22 * (uncommented) the _IO magic, it's no longer necessary. Wouter
23 * Verhelst <wouter@debian.org>
24 * Version 2.2 - Auto switch to read-only mode (usefull for floppies).
25 * Version 2.3 - Fixed code so that Large File Support works. This
26 * removes the FS_32BIT compile-time directive; define
27 * _FILE_OFFSET_BITS=64 and _LARGEFILE_SOURCE if you used to be
28 * using FS_32BIT. This will allow you to use files >2GB instead of
29 * having to use the -m option. Wouter Verhelst <wouter@debian.org>
30 * Version 2.4 - Added code to keep track of children, so that we can
31 * properly kill them from initscripts. Add a call to daemon(),
32 * so that processes don't think they have to wait for us, which is
33 * interesting for initscripts as well. Wouter Verhelst
35 * Version 2.5 - Bugfix release: forgot to reset child_arraysize to
36 * zero after fork()ing, resulting in nbd-server going berserk
37 * when it receives a signal with at least one child open. Wouter
38 * Verhelst <wouter@debian.org>
39 * 10/10/2003 - Added socket option SO_KEEPALIVE (sf.net bug 819235);
40 * rectified type of mainloop::size_host (sf.net bugs 814435 and
41 * 817385); close the PID file after writing to it, so that the
42 * daemon can actually be found. Wouter Verhelst
44 * 10/10/2003 - Size of the data "size_host" was wrong and so was not
45 * correctly put in network endianness. Many types were corrected
46 * (size_t and off_t instead of int). <vspaceg@sourceforge.net>
47 * Version 2.6 - Some code cleanup.
48 * Version 2.7 - Better build system.
49 * 11/02/2004 - Doxygenified the source, modularized it a bit. Needs a
50 * lot more work, but this is a start. Wouter Verhelst
54 /* Includes LFS defines, which defines behaviours of some of the following
55 * headers, so must come before those */
58 #include <sys/types.h>
59 #include <sys/socket.h>
61 #include <sys/wait.h> /* wait */
62 #ifdef HAVE_SYS_IOCTL_H
63 #include <sys/ioctl.h>
65 #include <sys/param.h>
66 #ifdef HAVE_SYS_MOUNT_H
67 #include <sys/mount.h> /* For BLKGETSIZE */
69 #include <signal.h> /* sigaction */
70 #include <netinet/tcp.h>
71 #include <netinet/in.h> /* sockaddr_in, htons, in_addr */
72 #include <netdb.h> /* hostent, gethostby*, getservby* */
79 #include <arpa/inet.h>
87 /* used in cliserv.h, so must come first */
88 #define MY_NAME "nbd_server"
91 /** how much space for child PIDs we have by default. Dynamically
92 allocated, and will be realloc()ed if out of space, so this should
93 probably be fair for most situations. */
94 #define DEFAULT_CHILD_ARRAY 256
96 /** Logging macros, now nothing goes to syslog unless you say ISSERVER */
98 #define msg2(a,b) syslog(a,b)
99 #define msg3(a,b,c) syslog(a,b,c)
100 #define msg4(a,b,c,d) syslog(a,b,c,d)
102 #define msg2(a,b) g_message(b)
103 #define msg3(a,b,c) g_message(b,c)
104 #define msg4(a,b,c,d) g_message(b,c,d)
107 /* Debugging macros */
110 #define DEBUG( a ) printf( a )
111 #define DEBUG2( a,b ) printf( a,b )
112 #define DEBUG3( a,b,c ) printf( a,b,c )
115 #define DEBUG2( a,b )
116 #define DEBUG3( a,b,c )
118 #ifndef PACKAGE_VERSION
119 #define PACKAGE_VERSION ""
122 * The highest value a variable of type off_t can reach.
124 /* This is starting to get ugly. If someone knows a better way to find
125 * the maximum value of a signed type *without* relying on overflow
126 * (doing so breaks on 64bit architectures), that would be nice.
128 * Actually, do we need this at all? Can't we just say '0 is autodetect', and
129 * live with it? Or better yet, use an extra flag, or so?
131 #define OFFT_MAX (((((off_t)1)<<((sizeof(off_t)-1)*8))-1)<<7)+127
132 #define LINELEN 256 /**< Size of static buffer used to read the
133 authorization file (yuck) */
134 #define BUFSIZE (1024*1024) /**< Size of buffer that can hold requests */
135 #define GIGA (1*1024*1024*1024) /**< 1 Gigabyte. Used as hunksize when doing
136 the multiple file thingy */
137 #define DIFFPAGESIZE 4096 /**< diff file uses those chunks */
138 #define F_READONLY 1 /**< flag to tell us a file is readonly */
139 #define F_MULTIFILE 2 /**< flag to tell us a file is exported using -m */
140 #define F_COPYONWRITE 4 /**< flag to tell us a file is exported using copyonwrite */
141 #define F_AUTOREADONLY 8 /**< flag to tell us a file is set to autoreadonly */
142 GHashTable *children;
143 char pidfname[256]; /**< name of our PID file */
146 * Variables associated with a server.
149 char* exportname; /**< (unprocessed) filename of the file we're exporting */
150 off_t hunksize; /**< size of a hunk of an exported file */
151 off_t expected_size; /**< size of the exported file as it was told to
152 us through configuration */
153 unsigned int port; /**< port we're exporting this file at */
154 char* authname; /**< filename of the authorization file */
155 int flags; /**< flags associated with this exported file */
156 unsigned int timeout;/**< how long a connection may be idle
161 * Variables associated with a client socket.
164 off_t exportsize; /**< size of the file we're exporting */
165 char *clientname; /**< peer */
166 char *exportname; /**< (processed) filename of the file we're exporting */
167 int export[1024]; /**< array of filedescriptors of exported files;
168 only the first is actually used unless we're
169 doing the multiple file option */
170 int lastpoint; /**< For keeping track of where we are in a file.
171 This code is BUGGY currently, at least in
172 combination with the multiple file option. */
173 int net; /**< The actual client socket */
174 SERVER *server; /**< The server this client is getting data from */
175 char* difffilename; /**< filename of the copy-on-write file, if any */
176 int difffile; /**< filedescriptor of copyonwrite file. @todo
177 shouldn't this be an array too? (cfr
178 nbd_server_opts::export) Or make -m and -c
179 mutually exclusive */
180 u32 difffilelen; /**< number of pages in difffile */
181 u32 *difmap; /**< see comment on the global difmap for this one */
185 * Check whether a client is allowed to connect. Works with an authorization
186 * file which contains one line per machine, no wildcards.
188 * @param name IP address of client trying to connect (in human-readable form)
189 * @return 0 - authorization refused, 1 - OK
191 int authorized_client(CLIENT *opts) {
196 if ((f=fopen(opts->server->authname,"r"))==NULL) {
197 msg4(LOG_INFO,"Can't open authorization file %s (%s).",
198 opts->server->authname,strerror(errno)) ;
202 while (fgets(line,LINELEN,f)!=NULL) {
203 if (strncmp(line,opts->clientname,strlen(opts->clientname))==0) {
213 * Read data from a file descriptor into a buffer
215 * @param f a file descriptor
216 * @param buf a buffer
217 * @param len the number of bytes to be read
219 inline void readit(int f, void *buf, size_t len)
224 if ((res = read(f, buf, len)) <= 0)
225 err("Read failed: %m");
232 * Write data from a buffer into a filedescriptor
234 * @param f a file descriptor
235 * @param buf a buffer containing data
236 * @param len the number of bytes to be written
238 inline void writeit(int f, void *buf, size_t len)
243 if ((res = write(f, buf, len)) <= 0)
244 err("Send failed: %m");
251 * Print out a message about how to use nbd-server. Split out to a separate
252 * function so that we can call it from multiple places
255 printf("This is nbd-server version " VERSION "\n");
256 printf("Usage: port file_to_export [size][kKmM] [-r] [-m] [-c] [-a timeout_sec]\n"
258 " -m multiple file\n"
259 " -c copy on write\n"
260 " -l file with list of hosts that are allowed to connect.\n"
261 " -a maximum idle seconds, terminates when idle time exceeded\n"
262 " if port is set to 0, stdin is used (for running from inetd)\n"
263 " if file_to_export contains '%%s', it is substituted with IP\n"
264 " address of machine trying to connect\n" );
268 * Parse the command line.
270 * @todo getopt() is a great thing, and easy to use. Also, we want to
271 * create a configuration file which nbd-server will read. Maybe do (as in,
274 * @param argc the argc argument to main()
275 * @param argv the argv argument to main()
277 SERVER* cmdline(int argc, char *argv[]) {
280 struct option long_options[] = {
281 {"read-only", no_argument, NULL, 'r'},
282 {"multi-file", no_argument, NULL, 'm'},
283 {"copy-on-write", no_argument, NULL, 'c'},
284 {"authorize-file", required_argument, NULL, 'l'},
285 {"idle-time", required_argument, NULL, 'a'},
290 serve=g_malloc(sizeof(SERVER));
291 serve->hunksize=OFFT_MAX;
292 while((c=getopt_long(argc, argv, "a:cl:mr", long_options, &i))>=0) {
295 serve->flags |= F_READONLY;
298 serve->flags |= F_MULTIFILE;
299 serve->hunksize = 1*GIGA;
302 serve->flags |=F_COPYONWRITE;
305 serve->authname=optarg;
308 serve->timeout=strtol(optarg, NULL, 0);
316 /* What's left: the port to export, the name of the to be exported
317 * file, and, optionally, the size of the file, in that order. */
322 serve->port=strtol(argv[i], NULL, 0);
327 serve->exportname = argv[i];
330 size_t last = strlen(argv[i])-1;
331 char suffix = argv[i][last];
332 if (suffix == 'k' || suffix == 'K' ||
333 suffix == 'm' || suffix == 'M')
334 argv[i][last] = '\0';
335 es = (off_t)atol(argv[i]);
343 serve->expected_size = es;
349 * Signal handler for SIGCHLD
350 * @param s the signal we're handling (must be SIGCHLD, or something
353 void sigchld_handler(int s)
360 while((pid=wait(status)) > 0) {
361 if(WIFEXITED(status)) {
362 msg3(LOG_INFO, "Child exited with %d", WEXITSTATUS(status));
364 i=g_hash_table_lookup(children, &pid);
366 msg3(LOG_INFO, "SIGCHLD received for an unknown child with PID %ld", (long)pid);
368 DEBUG2("Removing %d from the list of children", pid);
369 g_hash_table_remove(children, &pid);
375 * Kill a child. Called from sigterm_handler::g_hash_table_foreach.
378 * @param value the value corresponding to the above key
379 * @param user_data a pointer which we always set to 1, so that we know what
382 void killchild(gpointer key, gpointer value, gpointer user_data) {
384 int *parent=user_data;
391 * Handle SIGTERM and dispatch it to our children
392 * @param s the signal we're handling (must be SIGTERM, or something
393 * is severely wrong).
395 void sigterm_handler(int s) {
399 g_hash_table_foreach(children, killchild, &parent);
409 * Detect the size of a file.
411 * @param export An open filedescriptor
412 * @return the size of the file, or OFFT_MAX if detection was
415 off_t size_autodetect(int export)
419 struct stat stat_buf;
422 #ifdef HAVE_SYS_MOUNT_H
423 #ifdef HAVE_SYS_IOCTL_H
425 DEBUG("looking for export size with ioctl BLKGETSIZE\n");
426 if (!ioctl(export, BLKGETSIZE, &es32) && es32) {
427 es = (off_t)es32 * (off_t)512;
430 #endif /* BLKGETSIZE */
431 #endif /* HAVE_SYS_IOCTL_H */
432 #endif /* HAVE_SYS_MOUNT_H */
434 DEBUG("looking for export size with fstat\n");
435 stat_buf.st_size = 0;
436 error = fstat(export, &stat_buf);
438 if(stat_buf.st_size > 0)
439 return (off_t)stat_buf.st_size;
441 err("fstat failed: %m");
444 DEBUG("looking for export size with lseek SEEK_END\n");
445 es = lseek(export, (off_t)0, SEEK_END);
446 if (es > ((off_t)0)) {
449 DEBUG2("lseek failed: %d", errno==EBADF?1:(errno==ESPIPE?2:(errno==EINVAL?3:4)));
452 err("Could not find size of exported block device: %m");
457 * Seek to a position in a file, unless we're already there.
458 * @param handle a filedescriptor
459 * @param a position to seek to
460 * @param client the client we're working for
462 void maybeseek(int handle, off_t a, CLIENT* client) {
463 if (a < 0 || a > client->exportsize) {
464 err("Can not happen\n");
466 if (client->lastpoint != a) {
467 if (lseek(handle, a, SEEK_SET) < 0) {
468 err("Can not seek locally!\n");
470 client->lastpoint = a;
477 * Write an amount of bytes at a given offset to the right file. This
478 * abstracts the write-side of the multiple file option.
480 * @param a The offset where the write should start
481 * @param buf The buffer to write from
482 * @param len The length of buf
483 * @return The number of bytes actually written, or -1 in case of an error
485 int rawexpwrite(off_t a, char *buf, size_t len, CLIENT *client)
489 maybeseek(client->export[a/client->server->hunksize],
490 a%client->server->hunksize, client);
491 res = write(client->export[a/client->server->hunksize], buf, len);
492 return (res < 0 || (size_t)res != len);
496 * seek to a position in a file, no matter what. Used when using maybeseek is a
497 * bad idea (for instance, because we're reading the copyonwrite file instead
498 * of the exported file).
499 * @param handle a filedescriptor
500 * @param a position to seek to
501 * @todo get rid of this; lastpoint is a global variable right now, but it
502 * shouldn't be. If we pass it on as a parameter, that makes things a *lot*
505 void myseek(int handle,off_t a) {
506 if (lseek(handle, a, SEEK_SET) < 0) {
507 err("Can not seek locally!\n");
512 * Read an amount of bytes at a given offset from the right file. This
513 * abstracts the read-side of the multiple files option.
515 * @param a The offset where the read should start
516 * @param buf A buffer to read into
517 * @param len The size of buf
518 * @return The number of bytes actually read, or -1 in case of an
521 int rawexpread(off_t a, char *buf, size_t len, CLIENT *client)
525 maybeseek(client->export[a/client->server->hunksize],
526 a%client->server->hunksize, client);
527 res = read(client->export[a/client->server->hunksize], buf, len);
528 return (res < 0 || (size_t)res != len);
532 * Read an amount of bytes at a given offset from the right file. This
533 * abstracts the read-side of the copyonwrite stuff, and calls
534 * rawexpread() with the right parameters to do the actual work.
535 * @param a The offset where the read should start
536 * @param buf A buffer to read into
537 * @param len The size of buf
538 * @return The number of bytes actually read, or -1 in case of an error
540 int expread(off_t a, char *buf, size_t len, CLIENT *client)
543 off_t mapcnt, mapl, maph, pagestart;
545 if (!(client->server->flags & F_COPYONWRITE))
546 return rawexpread(a, buf, len, client);
547 DEBUG3("Asked to read %d bytes at %Lu.\n", len, (unsigned long long)a);
549 mapl=a/DIFFPAGESIZE; maph=(a+len-1)/DIFFPAGESIZE;
551 for (mapcnt=mapl;mapcnt<=maph;mapcnt++) {
552 pagestart=mapcnt*DIFFPAGESIZE;
554 rdlen=(0<DIFFPAGESIZE-offset && len<(size_t)(DIFFPAGESIZE-offset)) ?
555 len : (size_t)DIFFPAGESIZE-offset;
556 if (client->difmap[mapcnt]!=(u32)(-1)) { /* the block is already there */
557 DEBUG3("Page %Lu is at %lu\n", (unsigned long long)mapcnt,
558 (unsigned long)(client->difmap[mapcnt]));
559 myseek(client->difffile, client->difmap[mapcnt]*DIFFPAGESIZE+offset);
560 if (read(client->difffile, buf, rdlen) != rdlen) return -1;
561 } else { /* the block is not there */
562 DEBUG2("Page %Lu is not here, we read the original one\n",
563 (unsigned long long)mapcnt);
564 return rawexpread(a, buf, rdlen, client);
566 len-=rdlen; a+=rdlen; buf+=rdlen;
572 * Write an amount of bytes at a given offset to the right file. This
573 * abstracts the write-side of the copyonwrite option, and calls
574 * rawexpwrite() with the right parameters to do the actual work.
576 * @param a The offset where the write should start
577 * @param buf The buffer to write from
578 * @param len The length of buf
579 * @return The number of bytes actually written, or -1 in case of an error
581 int expwrite(off_t a, char *buf, size_t len, CLIENT *client) {
582 char pagebuf[DIFFPAGESIZE];
583 off_t mapcnt,mapl,maph;
588 if (!(client->server->flags & F_COPYONWRITE))
589 return(rawexpwrite(a,buf,len, client));
590 DEBUG3("Asked to write %d bytes at %Lu.\n", len, (unsigned long long)a);
592 mapl=a/DIFFPAGESIZE ; maph=(a+len-1)/DIFFPAGESIZE ;
594 for (mapcnt=mapl;mapcnt<=maph;mapcnt++) {
595 pagestart=mapcnt*DIFFPAGESIZE ;
597 wrlen=(0<DIFFPAGESIZE-offset && len<(size_t)(DIFFPAGESIZE-offset)) ?
598 len : (size_t)DIFFPAGESIZE-offset;
600 if (client->difmap[mapcnt]!=(u32)(-1)) { /* the block is already there */
601 DEBUG3("Page %Lu is at %lu\n", (unsigned long long)mapcnt,
602 (unsigned long)(client->difmap[mapcnt])) ;
603 myseek(client->difffile,
604 client->difmap[mapcnt]*DIFFPAGESIZE+offset);
605 if (write(client->difffile, buf, wrlen) != wrlen) return -1 ;
606 } else { /* the block is not there */
607 myseek(client->difffile,client->difffilelen*DIFFPAGESIZE) ;
608 client->difmap[mapcnt]=client->difffilelen++ ;
609 DEBUG3("Page %Lu is not here, we put it at %lu\n",
610 (unsigned long long)mapcnt,
611 (unsigned long)(client->difmap[mapcnt]));
613 if (rdlen+pagestart%(client->server->hunksize) >
614 (client->server->hunksize))
615 rdlen=client->server->hunksize -
616 (pagestart%client->server->hunksize);
617 if (rawexpread(pagestart, pagebuf, rdlen, client))
619 memcpy(pagebuf+offset,buf,wrlen) ;
620 if (write(client->difffile, pagebuf, DIFFPAGESIZE) !=
624 len-=wrlen ; a+=wrlen ; buf+=wrlen ;
630 * Do the initial negotiation.
632 * @param net A socket to do the negotiation over
634 void negotiate(CLIENT *client) {
638 memset(zeros, 0, 290);
639 if (write(client->net, INIT_PASSWD, 8) < 0)
640 err("Negotiation failed: %m");
641 cliserv_magic = htonll(cliserv_magic);
642 if (write(client->net, &cliserv_magic, sizeof(cliserv_magic)) < 0)
643 err("Negotiation failed: %m");
644 size_host = htonll((u64)(client->exportsize));
645 if (write(client->net, &size_host, 8) < 0)
646 err("Negotiation failed: %m");
647 if (write(client->net, zeros, 128) < 0)
648 err("Negotiation failed: %m");
651 /** sending macro. */
652 #define SEND(net,reply) writeit( net, &reply, sizeof( reply ));
654 #define ERROR(client,reply) { reply.error = htonl(-1); SEND(client->net,reply); reply.error = 0; client->lastpoint = -1; }
656 * Serve a file to a single client.
658 * @todo This beast needs to be split up in many tiny little manageable
659 * pieces. Preferably with a chainsaw.
661 * @param net A network socket, connected to an nbd client
664 int mainloop(CLIENT *client)
666 struct nbd_request request;
667 struct nbd_reply reply;
672 DEBUG("Entering request loop!\n");
673 reply.magic = htonl(NBD_REPLY_MAGIC);
682 if (client->server->timeout)
683 alarm(client->server->timeout);
684 readit(client->net, &request, sizeof(request));
685 request.from = ntohll(request.from);
686 request.type = ntohl(request.type);
688 if (request.type==NBD_CMD_DISC) { /* Disconnect request */
689 if (client->difmap) free(client->difmap) ;
690 if (client->difffile>=0) {
691 close(client->difffile) ; unlink(client->difffilename) ; }
692 err("Disconnect request received.") ;
695 len = ntohl(request.len);
697 if (request.magic != htonl(NBD_REQUEST_MAGIC))
698 err("Not enough magic.");
700 err("Request too big!");
702 printf("%s from %Lu (%Lu) len %d, ", request.type ? "WRITE" :
703 "READ", (unsigned long long)request.from,
704 (unsigned long long)request.from / 512, len);
706 memcpy(reply.handle, request.handle, sizeof(reply.handle));
707 if ((request.from + len) > (OFFT_MAX)) {
708 DEBUG("[Number too large!]");
709 ERROR(client, reply);
713 if (((ssize_t)((off_t)request.from + len) > client->exportsize) ||
714 ((client->server->flags & F_READONLY) && request.type)) {
716 ERROR(client, reply);
720 if (request.type==1) { /* WRITE */
721 DEBUG("wr: net->buf, ");
722 readit(client->net, buf, len);
724 if ((client->server->flags & F_AUTOREADONLY) ||
725 expwrite(request.from, buf, len,
727 DEBUG("Write failed: %m" );
728 ERROR(client, reply);
731 client->lastpoint += len;
732 SEND(client->net, reply);
739 if (expread(request.from, buf + sizeof(struct nbd_reply), len, client)) {
740 client->lastpoint = -1;
741 DEBUG("Read failed: %m");
742 ERROR(client, reply);
745 client->lastpoint += len;
748 memcpy(buf, &reply, sizeof(struct nbd_reply));
749 writeit(client->net, buf, len + sizeof(struct nbd_reply));
755 * Split a single exportfile into multiple ones, if that was asked.
756 * @return 0 on success, -1 on failure
757 * @param client information on the client which we want to split
759 int splitexport(CLIENT* client) {
762 for (i=0; i<client->exportsize; i+=client->server->hunksize) {
765 if(client->server->flags & F_MULTIFILE) {
766 snprintf(tmpname, 1024, "%s.%d", client->exportname,
767 (int)(i/client->server->hunksize));
769 strncpy(tmpname, client->exportname, 1024);
772 DEBUG2( "Opening %s\n", tmpname );
773 if ((client->export[ i/ client->server->hunksize ] =
774 open(tmpname, (client->server->flags &
775 F_READONLY) ? O_RDONLY
777 /* Read WRITE ACCESS was requested by media is only read only */
778 client->server->flags |= F_AUTOREADONLY;
779 client->server->flags |= F_READONLY;
780 if ((client->export[i/client->server->hunksize] =
781 open(tmpname, O_RDONLY)) == -1)
782 err("Could not open exported file: %m");
786 if (client->server->flags & F_COPYONWRITE) {
787 snprintf(client->difffilename, 1024, "%s-%s-%d.diff",client->exportname,client->clientname,
789 client->difffilename[1023]='\0';
790 msg3(LOG_INFO,"About to create map and diff file %s",client->difffilename) ;
791 client->difffile=open(client->difffilename,O_RDWR | O_CREAT | O_TRUNC,0600) ;
792 if (client->difffile<0) err("Could not create diff file (%m)") ;
793 if ((client->difmap=calloc(client->exportsize/DIFFPAGESIZE,sizeof(u32)))==NULL)
794 err("Could not allocate memory") ;
795 for (i=0;i<client->exportsize/DIFFPAGESIZE;i++) client->difmap[i]=(u32)-1 ;
802 * Serve a connection.
804 * @todo allow for multithreading, perhaps use libevent.
806 * @param net A network socket connected to an nbd client
808 void serveconnection(CLIENT *client) {
811 if (!client->server->expected_size) {
812 client->exportsize = size_autodetect(client->export[0]);
814 /* Perhaps we should check first. Not now. */
815 client->exportsize = client->server->expected_size;
817 if (client->exportsize > OFFT_MAX) {
818 /* uhm, well... In a parallel universe, this *might* be
820 err("Size of exported file is too big\n");
823 msg3(LOG_INFO, "size of exported file/device is %Lu", (unsigned long long)client->exportsize);
826 setmysockopt(client->net);
832 * Find the name of the file we have to serve. This will use snprintf()
833 * to put the IP address of the client inside a filename containing
834 * "%s". That name is then written to exportname2
836 * @param net A socket connected to an nbd client
837 * @param client information about the client. The IP address in human-readable
838 * format will be written to a new char* buffer, the address of which will be
839 * stored in client->clientname.
841 void set_peername(int net, CLIENT *client) {
842 struct sockaddr_in addrin;
843 int addrinlen = sizeof( addrin );
846 if (getpeername(net, (struct sockaddr *) &addrin, (socklen_t *)&addrinlen) < 0)
847 err("getsockname failed: %m");
848 peername = inet_ntoa(addrin.sin_addr);
849 client->exportname=g_strdup_printf(client->server->exportname, peername);
851 msg4(LOG_INFO, "connect from %s, assigned file is %s",
852 peername, client->exportname);
853 strncpy(client->clientname,peername,255) ;
858 * @param data a pointer to pid_t which should be freed
860 void destroy_pid_t(gpointer data) {
865 * Connect the socket, and start to serve. This function will fork()
866 * if a connection from an authorized client is received, and will
869 * @todo modularize this giant beast. Preferably with a chainsaw. Also,
870 * it has no business starting mainloop(); it should connect, and be
873 * @param port the port where we will listen
875 void connectme(SERVER* serve) {
876 struct sockaddr_in addrin;
878 int addrinlen = sizeof(addrin);
879 int net, sock, newpid, i;
893 snprintf(pidfname, sizeof(char)*255, "/var/run/nbd-server.%d.pid", serve->port);
894 pidf=fopen(pidfname, "w");
896 fprintf(pidf,"%d", (int)getpid());
900 fprintf(stderr, "Not fatal; continuing");
904 #endif /* NODAEMON */
906 if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
909 /* lose the pesky "Address already in use" error message */
910 if (setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) {
911 err("setsockopt SO_REUSEADDR");
913 if (setsockopt(sock,SOL_SOCKET,SO_KEEPALIVE,&yes,sizeof(int)) == -1) {
914 err("setsockopt SO_KEEPALIVE");
917 DEBUG("Waiting for connections... bind, ");
918 addrin.sin_family = AF_INET;
919 addrin.sin_port = htons(serve->port);
920 addrin.sin_addr.s_addr = 0;
921 if (bind(sock, (struct sockaddr *) &addrin, addrinlen) < 0)
924 if (listen(sock, 1) < 0)
927 sa.sa_handler = sigchld_handler;
928 sigemptyset(&sa.sa_mask);
929 sa.sa_flags = SA_RESTART;
930 if(sigaction(SIGCHLD, &sa, NULL) == -1)
931 err("sigaction: %m");
932 sa.sa_handler = sigterm_handler;
933 sigemptyset(&sa.sa_mask);
934 sa.sa_flags = SA_RESTART;
935 if(sigaction(SIGTERM, &sa, NULL) == -1)
936 err("sigaction: %m");
937 children=g_hash_table_new_full(g_int_hash, g_int_equal, NULL, destroy_pid_t);
938 for(;;) { /* infinite loop */
942 if ((net = accept(sock, (struct sockaddr *) &addrin, &addrinlen)) < 0)
945 client = g_malloc(sizeof(CLIENT));
946 client->server=serve;
947 client->exportsize=OFFT_MAX;
949 set_peername(net, client);
950 if (!authorized_client(client)) {
951 msg2(LOG_INFO,"Unauthorized client") ;
955 msg2(LOG_INFO,"Authorized client") ;
956 pid=g_malloc(sizeof(pid_t));
958 if ((*pid=fork())<0) {
959 msg3(LOG_INFO,"Could not fork (%s)",strerror(errno)) ;
963 if (*pid>0) { /* parent */
965 g_hash_table_insert(children, pid, pid);
969 g_hash_table_destroy(children);
972 msg2(LOG_INFO,"Starting to serve") ;
973 serveconnection(client);
978 * Main entry point...
980 int main(int argc, char *argv[]) {
982 if (sizeof( struct nbd_request )!=28) {
983 fprintf(stderr,"Bad size of structure. Alignment problems?\n");
987 serve=cmdline(argc, argv);
989 if (!(serve->port)) {
992 /* You really should define ISSERVER if you're going to use inetd
993 * mode, but if you don't, closing stdout and stderr (which inetd
994 * had connected to the client socket) will let it work. */
997 open("/dev/null", O_WRONLY);
998 open("/dev/null", O_WRONLY);
1000 client=g_malloc(sizeof(CLIENT));
1001 client->server=serve;
1003 client->exportsize=OFFT_MAX;
1004 set_peername(0,client);
1008 connectme(serve); /* serve infinitely */