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