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