r100: Bring comment in sync with reality
[nbd.git] / nbd-server.c
1 /*
2  * Network Block Device - server
3  *
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>
8  *
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
34  *      <wouter@debian.org>
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
43  *      <wouter@debian.org>
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
51  *      <wouter@debian.org>
52  */
53
54 /* Includes LFS defines, which defines behaviours of some of the following
55  * headers, so must come before those */
56 #include "lfs.h"
57
58 #include <sys/types.h>
59 #include <sys/socket.h>
60 #include <sys/stat.h>
61 #include <sys/wait.h>           /* wait */
62 #ifdef HAVE_SYS_IOCTL_H
63 #include <sys/ioctl.h>
64 #endif
65 #include <sys/param.h>
66 #ifdef HAVE_SYS_MOUNT_H
67 #include <sys/mount.h>          /* For BLKGETSIZE */
68 #endif
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* */
73 #include <syslog.h>
74 #include <unistd.h>
75 #include <stdio.h>
76 #include <stdlib.h>
77 #include <string.h>
78 #include <fcntl.h>
79 #include <arpa/inet.h>
80 #include <strings.h>
81 #include <dirent.h>
82 #include <unistd.h>
83 #include <getopt.h>
84
85 #include <glib.h>
86
87 /* used in cliserv.h, so must come first */
88 #define MY_NAME "nbd_server"
89 #include "cliserv.h"
90
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
95
96 /** Logging macros, now nothing goes to syslog unless you say ISSERVER */
97 #ifdef 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)
101 #else
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)
105 #endif
106
107 /* Debugging macros */
108 //#define DODBG
109 #ifdef DODBG
110 #define DEBUG( a ) printf( a )
111 #define DEBUG2( a,b ) printf( a,b )
112 #define DEBUG3( a,b,c ) printf( a,b,c )
113 #else
114 #define DEBUG( a )
115 #define DEBUG2( a,b ) 
116 #define DEBUG3( a,b,c ) 
117 #endif
118 #ifndef PACKAGE_VERSION
119 #define PACKAGE_VERSION ""
120 #endif
121 /**
122  * The highest value a variable of type off_t can reach.
123  **/
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.
127  *
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?
130  * Answer: yes, we need it, as the hunksize is defined to this when the
131  * multiple file thingy isn't used.
132  */
133 #define OFFT_MAX (((((off_t)1)<<((sizeof(off_t)-1)*8))-1)<<7)+127
134 #define LINELEN 256       /**< Size of static buffer used to read the
135                             authorization file (yuck) */
136 #define BUFSIZE (1024*1024) /**< Size of buffer that can hold requests */
137 #define GIGA (1*1024*1024*1024) /**< 1 Gigabyte. Used as hunksize when doing
138                                   the multiple file thingy. @todo: make this a
139                                   configuration option. */
140 #define DIFFPAGESIZE 4096 /**< diff file uses those chunks */
141 #define F_READONLY 1      /**< flag to tell us a file is readonly */
142 #define F_MULTIFILE 2     /**< flag to tell us a file is exported using -m */
143 #define F_COPYONWRITE 4   /**< flag to tell us a file is exported using
144                             copyonwrite */
145 #define F_AUTOREADONLY 8  /**< flag to tell us a file is set to autoreadonly */
146 GHashTable *children;
147 char pidfname[256]; /**< name of our PID file */
148
149 /**
150  * Variables associated with a server.
151  **/
152 typedef struct {
153         char* exportname;    /**< (unprocessed) filename of the file we're exporting */
154         off_t hunksize;      /**< size of a hunk of an exported file */
155         off_t expected_size; /**< size of the exported file as it was told to
156                                us through configuration */
157         unsigned int port;   /**< port we're exporting this file at */
158         char* authname;      /**< filename of the authorization file */
159         int flags;           /**< flags associated with this exported file */
160         unsigned int timeout;/**< how long a connection may be idle
161                                (0=forever) */
162         int socket;          /**< The socket of this server. */
163 } SERVER;
164
165 /**
166  * Variables associated with a client socket.
167  **/
168 typedef struct {
169         off_t exportsize;    /**< size of the file we're exporting */
170         char *clientname;    /**< peer */
171         char *exportname;    /**< (processed) filename of the file we're exporting */
172         int export[1024];    /**< array of filedescriptors of exported files;
173                                only the first is actually used unless we're
174                                doing the multiple file option */
175         int net;             /**< The actual client socket */
176         SERVER *server;      /**< The server this client is getting data from */
177         char* difffilename;  /**< filename of the copy-on-write file, if any */
178         int difffile;        /**< filedescriptor of copyonwrite file. @todo
179                                shouldn't this be an array too? (cfr export) Or
180                                make -m and -c mutually exclusive */
181         u32 difffilelen;     /**< number of pages in difffile */
182         u32 *difmap;         /**< see comment on the global difmap for this one */
183 } CLIENT;
184
185 /**
186  * Check whether a client is allowed to connect. Works with an authorization
187  * file which contains one line per machine, no wildcards.
188  *
189  * @param name IP address of client trying to connect (in human-readable form)
190  * @return 0 - authorization refused, 1 - OK
191  **/
192 int authorized_client(CLIENT *opts) {
193         FILE *f ;
194    
195         char line[LINELEN]; 
196
197         if ((f=fopen(opts->server->authname,"r"))==NULL) {
198                 msg4(LOG_INFO,"Can't open authorization file %s (%s).",
199                      opts->server->authname,strerror(errno)) ;
200                 return 1 ; 
201         }
202   
203         while (fgets(line,LINELEN,f)!=NULL) {
204                 if (strncmp(line,opts->clientname,strlen(opts->clientname))==0) {
205                         fclose(f);
206                         return 1;
207                 }
208         }
209         fclose(f) ;
210         return 0 ;
211 }
212
213 /**
214  * Read data from a file descriptor into a buffer
215  *
216  * @param f a file descriptor
217  * @param buf a buffer
218  * @param len the number of bytes to be read
219  **/
220 inline void readit(int f, void *buf, size_t len) {
221         ssize_t res;
222         while (len > 0) {
223                 DEBUG("*");
224                 if ((res = read(f, buf, len)) <= 0)
225                         err("Read failed: %m");
226                 len -= res;
227                 buf += res;
228         }
229 }
230
231 /**
232  * Write data from a buffer into a filedescriptor
233  *
234  * @param f a file descriptor
235  * @param buf a buffer containing data
236  * @param len the number of bytes to be written
237  **/
238 inline void writeit(int f, void *buf, size_t len) {
239         ssize_t res;
240         while (len > 0) {
241                 DEBUG("+");
242                 if ((res = write(f, buf, len)) <= 0)
243                         err("Send failed: %m");
244                 len -= res;
245                 buf += res;
246         }
247 }
248
249 /**
250  * Print out a message about how to use nbd-server. Split out to a separate
251  * function so that we can call it from multiple places
252  */
253 void usage() {
254         printf("This is nbd-server version " VERSION "\n");
255         printf("Usage: port file_to_export [size][kKmM] [-l authorize_file] [-r] [-m] [-c] [-a timeout_sec]\n"
256                "\t-r|--read-only\t\tread only\n"
257                "\t-m|--multi-file\t\tmultiple file\n"
258                "\t-c|--copy-on-write\tcopy on write\n"
259                "\t-l|--authorize-file\tfile with list of hosts that are allowed to\n\t\t\t\tconnect.\n"
260                "\t-a|--idle-time\t\tmaximum idle seconds; server terminates when\n\t\t\t\tidle time exceeded\n\n"
261                "\tif port is set to 0, stdin is used (for running from inetd)\n"
262                "\tif file_to_export contains '%%s', it is substituted with the IP\n"
263                "\t\taddress of the machine trying to connect\n" );
264 }
265
266 /**
267  * Parse the command line.
268  *
269  * @todo getopt() is a great thing, and easy to use. Also, we want to
270  * create a configuration file which nbd-server will read. Maybe do (as in,
271  * parse) that here.
272  *
273  * @param argc the argc argument to main()
274  * @param argv the argv argument to main()
275  **/
276 SERVER* cmdline(int argc, char *argv[]) {
277         int i=0;
278         int c;
279         struct option long_options[] = {
280                 {"read-only", no_argument, NULL, 'r'},
281                 {"multi-file", no_argument, NULL, 'm'},
282                 {"copy-on-write", no_argument, NULL, 'c'},
283                 {"authorize-file", required_argument, NULL, 'l'},
284                 {"idle-time", required_argument, NULL, 'a'},
285                 {0,0,0,0}
286         };
287         SERVER *serve;
288
289         serve=g_malloc(sizeof(SERVER));
290         serve->hunksize=OFFT_MAX;
291         while((c=getopt_long(argc, argv, "a:cl:mr", long_options, &i))>=0) {
292                 switch (c) {
293                 case 'r':
294                         serve->flags |= F_READONLY;
295                         break;
296                 case 'm':
297                         serve->flags |= F_MULTIFILE;
298                         serve->hunksize = 1*GIGA;
299                         break;
300                 case 'c': 
301                         serve->flags |=F_COPYONWRITE;
302                         break;
303                 case 'l':
304                         serve->authname=optarg;
305                         break;
306                 case 'a': 
307                         serve->timeout=strtol(optarg, NULL, 0);
308                         break;
309                 default:
310                         usage();
311                         exit(0);
312                         break;
313                 }
314         }
315         /* What's left: the port to export, the name of the to be exported
316          * file, and, optionally, the size of the file, in that order. */
317         if(++i>=argc) {
318                 usage();
319                 exit(0);
320         } 
321         serve->port=strtol(argv[i], NULL, 0);
322         if(++i>=argc) {
323                 usage();
324                 exit(0);
325         }
326         serve->exportname = argv[i];
327         if(++i<argc) {
328                 off_t es;
329                 size_t last = strlen(argv[i])-1;
330                 char suffix = argv[i][last];
331                 if (suffix == 'k' || suffix == 'K' ||
332                     suffix == 'm' || suffix == 'M')
333                         argv[i][last] = '\0';
334                 es = (off_t)atol(argv[i]);
335                 switch (suffix) {
336                         case 'm':
337                         case 'M':  es <<= 10;
338                         case 'k':
339                         case 'K':  es <<= 10;
340                         default :  break;
341                 }
342                 serve->expected_size = es;
343         }
344         return serve;
345 }
346
347 /**
348  * Signal handler for SIGCHLD
349  * @param s the signal we're handling (must be SIGCHLD, or something
350  * is severely wrong)
351  **/
352 void sigchld_handler(int s) {
353         int* status=NULL;
354         int* i;
355         char buf[80];
356         pid_t pid;
357
358         while((pid=wait(status)) > 0) {
359                 if(WIFEXITED(status)) {
360                         msg3(LOG_INFO, "Child exited with %d", WEXITSTATUS(status));
361                 }
362                 i=g_hash_table_lookup(children, &pid);
363                 if(!i) {
364                         msg3(LOG_INFO, "SIGCHLD received for an unknown child with PID %ld", (long)pid);
365                 } else {
366                         DEBUG2("Removing %d from the list of children", pid);
367                         g_hash_table_remove(children, &pid);
368                 }
369         }
370 }
371
372 /**
373  * Kill a child. Called from sigterm_handler::g_hash_table_foreach.
374  *
375  * @param key the key
376  * @param value the value corresponding to the above key
377  * @param user_data a pointer which we always set to 1, so that we know what
378  * will happen next.
379  **/
380 void killchild(gpointer key, gpointer value, gpointer user_data) {
381         pid_t *pid=value;
382         int *parent=user_data;
383
384         kill(*pid, SIGTERM);
385         *parent=1;
386 }
387
388 /**
389  * Handle SIGTERM and dispatch it to our children
390  * @param s the signal we're handling (must be SIGTERM, or something
391  * is severely wrong).
392  **/
393 void sigterm_handler(int s) {
394         int i;
395         int parent=0;
396
397         g_hash_table_foreach(children, killchild, &parent);
398
399         if(parent) {
400                 unlink(pidfname);
401         }
402
403         exit(0);
404 }
405
406 /**
407  * Detect the size of a file.
408  *
409  * @param export An open filedescriptor
410  * @return the size of the file, or OFFT_MAX if detection was
411  * impossible.
412  **/
413 off_t size_autodetect(int export) {
414         off_t es;
415         u32 es32;
416         struct stat stat_buf;
417         int error;
418
419 #ifdef HAVE_SYS_MOUNT_H
420 #ifdef HAVE_SYS_IOCTL_H
421 #ifdef BLKGETSIZE
422         DEBUG("looking for export size with ioctl BLKGETSIZE\n");
423         if (!ioctl(export, BLKGETSIZE, &es32) && es32) {
424                 es = (off_t)es32 * (off_t)512;
425                 return es;
426         }
427 #endif /* BLKGETSIZE */
428 #endif /* HAVE_SYS_IOCTL_H */
429 #endif /* HAVE_SYS_MOUNT_H */
430
431         DEBUG("looking for export size with fstat\n");
432         stat_buf.st_size = 0;
433         error = fstat(export, &stat_buf);
434         if (!error) {
435                 if(stat_buf.st_size > 0)
436                         return (off_t)stat_buf.st_size;
437         } else {
438                 err("fstat failed: %m");
439         }
440
441         DEBUG("looking for export size with lseek SEEK_END\n");
442         es = lseek(export, (off_t)0, SEEK_END);
443         if (es > ((off_t)0)) {
444                 return es;
445         } else {
446                 DEBUG2("lseek failed: %d", errno==EBADF?1:(errno==ESPIPE?2:(errno==EINVAL?3:4)));
447         }
448
449         err("Could not find size of exported block device: %m");
450         return OFFT_MAX;
451 }
452
453 /**
454  * seek to a position in a file, with error handling.
455  * @param handle a filedescriptor
456  * @param a position to seek to
457  * @todo get rid of this; lastpoint is a global variable right now, but it
458  * shouldn't be. If we pass it on as a parameter, that makes things a *lot*
459  * easier.
460  **/
461 void myseek(int handle,off_t a) {
462         if (lseek(handle, a, SEEK_SET) < 0) {
463                 err("Can not seek locally!\n");
464         }
465 }
466
467 /**
468  * Write an amount of bytes at a given offset to the right file. This
469  * abstracts the write-side of the multiple file option.
470  *
471  * @param a The offset where the write should start
472  * @param buf The buffer to write from
473  * @param len The length of buf
474  * @return The number of bytes actually written, or -1 in case of an error
475  **/
476 int rawexpwrite(off_t a, char *buf, size_t len, CLIENT *client) {
477         ssize_t res;
478
479         myseek(client->export[(int)a/client->server->hunksize],
480                         a%client->server->hunksize);
481         res = write(client->export[(int)((off_t)a/(off_t)(client->server->hunksize))], buf, len);
482         return (res < 0 || (size_t)res != len);
483 }
484
485 /**
486  * Read an amount of bytes at a given offset from the right file. This
487  * abstracts the read-side of the multiple files option.
488  *
489  * @param a The offset where the read should start
490  * @param buf A buffer to read into
491  * @param len The size of buf
492  * @return The number of bytes actually read, or -1 in case of an
493  * error.
494  **/
495 int rawexpread(off_t a, char *buf, size_t len, CLIENT *client) {
496         ssize_t res;
497
498         myseek(client->export[(int)a/client->server->hunksize],
499                         a%client->server->hunksize);
500         res = read(client->export[(int)a/client->server->hunksize], buf, len);
501         return (res < 0 || (size_t)res != len);
502 }
503
504 /**
505  * Read an amount of bytes at a given offset from the right file. This
506  * abstracts the read-side of the copyonwrite stuff, and calls
507  * rawexpread() with the right parameters to do the actual work.
508  * @param a The offset where the read should start
509  * @param buf A buffer to read into
510  * @param len The size of buf
511  * @return The number of bytes actually read, or -1 in case of an error
512  **/
513 int expread(off_t a, char *buf, size_t len, CLIENT *client) {
514         off_t rdlen, offset;
515         off_t mapcnt, mapl, maph, pagestart;
516
517         if (!(client->server->flags & F_COPYONWRITE))
518                 return rawexpread(a, buf, len, client);
519         DEBUG3("Asked to read %d bytes at %Lu.\n", len, (unsigned long long)a);
520
521         mapl=a/DIFFPAGESIZE; maph=(a+len-1)/DIFFPAGESIZE;
522
523         for (mapcnt=mapl;mapcnt<=maph;mapcnt++) {
524                 pagestart=mapcnt*DIFFPAGESIZE;
525                 offset=a-pagestart;
526                 rdlen=(0<DIFFPAGESIZE-offset && len<(size_t)(DIFFPAGESIZE-offset)) ?
527                         len : (size_t)DIFFPAGESIZE-offset;
528                 if (client->difmap[mapcnt]!=(u32)(-1)) { /* the block is already there */
529                         DEBUG3("Page %Lu is at %lu\n", (unsigned long long)mapcnt,
530                                (unsigned long)(client->difmap[mapcnt]));
531                         myseek(client->difffile, client->difmap[mapcnt]*DIFFPAGESIZE+offset);
532                         if (read(client->difffile, buf, rdlen) != rdlen) return -1;
533                 } else { /* the block is not there */
534                         DEBUG2("Page %Lu is not here, we read the original one\n",
535                                (unsigned long long)mapcnt);
536                         return rawexpread(a, buf, rdlen, client);
537                 }
538                 len-=rdlen; a+=rdlen; buf+=rdlen;
539         }
540         return 0;
541 }
542
543 /**
544  * Write an amount of bytes at a given offset to the right file. This
545  * abstracts the write-side of the copyonwrite option, and calls
546  * rawexpwrite() with the right parameters to do the actual work.
547  *
548  * @param a The offset where the write should start
549  * @param buf The buffer to write from
550  * @param len The length of buf
551  * @return The number of bytes actually written, or -1 in case of an error
552  **/
553 int expwrite(off_t a, char *buf, size_t len, CLIENT *client) {
554         char pagebuf[DIFFPAGESIZE];
555         off_t mapcnt,mapl,maph;
556         off_t wrlen,rdlen; 
557         off_t pagestart;
558         off_t offset;
559
560         if (!(client->server->flags & F_COPYONWRITE))
561                 return(rawexpwrite(a,buf,len, client)); 
562         DEBUG3("Asked to write %d bytes at %Lu.\n", len, (unsigned long long)a);
563
564         mapl=a/DIFFPAGESIZE ; maph=(a+len-1)/DIFFPAGESIZE ;
565
566         for (mapcnt=mapl;mapcnt<=maph;mapcnt++) {
567                 pagestart=mapcnt*DIFFPAGESIZE ;
568                 offset=a-pagestart ;
569                 wrlen=(0<DIFFPAGESIZE-offset && len<(size_t)(DIFFPAGESIZE-offset)) ?
570                         len : (size_t)DIFFPAGESIZE-offset;
571
572                 if (client->difmap[mapcnt]!=(u32)(-1)) { /* the block is already there */
573                         DEBUG3("Page %Lu is at %lu\n", (unsigned long long)mapcnt,
574                                (unsigned long)(client->difmap[mapcnt])) ;
575                         myseek(client->difffile,
576                                         client->difmap[mapcnt]*DIFFPAGESIZE+offset);
577                         if (write(client->difffile, buf, wrlen) != wrlen) return -1 ;
578                 } else { /* the block is not there */
579                         myseek(client->difffile,client->difffilelen*DIFFPAGESIZE) ;
580                         client->difmap[mapcnt]=client->difffilelen++ ;
581                         DEBUG3("Page %Lu is not here, we put it at %lu\n",
582                                (unsigned long long)mapcnt,
583                                (unsigned long)(client->difmap[mapcnt]));
584                         rdlen=DIFFPAGESIZE ;
585                         if (rdlen+pagestart%(client->server->hunksize) >
586                                         (client->server->hunksize)) 
587                                 rdlen=client->server->hunksize -
588                                         (pagestart%client->server->hunksize);
589                         if (rawexpread(pagestart, pagebuf, rdlen, client))
590                                 return -1;
591                         memcpy(pagebuf+offset,buf,wrlen) ;
592                         if (write(client->difffile, pagebuf, DIFFPAGESIZE) !=
593                                         DIFFPAGESIZE)
594                                 return -1;
595                 }                                                   
596                 len-=wrlen ; a+=wrlen ; buf+=wrlen ;
597         }
598         return 0;
599 }
600
601 /**
602  * Do the initial negotiation.
603  *
604  * @param net A socket to do the negotiation over
605  **/
606 void negotiate(CLIENT *client) {
607         char zeros[300];
608         u64 size_host;
609
610         memset(zeros, 0, 290);
611         if (write(client->net, INIT_PASSWD, 8) < 0)
612                 err("Negotiation failed: %m");
613         cliserv_magic = htonll(cliserv_magic);
614         if (write(client->net, &cliserv_magic, sizeof(cliserv_magic)) < 0)
615                 err("Negotiation failed: %m");
616         size_host = htonll((u64)(client->exportsize));
617         if (write(client->net, &size_host, 8) < 0)
618                 err("Negotiation failed: %m");
619         if (write(client->net, zeros, 128) < 0)
620                 err("Negotiation failed: %m");
621 }
622
623 /** sending macro. */
624 #define SEND(net,reply) writeit( net, &reply, sizeof( reply ));
625 /** error macro. */
626 #define ERROR(client,reply) { reply.error = htonl(-1); SEND(client->net,reply); reply.error = 0; }
627 /**
628  * Serve a file to a single client.
629  *
630  * @todo This beast needs to be split up in many tiny little manageable
631  * pieces. Preferably with a chainsaw.
632  *
633  * @param net A network socket, connected to an nbd client
634  * @return never
635  **/
636 int mainloop(CLIENT *client) {
637         struct nbd_request request;
638         struct nbd_reply reply;
639         gboolean go_on=TRUE;
640 #ifdef DODBG
641         int i = 0;
642 #endif
643         negotiate(client);
644         DEBUG("Entering request loop!\n");
645         reply.magic = htonl(NBD_REPLY_MAGIC);
646         reply.error = 0;
647         while (go_on) {
648                 char buf[BUFSIZE];
649                 size_t len;
650 #ifdef DODBG
651                 i++;
652                 printf("%d: ", i);
653 #endif
654                 if (client->server->timeout) 
655                         alarm(client->server->timeout);
656                 readit(client->net, &request, sizeof(request));
657                 request.from = ntohll(request.from);
658                 request.type = ntohl(request.type);
659
660                 if (request.type==NBD_CMD_DISC) {
661                         msg2(LOG_INFO, "Disconnect request received.");
662                         if (client->difmap) g_free(client->difmap) ;
663                         if (client->difffile>=0) { 
664                                 close(client->difffile);
665                                 unlink(client->difffilename);
666                         }
667                         go_on=FALSE;
668                         continue;
669                 }
670
671                 len = ntohl(request.len);
672
673                 if (request.magic != htonl(NBD_REQUEST_MAGIC))
674                         err("Not enough magic.");
675                 if (len > BUFSIZE)
676                         err("Request too big!");
677 #ifdef DODBG
678                 printf("%s from %Lu (%Lu) len %d, ", request.type ? "WRITE" :
679                                 "READ", (unsigned long long)request.from,
680                                 (unsigned long long)request.from / 512, len);
681 #endif
682                 memcpy(reply.handle, request.handle, sizeof(reply.handle));
683                 if ((request.from + len) > (OFFT_MAX)) {
684                         DEBUG("[Number too large!]");
685                         ERROR(client, reply);
686                         continue;
687                 }
688
689                 if (((ssize_t)((off_t)request.from + len) > client->exportsize) ||
690                     ((client->server->flags & F_READONLY) && request.type)) {
691                         DEBUG("[RANGE!]");
692                         ERROR(client, reply);
693                         continue;
694                 }
695
696                 if (request.type==NBD_CMD_WRITE) {
697                         DEBUG("wr: net->buf, ");
698                         readit(client->net, buf, len);
699                         DEBUG("buf->exp, ");
700                         if ((client->server->flags & F_AUTOREADONLY) ||
701                                         expwrite(request.from, buf, len,
702                                                 client)) {
703                                 DEBUG("Write failed: %m" );
704                                 ERROR(client, reply);
705                                 continue;
706                         }
707                         SEND(client->net, reply);
708                         DEBUG("OK!\n");
709                         continue;
710                 }
711                 /* READ */
712
713                 DEBUG("exp->buf, ");
714                 if (expread(request.from, buf + sizeof(struct nbd_reply), len, client)) {
715                         DEBUG("Read failed: %m");
716                         ERROR(client, reply);
717                         continue;
718                 }
719
720                 DEBUG("buf->net, ");
721                 memcpy(buf, &reply, sizeof(struct nbd_reply));
722                 writeit(client->net, buf, len + sizeof(struct nbd_reply));
723                 DEBUG("OK!\n");
724         }
725 }
726
727 /**
728  * Split a single exportfile into multiple ones, if that was asked.
729  * @return 0 on success, -1 on failure
730  * @param client information on the client which we want to split
731  **/
732 int splitexport(CLIENT* client) {
733         off_t i;
734
735         for (i=0; i<client->exportsize; i+=client->server->hunksize) {
736                 gchar *tmpname;
737
738                 if(client->server->flags & F_MULTIFILE) {
739                         tmpname=g_strdup_printf("%s.%d", client->exportname,
740                                         (int)(i/client->server->hunksize));
741                 } else {
742                         tmpname=g_strdup(client->exportname);
743                 }
744                 DEBUG2( "Opening %s\n", tmpname );
745                 if ((client->export[ i/ client->server->hunksize ] =
746                                         open(tmpname, (client->server->flags &
747                                                         F_READONLY) ? O_RDONLY
748                                                 : O_RDWR)) == -1) {
749                         /* Read WRITE ACCESS was requested by media is only read only */
750                         client->server->flags |= F_AUTOREADONLY;
751                         client->server->flags |= F_READONLY;
752                         if ((client->export[i/client->server->hunksize] =
753                                                 open(tmpname, O_RDONLY)) == -1) 
754                                 err("Could not open exported file: %m");
755                 }
756                 g_free(tmpname);
757         }
758
759         if (client->server->flags & F_COPYONWRITE) {
760                 snprintf(client->difffilename, 1024, "%s-%s-%d.diff",client->exportname,client->clientname,
761                         (int)getpid()) ;
762                 client->difffilename[1023]='\0';
763                 msg3(LOG_INFO,"About to create map and diff file %s",client->difffilename) ;
764                 client->difffile=open(client->difffilename,O_RDWR | O_CREAT | O_TRUNC,0600) ;
765                 if (client->difffile<0) err("Could not create diff file (%m)") ;
766                 if ((client->difmap=calloc(client->exportsize/DIFFPAGESIZE,sizeof(u32)))==NULL)
767                         err("Could not allocate memory") ;
768                 for (i=0;i<client->exportsize/DIFFPAGESIZE;i++) client->difmap[i]=(u32)-1 ;
769         }
770
771         return 0;
772 }
773
774 /**
775  * Serve a connection. 
776  *
777  * @todo allow for multithreading, perhaps use libevent. Not just yet, though;
778  * follow the road map.
779  *
780  * @param net A network socket connected to an nbd client
781  **/
782 void serveconnection(CLIENT *client) {
783         char buf[80];
784         splitexport(client);
785
786         if (!client->server->expected_size) {
787                 client->exportsize = size_autodetect(client->export[0]);
788         } else {
789                 /* Perhaps we should check first. Not now. */
790                 client->exportsize = client->server->expected_size;
791         }
792         if (client->exportsize > OFFT_MAX) {
793                 /* uhm, well... In a parallel universe, this *might* be
794                  * possible... */
795                 err("Size of exported file is too big\n");
796         }
797         else {
798                 msg3(LOG_INFO, "size of exported file/device is %Lu", (unsigned long long)client->exportsize);
799         }
800
801         setmysockopt(client->net);
802
803         mainloop(client);
804 }
805
806 /**
807  * Find the name of the file we have to serve. This will use g_strdup_printf
808  * to put the IP address of the client inside a filename containing
809  * "%s". That name is then written to client->exportname.
810  *
811  * @param net A socket connected to an nbd client
812  * @param client information about the client. The IP address in human-readable
813  * format will be written to a new char* buffer, the address of which will be
814  * stored in client->clientname.
815  **/
816 void set_peername(int net, CLIENT *client) {
817         struct sockaddr_in addrin;
818         int addrinlen = sizeof( addrin );
819         char *peername ;
820
821         if (getpeername(net, (struct sockaddr *) &addrin, (socklen_t *)&addrinlen) < 0)
822                 err("getsockname failed: %m");
823         peername = inet_ntoa(addrin.sin_addr);
824         client->exportname=g_strdup_printf(client->server->exportname, peername);
825
826         msg4(LOG_INFO, "connect from %s, assigned file is %s", 
827              peername, client->exportname);
828         client->clientname=g_strdup(peername);
829 }
830
831 /**
832  * Destroy a pid_t*
833  * @param data a pointer to pid_t which should be freed
834  **/
835 void destroy_pid_t(gpointer data) {
836         g_free(data);
837 }
838
839 /**
840  * Go daemon (unless we specified at compile time that we didn't want this)
841  * @param serve the first server of our configuration. If its port is zero,
842  *      then do not daemonize, because we're doing inetd then.
843  **/
844 #if !defined(NODAEMON) && !defined(NOFORK)
845 void daemonize(SERVER* serve) {
846         FILE*pidf;
847
848         if((serve->port)) {
849                 if(daemon(0,0)<0) {
850                         err("daemon");
851                 }
852                 snprintf(pidfname, sizeof(char)*255, "/var/run/nbd-server.%d.pid", serve->port);
853                 pidf=fopen(pidfname, "w");
854                 if(pidf) {
855                         fprintf(pidf,"%d", (int)getpid());
856                         fclose(pidf);
857                 } else {
858                         perror("fopen");
859                         fprintf(stderr, "Not fatal; continuing");
860                 }
861         }
862 }
863 #else
864 #define daemonize(serve)
865 #endif /* !defined(NODAEMON) && !defined(NOFORK) */
866
867 /**
868  * Connect a server's socket.
869  *
870  * @todo modularize this giant beast. Preferably with a chainsaw. Also,
871  * it has no business starting mainloop(), through serveconnection(); it
872  * should connect, and be done with it.
873  *
874  * @param serve the server we want to connect.
875  **/
876 void setup_serve(SERVER* serve) {
877         struct sockaddr_in addrin;
878         struct sigaction sa;
879         int addrinlen = sizeof(addrin);
880         int newpid, i;
881 #ifndef sun
882         int yes=1;
883 #else
884         char yes='1';
885 #endif /* sun */
886
887         if ((serve->socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
888                 err("socket: %m");
889
890         /* lose the pesky "Address already in use" error message */
891         if (setsockopt(serve->socket,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) {
892                 err("setsockopt SO_REUSEADDR");
893         }
894         if (setsockopt(serve->socket,SOL_SOCKET,SO_KEEPALIVE,&yes,sizeof(int)) == -1) {
895                 err("setsockopt SO_KEEPALIVE");
896         }
897
898         DEBUG("Waiting for connections... bind, ");
899         addrin.sin_family = AF_INET;
900         addrin.sin_port = htons(serve->port);
901         addrin.sin_addr.s_addr = 0;
902         if (bind(serve->socket, (struct sockaddr *) &addrin, addrinlen) < 0)
903                 err("bind: %m");
904         DEBUG("listen, ");
905         if (listen(serve->socket, 1) < 0)
906                 err("listen: %m");
907         sa.sa_handler = sigchld_handler;
908         sigemptyset(&sa.sa_mask);
909         sa.sa_flags = SA_RESTART;
910         if(sigaction(SIGCHLD, &sa, NULL) == -1)
911                 err("sigaction: %m");
912         sa.sa_handler = sigterm_handler;
913         sigemptyset(&sa.sa_mask);
914         sa.sa_flags = SA_RESTART;
915         if(sigaction(SIGTERM, &sa, NULL) == -1)
916                 err("sigaction: %m");
917         children=g_hash_table_new_full(g_int_hash, g_int_equal, NULL, destroy_pid_t);
918 }
919
920 /**
921  * Loop through the available servers, and serve them.
922  *
923  * Actually, right now we only handle one server. Will change that for
924  * 2.9.
925  **/
926 int serveloop(SERVER* serve) {
927         struct sockaddr_in addrin;
928         int addrinlen=sizeof(addrin);
929         for(;;) {
930                 CLIENT *client;
931                 int net;
932                 pid_t *pid;
933
934                 DEBUG("accept, ");
935                 if ((net = accept(serve->socket, (struct sockaddr *) &addrin, &addrinlen)) < 0)
936                         err("accept: %m");
937
938                 client = g_malloc(sizeof(CLIENT));
939                 client->server=serve;
940                 client->exportsize=OFFT_MAX;
941                 client->net=net;
942                 set_peername(net, client);
943                 if (!authorized_client(client)) {
944                         msg2(LOG_INFO,"Unauthorized client") ;
945                         close(net) ;
946                         continue ;
947                 }
948                 msg2(LOG_INFO,"Authorized client") ;
949                 pid=g_malloc(sizeof(pid_t));
950 #ifndef NOFORK
951                 if ((*pid=fork())<0) {
952                         msg3(LOG_INFO,"Could not fork (%s)",strerror(errno)) ;
953                         close(net) ;
954                         continue ;
955                 }
956                 if (*pid>0) { /* parent */
957                         close(net);
958                         g_hash_table_insert(children, pid, pid);
959                         continue;
960                 }
961                 /* child */
962                 g_hash_table_destroy(children);
963                 close(serve->socket) ;
964 #endif // NOFORK
965                 msg2(LOG_INFO,"Starting to serve") ;
966                 serveconnection(client);
967         }
968 }
969
970 /**
971  * Main entry point...
972  **/
973 int main(int argc, char *argv[]) {
974         SERVER* serve;
975         GArray* servers;
976
977         if (sizeof( struct nbd_request )!=28) {
978                 fprintf(stderr,"Bad size of structure. Alignment problems?\n");
979                 exit(-1) ;
980         }
981
982         logging();
983         serve=cmdline(argc, argv);
984         servers=g_array_new(TRUE, FALSE, sizeof(SERVER*));
985
986         if (!(serve->port)) {
987                 CLIENT *client;
988 #ifndef ISSERVER
989                 /* You really should define ISSERVER if you're going to use
990                  * inetd mode, but if you don't, closing stdout and stderr
991                  * (which inetd had connected to the client socket) will let it
992                  * work. */
993                 close(1);
994                 close(2);
995                 open("/dev/null", O_WRONLY);
996                 open("/dev/null", O_WRONLY);
997 #endif
998                 client=g_malloc(sizeof(CLIENT));
999                 client->server=serve;
1000                 client->net=0;
1001                 client->exportsize=OFFT_MAX;
1002                 set_peername(0,client);
1003                 serveconnection(client);
1004                 return 0;
1005         }
1006         daemonize(serve);
1007         setup_serve(serve);
1008         serveloop(serve);
1009         return 0 ;
1010 }