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