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