Imported Upstream version 2.5.2p1
[debian/amanda] / server-src / dumper.c
1 /*
2  * Amanda, The Advanced Maryland Automatic Network Disk Archiver
3  * Copyright (c) 1991-1999 University of Maryland at College Park
4  * All Rights Reserved.
5  *
6  * Permission to use, copy, modify, distribute, and sell this software and its
7  * documentation for any purpose is hereby granted without fee, provided that
8  * the above copyright notice appear in all copies and that both that
9  * copyright notice and this permission notice appear in supporting
10  * documentation, and that the name of U.M. not be used in advertising or
11  * publicity pertaining to distribution of the software without specific,
12  * written prior permission.  U.M. makes no representations about the
13  * suitability of this software for any purpose.  It is provided "as is"
14  * without express or implied warranty.
15  *
16  * U.M. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL U.M.
18  * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
19  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
20  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
21  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22  *
23  * Authors: the Amanda Development Team.  Its members are listed in a
24  * file named AUTHORS, in the root directory of this distribution.
25  */
26 /* $Id: dumper.c,v 1.190 2006/08/30 19:53:57 martinea Exp $
27  *
28  * requests remote amandad processes to dump filesystems
29  */
30 #include "amanda.h"
31 #include "amindex.h"
32 #include "arglist.h"
33 #include "clock.h"
34 #include "conffile.h"
35 #include "event.h"
36 #include "logfile.h"
37 #include "packet.h"
38 #include "protocol.h"
39 #include "security.h"
40 #include "stream.h"
41 #include "token.h"
42 #include "version.h"
43 #include "fileheader.h"
44 #include "amfeatures.h"
45 #include "server_util.h"
46 #include "util.h"
47
48 #define dumper_debug(i,x) do {          \
49         if ((i) <= debug_dumper) {      \
50             dbprintf(x);                \
51         }                               \
52 } while (0)
53
54 #ifndef SEEK_SET
55 #define SEEK_SET 0
56 #endif
57
58 #ifndef SEEK_CUR
59 #define SEEK_CUR 1
60 #endif
61
62 #define CONNECT_TIMEOUT 5*60
63
64 #define STARTUP_TIMEOUT 60
65
66 struct databuf {
67     int fd;                     /* file to flush to */
68     char *buf;
69     char *datain;               /* data buffer markers */
70     char *dataout;
71     char *datalimit;
72     pid_t compresspid;          /* valid if fd is pipe to compress */
73     pid_t encryptpid;           /* valid if fd is pipe to encrypt */
74 };
75
76 static char *handle = NULL;
77
78 static char *errstr = NULL;
79 static off_t dumpbytes;
80 static off_t dumpsize, headersize, origsize;
81
82 static comp_t srvcompress = COMP_NONE;
83 char *srvcompprog = NULL;
84 char *clntcompprog = NULL;
85
86 static encrypt_t srvencrypt = ENCRYPT_NONE;
87 char *srv_encrypt = NULL;
88 char *clnt_encrypt = NULL;
89 char *srv_decrypt_opt = NULL;
90 char *clnt_decrypt_opt = NULL;
91
92 static FILE *errf = NULL;
93 static char *hostname = NULL;
94 am_feature_t *their_features = NULL;
95 static char *diskname = NULL;
96 static char *qdiskname = NULL;
97 static char *device = NULL;
98 static char *options = NULL;
99 static char *progname = NULL;
100 static char *amandad_path=NULL;
101 static char *client_username=NULL;
102 static char *ssh_keys=NULL;
103 static int level;
104 static char *dumpdate = NULL;
105 static char *dumper_timestamp = NULL;
106 static time_t conf_dtimeout;
107 static int indexfderror;
108 static int set_datafd;
109
110 static dumpfile_t file;
111
112 static struct {
113     const char *name;
114     security_stream_t *fd;
115 } streams[] = {
116 #define DATAFD  0
117     { "DATA", NULL },
118 #define MESGFD  1
119     { "MESG", NULL },
120 #define INDEXFD 2
121     { "INDEX", NULL },
122 };
123 #define NSTREAMS        (int)(sizeof(streams) / sizeof(streams[0]))
124
125 static am_feature_t *our_features = NULL;
126 static char *our_feature_string = NULL;
127
128 /* local functions */
129 int             main(int, char **);
130 static int      do_dump(struct databuf *);
131 static void     check_options(char *);
132 static void     finish_tapeheader(dumpfile_t *);
133 static ssize_t  write_tapeheader(int, dumpfile_t *);
134 static void     databuf_init(struct databuf *, int);
135 static int      databuf_write(struct databuf *, const void *, size_t);
136 static int      databuf_flush(struct databuf *);
137 static void     process_dumpeof(void);
138 static void     process_dumpline(const char *);
139 static void     add_msg_data(const char *, size_t);
140 static void     parse_info_line(char *);
141 static void     log_msgout(logtype_t);
142 static char *   dumper_get_security_conf (char *, void *);
143
144 static int      runcompress(int, pid_t *, comp_t);
145 static int      runencrypt(int, pid_t *,  encrypt_t);
146
147 static void     sendbackup_response(void *, pkt_t *, security_handle_t *);
148 static int      startup_dump(const char *, const char *, const char *, int,
149                         const char *, const char *, const char *,
150                         const char *, const char *, const char *);
151 static void     stop_dump(void);
152
153 static void     read_indexfd(void *, void *, ssize_t);
154 static void     read_datafd(void *, void *, ssize_t);
155 static void     read_mesgfd(void *, void *, ssize_t);
156 static void     timeout(time_t);
157 static void     timeout_callback(void *);
158
159 static void
160 check_options(
161     char *options)
162 {
163   char *compmode = NULL;
164   char *compend  = NULL;
165   char *encryptmode = NULL;
166   char *encryptend = NULL;
167   char *decryptmode = NULL;
168   char *decryptend = NULL;
169
170     /* parse the compression option */
171   if (strstr(options, "srvcomp-best;") != NULL) 
172       srvcompress = COMP_BEST;
173     else if (strstr(options, "srvcomp-fast;") != NULL)
174       srvcompress = COMP_FAST;
175     else if ((compmode = strstr(options, "srvcomp-cust=")) != NULL) {
176         compend = strchr(compmode, ';');
177         if (compend ) {
178             srvcompress = COMP_SERVER_CUST;
179             *compend = '\0';
180             srvcompprog = stralloc(compmode + strlen("srvcomp-cust="));
181             *compend = ';';
182         }
183     } else if ((compmode = strstr(options, "comp-cust=")) != NULL) {
184         compend = strchr(compmode, ';');
185         if (compend) {
186             srvcompress = COMP_CUST;
187             *compend = '\0';
188             clntcompprog = stralloc(compmode + strlen("comp-cust="));
189             *compend = ';';
190         }
191     }
192     else {
193       srvcompress = COMP_NONE;
194     }
195     
196
197     /* now parse the encryption option */
198     if ((encryptmode = strstr(options, "encrypt-serv-cust=")) != NULL) {
199       encryptend = strchr(encryptmode, ';');
200       if (encryptend) {
201             srvencrypt = ENCRYPT_SERV_CUST;
202             *encryptend = '\0';
203             srv_encrypt = stralloc(encryptmode + strlen("encrypt-serv-cust="));
204             *encryptend = ';';
205       }
206     } else if ((encryptmode = strstr(options, "encrypt-cust=")) != NULL) {
207       encryptend = strchr(encryptmode, ';');
208       if (encryptend) {
209             srvencrypt = ENCRYPT_CUST;
210             *encryptend = '\0';
211             clnt_encrypt = stralloc(encryptmode + strlen("encrypt-cust="));
212             *encryptend = ';';
213       }
214     } else {
215       srvencrypt = ENCRYPT_NONE;
216     }
217     /* get the decryption option parameter */
218     if ((decryptmode = strstr(options, "server-decrypt-option=")) != NULL) {
219       decryptend = strchr(decryptmode, ';');
220       if (decryptend) {
221         *decryptend = '\0';
222         srv_decrypt_opt = stralloc(decryptmode + strlen("server-decrypt-option="));
223         *decryptend = ';';
224       }
225     } else if ((decryptmode = strstr(options, "client-decrypt-option=")) != NULL) {
226       decryptend = strchr(decryptmode, ';');
227       if (decryptend) {
228         *decryptend = '\0';
229         clnt_decrypt_opt = stralloc(decryptmode + strlen("client-decrypt-option="));
230         *decryptend = ';';
231       }
232     }
233 }
234
235
236 int
237 main(
238     int         main_argc,
239     char **     main_argv)
240 {
241     static struct databuf db;
242     struct cmdargs cmdargs;
243     cmd_t cmd;
244     int outfd = -1;
245     int rc;
246     in_port_t taper_port;
247     unsigned long malloc_hist_1, malloc_size_1;
248     unsigned long malloc_hist_2, malloc_size_2;
249     char *conffile;
250     char *q = NULL;
251     int a;
252     uid_t ruid;
253     int    new_argc,   my_argc;
254     char **new_argv, **my_argv;
255     struct addrinfo hints;
256     int res;
257     struct addrinfo *gaires = NULL;
258
259     safe_fd(-1, 0);
260
261     set_pname("dumper");
262
263     dbopen(DBG_SUBDIR_SERVER);
264
265     /* Don't die when child closes pipe */
266     signal(SIGPIPE, SIG_IGN);
267
268     malloc_size_1 = malloc_inuse(&malloc_hist_1);
269
270     erroutput_type = (ERR_AMANDALOG|ERR_INTERACTIVE);
271     set_logerror(logerror);
272
273     parse_conf(main_argc, main_argv, &new_argc, &new_argv);
274     my_argc = new_argc;
275     my_argv = new_argv;
276
277     if (my_argc > 1) {
278         config_name = stralloc(my_argv[1]);
279         config_dir = vstralloc(CONFIG_DIR, "/", config_name, "/", NULL);
280     } else {
281         char my_cwd[STR_SIZE];
282
283         if (getcwd(my_cwd, SIZEOF(my_cwd)) == NULL) {
284             error("cannot determine current working directory");
285             /*NOTREACHED*/
286         }
287         config_dir = stralloc2(my_cwd, "/");
288         if ((config_name = strrchr(my_cwd, '/')) != NULL) {
289             config_name = stralloc(config_name + 1);
290         }
291     }
292
293     safe_cd();
294
295     our_features = am_init_feature_set();
296     our_feature_string = am_feature_to_string(our_features);
297
298     conffile = stralloc2(config_dir, CONFFILE_NAME);
299     if(read_conffile(conffile)) {
300         error("errors processing config file \"%s\"", conffile);
301         /*NOTREACHED*/
302     }
303     amfree(conffile);
304
305     dbrename(config_name, DBG_SUBDIR_SERVER);
306
307     report_bad_conf_arg();
308     /*
309      * Make our effective uid nonprivlidged, keeping save uid as root
310      * in case we need to get back (to bind privlidged ports, etc).
311      */
312     ruid = getuid();
313     if(geteuid() == 0) {
314         seteuid(ruid);
315         setgid(getgid());
316     }
317 #if defined BSD_SECURITY && !defined SSH_SECURITY
318     else {
319         error("must be run setuid root to communicate correctly");
320         /*NOTREACHED*/
321     }
322 #endif
323
324     fprintf(stderr,
325             "%s: pid %ld executable %s version %s\n",
326             get_pname(), (long) getpid(),
327             my_argv[0], version());
328     fflush(stderr);
329
330     /* now, make sure we are a valid user */
331
332     if (getpwuid(getuid()) == NULL) {
333         error("can't get login name for my uid %ld", (long)getuid());
334         /*NOTREACHED*/
335     }
336
337     signal(SIGPIPE, SIG_IGN);
338
339     conf_dtimeout = (time_t)getconf_int(CNF_DTIMEOUT);
340
341     protocol_init();
342
343     do {
344         cmd = getcmd(&cmdargs);
345
346         switch(cmd) {
347         case START:
348             if(cmdargs.argc <  2)
349                 error("error [dumper START: not enough args: timestamp]");
350             dumper_timestamp = newstralloc(dumper_timestamp, cmdargs.argv[2]);
351             break;
352
353         case ABORT:
354             break;
355
356         case QUIT:
357             break;
358
359         case PORT_DUMP:
360             /*
361              * PORT-DUMP
362              *   handle
363              *   port
364              *   host
365              *   features
366              *   disk
367              *   device
368              *   level
369              *   dumpdate
370              *   progname
371              *   amandad_path
372              *   client_username
373              *   ssh_keys
374              *   options
375              */
376             cmdargs.argc++;                     /* true count of args */
377             a = 2;
378
379             if(a >= cmdargs.argc) {
380                 error("error [dumper PORT-DUMP: not enough args: handle]");
381                 /*NOTREACHED*/
382             }
383             handle = newstralloc(handle, cmdargs.argv[a++]);
384
385             if(a >= cmdargs.argc) {
386                 error("error [dumper PORT-DUMP: not enough args: port]");
387                 /*NOTREACHED*/
388             }
389             taper_port = (in_port_t)atoi(cmdargs.argv[a++]);
390
391             if(a >= cmdargs.argc) {
392                 error("error [dumper PORT-DUMP: not enough args: hostname]");
393                 /*NOTREACHED*/
394             }
395             hostname = newstralloc(hostname, cmdargs.argv[a++]);
396
397             if(a >= cmdargs.argc) {
398                 error("error [dumper PORT-DUMP: not enough args: features]");
399                 /*NOTREACHED*/
400             }
401             am_release_feature_set(their_features);
402             their_features = am_string_to_feature(cmdargs.argv[a++]);
403
404             if(a >= cmdargs.argc) {
405                 error("error [dumper PORT-DUMP: not enough args: diskname]");
406                 /*NOTREACHED*/
407             }
408             qdiskname = newstralloc(qdiskname, cmdargs.argv[a++]);
409             if (diskname != NULL)
410                 amfree(diskname);
411             diskname = unquote_string(qdiskname);
412
413             if(a >= cmdargs.argc) {
414                 error("error [dumper PORT-DUMP: not enough args: device]");
415                 /*NOTREACHED*/
416             }
417             device = newstralloc(device, cmdargs.argv[a++]);
418             if(strcmp(device,"NODEVICE") == 0)
419                 amfree(device);
420
421             if(a >= cmdargs.argc) {
422                 error("error [dumper PORT-DUMP: not enough args: level]");
423                 /*NOTREACHED*/
424             }
425             level = atoi(cmdargs.argv[a++]);
426
427             if(a >= cmdargs.argc) {
428                 error("error [dumper PORT-DUMP: not enough args: dumpdate]");
429                 /*NOTREACHED*/
430             }
431             dumpdate = newstralloc(dumpdate, cmdargs.argv[a++]);
432
433             if(a >= cmdargs.argc) {
434                 error("error [dumper PORT-DUMP: not enough args: program]");
435                 /*NOTREACHED*/
436             }
437             progname = newstralloc(progname, cmdargs.argv[a++]);
438
439             if(a >= cmdargs.argc) {
440                 error("error [dumper PORT-DUMP: not enough args: amandad_path]");
441                 /*NOTREACHED*/
442             }
443             amandad_path = newstralloc(amandad_path, cmdargs.argv[a++]);
444
445             if(a >= cmdargs.argc) {
446                 error("error [dumper PORT-DUMP: not enough args: client_username]");
447             }
448             client_username = newstralloc(client_username, cmdargs.argv[a++]);
449
450             if(a >= cmdargs.argc) {
451                 error("error [dumper PORT-DUMP: not enough args: ssh_keys]");
452             }
453             ssh_keys = newstralloc(ssh_keys, cmdargs.argv[a++]);
454
455             if(a >= cmdargs.argc) {
456                 error("error [dumper PORT-DUMP: not enough args: options]");
457             }
458             options = newstralloc(options, cmdargs.argv[a++]);
459
460             if(a != cmdargs.argc) {
461                 error("error [dumper PORT-DUMP: too many args: %d != %d]",
462                       cmdargs.argc, a);
463                 /*NOTREACHED*/
464             }
465
466             /* Double-check that 'localhost' resolves properly */
467 #ifdef WORKING_IPV6
468             hints.ai_flags = AI_CANONNAME | AI_V4MAPPED | AI_ALL;
469             hints.ai_family = AF_UNSPEC;
470 #else
471             hints.ai_flags = AI_CANONNAME;
472             hints.ai_family = AF_INET;
473 #endif
474             hints.ai_socktype = 0;
475             hints.ai_protocol = 0;
476             hints.ai_addrlen = 0;
477             hints.ai_addr = NULL;
478             hints.ai_canonname = NULL;
479             hints.ai_next = NULL;
480             res = getaddrinfo("localhost", NULL, &hints, &gaires);
481 #ifdef WORKING_IPV6
482             if (res != 0) {
483                 hints.ai_flags = AI_CANONNAME;
484                 hints.ai_family = AF_UNSPEC;
485                 res = getaddrinfo("localhost", NULL, &hints, &gaires);
486             }
487 #endif
488             if (res != 0) {
489                 errstr = newvstralloc(errstr,
490                                      _("could not resolve localhost: "),
491                                      gai_strerror(res), NULL);
492                 q = squotef(errstr);
493                 putresult(FAILED, "%s %s\n", handle, q);
494                 log_add(L_FAIL, "%s %s %s %d [%s]", hostname, qdiskname,
495                         dumper_timestamp, level, errstr);
496                 amfree(q);
497                 break;
498             }
499             if (gaires) freeaddrinfo(gaires);
500
501             /* connect outf to chunker/taper port */
502
503             outfd = stream_client("localhost", taper_port,
504                                   STREAM_BUFSIZE, 0, NULL, 0);
505             if (outfd == -1) {
506                 
507                 errstr = newvstralloc(errstr, "port open: ",
508                                       strerror(errno), NULL);
509                 q = squotef(errstr);
510                 putresult(FAILED, "%s %s\n", handle, q);
511                 log_add(L_FAIL, "%s %s %s %d [%s]", hostname, qdiskname,
512                         dumper_timestamp, level, errstr);
513                 amfree(q);
514                 break;
515             }
516             databuf_init(&db, outfd);
517
518             check_options(options);
519
520             rc = startup_dump(hostname,
521                               diskname,
522                               device,
523                               level,
524                               dumpdate,
525                               progname,
526                               amandad_path,
527                               client_username,
528                               ssh_keys,
529                               options);
530             if (rc != 0) {
531                 q = squote(errstr);
532                 putresult(rc == 2? FAILED : TRYAGAIN, "%s %s\n",
533                     handle, q);
534                 if (rc == 2)
535                     log_add(L_FAIL, "%s %s %s %d [%s]", hostname, qdiskname,
536                         dumper_timestamp, level, errstr);
537                 amfree(q);
538             } else {
539                 do_dump(&db);
540             }
541
542             amfree(amandad_path);
543             amfree(client_username);
544
545             break;
546
547         default:
548             if(cmdargs.argc >= 1) {
549                 q = squote(cmdargs.argv[1]);
550             } else if(cmdargs.argc >= 0) {
551                 q = squote(cmdargs.argv[0]);
552             } else {
553                 q = stralloc("(no input?)");
554             }
555             putresult(BAD_COMMAND, "%s\n", q);
556             amfree(q);
557             break;
558         }
559
560         if (outfd != -1)
561             aclose(outfd);
562     } while(cmd != QUIT);
563
564     /* make sure root privilege is dropped */
565     if ( geteuid() == 0 ) {
566       setuid(ruid);
567       seteuid(ruid);
568     }
569
570     free_new_argv(new_argc, new_argv);
571     free_server_config();
572     am_release_feature_set(our_features);
573     amfree(our_feature_string);
574     amfree(errstr);
575     amfree(dumper_timestamp);
576     amfree(handle);
577     amfree(hostname);
578     amfree(qdiskname);
579     amfree(diskname);
580     amfree(device);
581     amfree(dumpdate);
582     amfree(progname);
583     amfree(srvcompprog);
584     amfree(clntcompprog);
585     amfree(srv_encrypt);
586     amfree(clnt_encrypt);
587     amfree(srv_decrypt_opt);
588     amfree(clnt_decrypt_opt);
589     amfree(options);
590     amfree(config_dir);
591     amfree(config_name);
592
593     malloc_size_2 = malloc_inuse(&malloc_hist_2);
594
595     if (malloc_size_1 != malloc_size_2) {
596         malloc_list(fileno(stderr), malloc_hist_1, malloc_hist_2);
597     }
598
599     dbclose();
600     return (0); /* exit */
601 }
602
603
604 /*
605  * Initialize a databuf.  Takes a writeable file descriptor.
606  */
607 static void
608 databuf_init(
609     struct databuf *    db,
610     int                 fd)
611 {
612
613     db->fd = fd;
614     db->datain = db->dataout = db->datalimit = NULL;
615     db->compresspid = -1;
616     db->encryptpid = -1;
617 }
618
619
620 /*
621  * Updates the buffer pointer for the input data buffer.  The buffer is
622  * written regardless of how much data is present, since we know we
623  * are writing to a socket (to chunker) and there is no need to maintain
624  * any boundaries.
625  */
626 static int
627 databuf_write(
628     struct databuf *    db,
629     const void *        buf,
630     size_t              size)
631 {
632     db->buf = (char *)buf;
633     db->datain = db->datalimit = db->buf + size;
634     db->dataout = db->buf;
635     return databuf_flush(db);
636 }
637
638 /*
639  * Write out the buffer to chunker.
640  */
641 static int
642 databuf_flush(
643     struct databuf *    db)
644 {
645     ssize_t written;
646
647     /*
648      * If there's no data, do nothing.
649      */
650     if (db->dataout >= db->datain) {
651         return 0;
652     }
653
654     /*
655      * Write out the buffer
656      */
657     written = fullwrite(db->fd, db->dataout,
658                         (size_t)(db->datain - db->dataout));
659     if (written > 0) {
660         db->dataout += written;
661         dumpbytes += (off_t)written;
662     }
663     if (dumpbytes >= (off_t)1024) {
664         dumpsize += (dumpbytes / (off_t)1024);
665         dumpbytes %= (off_t)1024;
666     }
667     if (written < 0) {
668         errstr = squotef("data write: %s", strerror(errno));
669         return -1;
670     }
671     db->datain = db->dataout = db->buf;
672     return 0;
673 }
674
675 static int dump_result;
676 static int status;
677 #define GOT_INFO_ENDLINE        (1 << 0)
678 #define GOT_SIZELINE            (1 << 1)
679 #define GOT_ENDLINE             (1 << 2)
680 #define HEADER_DONE             (1 << 3)
681
682
683 static void
684 process_dumpeof(void)
685 {
686     /* process any partial line in msgbuf? !!! */
687     add_msg_data(NULL, 0);
688     if(!ISSET(status, GOT_SIZELINE) && dump_result < 2) {
689         /* make a note if there isn't already a failure */
690         fprintf(errf,
691                 "? %s: strange [missing size line from sendbackup]\n",
692                 get_pname());
693         if(errstr == NULL) {
694             errstr = stralloc("missing size line from sendbackup");
695         }
696         dump_result = max(dump_result, 2);
697     }
698
699     if(!ISSET(status, GOT_ENDLINE) && dump_result < 2) {
700         fprintf(errf,
701                 "? %s: strange [missing end line from sendbackup]\n",
702                 get_pname());
703         if(errstr == NULL) {
704             errstr = stralloc("missing end line from sendbackup");
705         }
706         dump_result = max(dump_result, 2);
707     }
708 }
709
710 /*
711  * Parse an information line from the client.
712  * We ignore unknown parameters and only remember the last
713  * of any duplicates.
714  */
715 static void
716 parse_info_line(
717     char *str)
718 {
719     static const struct {
720         const char *name;
721         char *value;
722         size_t len;
723     } fields[] = {
724         { "BACKUP", file.program, SIZEOF(file.program) },
725         { "DUMPER", file.dumper, SIZEOF(file.dumper) },
726         { "RECOVER_CMD", file.recover_cmd, SIZEOF(file.recover_cmd) },
727         { "COMPRESS_SUFFIX", file.comp_suffix, SIZEOF(file.comp_suffix) },
728         { "SERVER_CUSTOM_COMPRESS", file.srvcompprog, SIZEOF(file.srvcompprog) },
729         { "CLIENT_CUSTOM_COMPRESS", file.clntcompprog, SIZEOF(file.clntcompprog) },
730         { "SERVER_ENCRYPT", file.srv_encrypt, SIZEOF(file.srv_encrypt) },
731         { "CLIENT_ENCRYPT", file.clnt_encrypt, SIZEOF(file.clnt_encrypt) },
732         { "SERVER_DECRYPT_OPTION", file.srv_decrypt_opt, SIZEOF(file.srv_decrypt_opt) },
733         { "CLIENT_DECRYPT_OPTION", file.clnt_decrypt_opt, SIZEOF(file.clnt_decrypt_opt) }
734     };
735     char *name, *value;
736     size_t i;
737
738     if (strcmp(str, "end") == 0) {
739         SET(status, GOT_INFO_ENDLINE);
740         return;
741     }
742
743     name = strtok(str, "=");
744     if (name == NULL)
745         return;
746     value = strtok(NULL, "");
747     if (value == NULL)
748         return;
749
750     for (i = 0; i < SIZEOF(fields) / SIZEOF(fields[0]); i++) {
751         if (strcmp(name, fields[i].name) == 0) {
752             strncpy(fields[i].value, value, fields[i].len - 1);
753             fields[i].value[fields[i].len - 1] = '\0';
754             break;
755         }
756     }
757 }
758
759 static void
760 process_dumpline(
761     const char *        str)
762 {
763     char *buf, *tok;
764
765     buf = stralloc(str);
766
767     switch (*buf) {
768     case '|':
769         /* normal backup output line */
770         break;
771     case '?':
772         /* sendbackup detected something strange */
773         dump_result = max(dump_result, 1);
774         break;
775     case 's':
776         /* a sendbackup line, just check them all since there are only 5 */
777         tok = strtok(buf, " ");
778         if (tok == NULL || strcmp(tok, "sendbackup:") != 0)
779             goto bad_line;
780
781         tok = strtok(NULL, " ");
782         if (tok == NULL)
783             goto bad_line;
784
785         if (strcmp(tok, "start") == 0) {
786             break;
787         }
788
789         if (strcmp(tok, "size") == 0) {
790             tok = strtok(NULL, "");
791             if (tok != NULL) {
792                 origsize = OFF_T_ATOI(tok);
793                 SET(status, GOT_SIZELINE);
794             }
795             break;
796         }
797
798         if (strcmp(tok, "end") == 0) {
799             SET(status, GOT_ENDLINE);
800             break;
801         }
802
803         if (strcmp(tok, "warning") == 0) {
804             dump_result = max(dump_result, 1);
805             break;
806         }
807
808         if (strcmp(tok, "error") == 0) {
809             SET(status, GOT_ENDLINE);
810             dump_result = max(dump_result, 2);
811
812             tok = strtok(NULL, "");
813             if (tok == NULL || *tok != '[') {
814                 errstr = newvstralloc(errstr, "bad remote error: ", str, NULL);
815             } else {
816                 char *enderr;
817
818                 tok++;  /* skip over '[' */
819                 if ((enderr = strchr(tok, ']')) != NULL)
820                     *enderr = '\0';
821                 errstr = newstralloc(errstr, tok);
822             }
823             break;
824         }
825
826         if (strcmp(tok, "info") == 0) {
827             tok = strtok(NULL, "");
828             if (tok != NULL)
829                 parse_info_line(tok);
830             break;
831         }
832         /* else we fall through to bad line */
833     default:
834 bad_line:
835         /* prefix with ?? */
836         fprintf(errf, "??");
837         dump_result = max(dump_result, 1);
838         break;
839     }
840     fprintf(errf, "%s\n", str);
841     amfree(buf);
842 }
843
844 static void
845 add_msg_data(
846     const char *        str,
847     size_t              len)
848 {
849     static struct {
850         char *buf;      /* buffer holding msg data */
851         size_t size;    /* size of alloced buffer */
852     } msg = { NULL, 0 };
853     char *line, *ch;
854     size_t buflen;
855     int in_quotes = 0;
856
857     if (msg.buf != NULL)
858         buflen = strlen(msg.buf);
859     else
860         buflen = 0;
861
862     /*
863      * If our argument is NULL, then we need to flush out any remaining
864      * bits and return.
865      */
866     if (str == NULL) {
867         if (buflen == 0)
868             return;
869         fprintf(errf,"? %s: error [partial line in msgbuf: "
870                                 SIZE_T_FMT " bytes]\n", get_pname(),
871                                 (SIZE_T_FMT_TYPE)buflen);
872         fprintf(errf,"? %s: error [partial line in msgbuf: \"%s\"]\n",
873             get_pname(), msg.buf);
874         msg.buf[0] = '\0';
875         return;
876     }
877
878     /*
879      * Expand the buffer if it can't hold the new contents.
880      */
881     if ((buflen + len + 1) > msg.size) {
882         char *newbuf;
883         size_t newsize;
884
885 /* round up to next y, where y is a power of 2 */
886 #define ROUND(x, y)     (((x) + (y) - 1) & ~((y) - 1))
887
888         newsize = ROUND(buflen + (ssize_t)len + 1, 256);
889         newbuf = alloc(newsize);
890
891         if (msg.buf != NULL) {
892             strncpy(newbuf, msg.buf, newsize);
893             amfree(msg.buf);
894         } else
895             newbuf[0] = '\0';
896         msg.buf = newbuf;
897         msg.size = newsize;
898     }
899
900     /*
901      * If there was a partial line from the last call, then
902      * append the new data to the end.
903      */
904     strncat(msg.buf, str, len);
905
906     /*
907      * Process all lines in the buffer
908      * scanning line for unqouted newline.
909      */
910     for (ch = line = msg.buf; *ch != '\0'; ch++) {
911         if (*ch == '"') {
912             in_quotes = !in_quotes;
913         } else if ((*ch == '\\') && (*(ch + 1) == '"')) {
914                 ch++;
915         } else if (!in_quotes && (*ch == '\n')) {
916             /*
917              * Found an unqouted newline.  Terminate and process line.
918              */
919             *ch = '\0';
920             process_dumpline(line);
921             line = ch + 1;
922         }
923     }
924
925     /*
926      * If we did not process all of the data, move it to the front
927      * of the buffer so it is there next time.
928      */
929     if (*line != '\0') {
930         buflen = strlen(line);
931         memmove(msg.buf, line, (size_t)buflen + 1);
932     } else {
933         msg.buf[0] = '\0';
934     }
935 }
936
937
938 static void
939 log_msgout(
940     logtype_t   typ)
941 {
942     char *line;
943
944     fflush(errf);
945     if (fseek(errf, 0L, SEEK_SET) < 0) {
946         dbprintf(("log_msgout: warning - seek failed: %s\n", strerror(errno)));
947     }
948     while ((line = agets(errf)) != NULL) {
949         if (line[0] != '\0') {
950                 log_add(typ, "%s", line);
951         }
952         amfree(line);
953     }
954
955     afclose(errf);
956 }
957
958 /* ------------- */
959
960 /*
961  * Fill in the rest of the tape header
962  */
963 static void
964 finish_tapeheader(
965     dumpfile_t *file)
966 {
967
968     assert(ISSET(status, HEADER_DONE));
969
970     file->type = F_DUMPFILE;
971     strncpy(file->datestamp, dumper_timestamp, sizeof(file->datestamp) - 1);
972     strncpy(file->name, hostname, SIZEOF(file->name) - 1);
973     strncpy(file->disk, diskname, SIZEOF(file->disk) - 1);
974     file->dumplevel = level;
975
976     /*
977      * If we're doing the compression here, we need to override what
978      * sendbackup told us the compression was.
979      */
980     if (srvcompress != COMP_NONE) {
981         file->compressed = 1;
982 #ifndef UNCOMPRESS_OPT
983 #define UNCOMPRESS_OPT  ""
984 #endif
985         if (srvcompress == COMP_SERVER_CUST) {
986             snprintf(file->uncompress_cmd, SIZEOF(file->uncompress_cmd),
987                      " %s %s |", srvcompprog, "-d");
988             strncpy(file->comp_suffix, "cust", SIZEOF(file->comp_suffix) - 1);
989             file->comp_suffix[SIZEOF(file->comp_suffix) - 1] = '\0';
990             strncpy(file->srvcompprog, srvcompprog, SIZEOF(file->srvcompprog) - 1);
991             file->srvcompprog[SIZEOF(file->srvcompprog) - 1] = '\0';
992         } else if ( srvcompress == COMP_CUST ) {
993             snprintf(file->uncompress_cmd, SIZEOF(file->uncompress_cmd),
994                      " %s %s |", clntcompprog, "-d");
995             strncpy(file->comp_suffix, "cust", SIZEOF(file->comp_suffix) - 1);
996             file->comp_suffix[SIZEOF(file->comp_suffix) - 1] = '\0';
997             strncpy(file->clntcompprog, clntcompprog, SIZEOF(file->clntcompprog));
998             file->clntcompprog[SIZEOF(file->clntcompprog) - 1] = '\0';
999         } else {
1000             snprintf(file->uncompress_cmd, SIZEOF(file->uncompress_cmd),
1001                 " %s %s |", UNCOMPRESS_PATH, UNCOMPRESS_OPT);
1002             strncpy(file->comp_suffix, COMPRESS_SUFFIX,SIZEOF(file->comp_suffix) - 1);
1003             file->comp_suffix[SIZEOF(file->comp_suffix) - 1] = '\0';
1004         }
1005     } else {
1006         if (file->comp_suffix[0] == '\0') {
1007             file->compressed = 0;
1008             assert(SIZEOF(file->comp_suffix) >= 2);
1009             strncpy(file->comp_suffix, "N", SIZEOF(file->comp_suffix) - 1);
1010             file->comp_suffix[SIZEOF(file->comp_suffix) - 1] = '\0';
1011         } else {
1012             file->compressed = 1;
1013         }
1014     }
1015     /* take care of the encryption header here */
1016     if (srvencrypt != ENCRYPT_NONE) {
1017       file->encrypted= 1;
1018       if (srvencrypt == ENCRYPT_SERV_CUST) {
1019         snprintf(file->decrypt_cmd, SIZEOF(file->decrypt_cmd),
1020                  " %s %s |", srv_encrypt, srv_decrypt_opt); 
1021         strncpy(file->encrypt_suffix, "enc", SIZEOF(file->encrypt_suffix) - 1);
1022         file->encrypt_suffix[SIZEOF(file->encrypt_suffix) - 1] = '\0';
1023         strncpy(file->srv_encrypt, srv_encrypt, SIZEOF(file->srv_encrypt) - 1);
1024         file->srv_encrypt[SIZEOF(file->srv_encrypt) - 1] = '\0';
1025         strncpy(file->srv_decrypt_opt, srv_decrypt_opt, SIZEOF(file->srv_decrypt_opt) - 1);
1026         file->srv_decrypt_opt[SIZEOF(file->srv_decrypt_opt) - 1] = '\0';
1027       } else if ( srvencrypt == ENCRYPT_CUST ) {
1028         snprintf(file->decrypt_cmd, SIZEOF(file->decrypt_cmd),
1029                  " %s %s |", clnt_encrypt, clnt_decrypt_opt);
1030         strncpy(file->encrypt_suffix, "enc", SIZEOF(file->encrypt_suffix) - 1);
1031         file->encrypt_suffix[SIZEOF(file->encrypt_suffix) - 1] = '\0';
1032         strncpy(file->clnt_encrypt, clnt_encrypt, SIZEOF(file->clnt_encrypt) - 1);
1033         file->clnt_encrypt[SIZEOF(file->clnt_encrypt) - 1] = '\0';
1034         strncpy(file->clnt_decrypt_opt, clnt_decrypt_opt, SIZEOF(file->clnt_decrypt_opt));
1035         file->clnt_decrypt_opt[SIZEOF(file->clnt_decrypt_opt) - 1] = '\0';
1036       }
1037     } else {
1038       if (file->encrypt_suffix[0] == '\0') {
1039         file->encrypted = 0;
1040         assert(SIZEOF(file->encrypt_suffix) >= 2);
1041         strncpy(file->encrypt_suffix, "N", SIZEOF(file->encrypt_suffix) - 1);
1042         file->encrypt_suffix[SIZEOF(file->encrypt_suffix) - 1] = '\0';
1043       } else {
1044         file->encrypted= 1;
1045       }
1046     }
1047 }
1048
1049 /*
1050  * Send an Amanda dump header to the output file.
1051  */
1052 static ssize_t
1053 write_tapeheader(
1054     int         outfd,
1055     dumpfile_t *file)
1056 {
1057     char buffer[DISK_BLOCK_BYTES];
1058     ssize_t written;
1059
1060     build_header(buffer, file, SIZEOF(buffer));
1061
1062     written = fullwrite(outfd, buffer, SIZEOF(buffer));
1063     if(written == (ssize_t)sizeof(buffer))
1064         return 0;
1065     if(written < 0)
1066         return written;
1067
1068     return -1;
1069 }
1070
1071 static int
1072 do_dump(
1073     struct databuf *db)
1074 {
1075     char *indexfile_tmp = NULL;
1076     char *indexfile_real = NULL;
1077     char level_str[NUM_STR_SIZE];
1078     char *fn;
1079     char *q;
1080     times_t runtime;
1081     double dumptime;    /* Time dump took in secs */
1082     char *errfname = NULL;
1083     int indexout;
1084     pid_t indexpid = -1;
1085
1086     startclock();
1087
1088     status = 0;
1089     dump_result = 0;
1090     dumpbytes = dumpsize = headersize = origsize = (off_t)0;
1091     fh_init(&file);
1092
1093     snprintf(level_str, SIZEOF(level_str), "%d", level);
1094     fn = sanitise_filename(diskname);
1095     errfname = newvstralloc(errfname,
1096                             AMANDA_TMPDIR,
1097                             "/", hostname,
1098                             ".", fn,
1099                             ".", level_str,
1100                             ".errout",
1101                             NULL);
1102     amfree(fn);
1103     if((errf = fopen(errfname, "w+")) == NULL) {
1104         errstr = newvstralloc(errstr,
1105                               "errfile open \"", errfname, "\": ",
1106                               strerror(errno),
1107                               NULL);
1108         amfree(errfname);
1109         goto failed;
1110     }
1111     unlink(errfname);                           /* so it goes away on close */
1112     amfree(errfname);
1113
1114     if (streams[INDEXFD].fd != NULL) {
1115         indexfile_real = getindexfname(hostname, diskname, dumper_timestamp, level);
1116         indexfile_tmp = stralloc2(indexfile_real, ".tmp");
1117
1118         if (mkpdir(indexfile_tmp, 02755, (uid_t)-1, (gid_t)-1) == -1) {
1119            errstr = newvstralloc(errstr,
1120                                  "err create ",
1121                                  indexfile_tmp,
1122                                  ": ",
1123                                  strerror(errno),
1124                                  NULL);
1125            amfree(indexfile_real);
1126            amfree(indexfile_tmp);
1127            goto failed;
1128         }
1129         indexout = open(indexfile_tmp, O_WRONLY | O_CREAT | O_TRUNC, 0600);
1130         if (indexout == -1) {
1131             errstr = newvstralloc(errstr, "err open ", indexfile_tmp, ": ",
1132                 strerror(errno), NULL);
1133             goto failed;
1134         } else {
1135             if (runcompress(indexout, &indexpid, COMP_BEST) < 0) {
1136                 aclose(indexout);
1137                 goto failed;
1138             }
1139         }
1140         indexfderror = 0;
1141         /*
1142          * Schedule the indexfd for relaying to the index file
1143          */
1144         security_stream_read(streams[INDEXFD].fd, read_indexfd, &indexout);
1145     }
1146
1147     /*
1148      * We only need to process messages initially.  Once we have done
1149      * the header, we will start processing data too.
1150      */
1151     security_stream_read(streams[MESGFD].fd, read_mesgfd, db);
1152     set_datafd = 0;
1153
1154     /*
1155      * Setup a read timeout
1156      */
1157     timeout(conf_dtimeout);
1158
1159     /*
1160      * Start the event loop.  This will exit when all three events
1161      * (read the mesgfd, read the datafd, and timeout) are removed.
1162      */
1163     event_loop(0);
1164
1165     if (dump_result > 1)
1166         goto failed;
1167
1168     runtime = stopclock();
1169     dumptime = (double)(runtime.r.tv_sec) +
1170                ((double)(runtime.r.tv_usec) / 1000000.0);
1171
1172     dumpsize -= headersize;             /* don't count the header */
1173     if (dumpsize < (off_t)0)            /* XXX - maybe this should be fatal? */
1174         dumpsize = (off_t)0;
1175
1176     amfree(errstr);
1177     errstr = alloc(128);
1178     snprintf(errstr, 128, "sec %s kb " OFF_T_FMT " kps %3.1lf orig-kb " OFF_T_FMT "",
1179         walltime_str(runtime),
1180         (OFF_T_FMT_TYPE)dumpsize,
1181         (isnormal(dumptime) ? ((double)dumpsize / (double)dumptime) : 0.0),
1182         (OFF_T_FMT_TYPE)origsize);
1183     q = squotef("[%s]", errstr);
1184     putresult(DONE, "%s " OFF_T_FMT " " OFF_T_FMT " %lu %s\n", handle,
1185                 (OFF_T_FMT_TYPE)origsize,
1186                 (OFF_T_FMT_TYPE)dumpsize,
1187                 (unsigned long)((double)dumptime+0.5), q);
1188     amfree(q);
1189
1190     switch(dump_result) {
1191     case 0:
1192         log_add(L_SUCCESS, "%s %s %s %d [%s]", hostname, qdiskname, dumper_timestamp, level, errstr);
1193
1194         break;
1195
1196     case 1:
1197         log_start_multiline();
1198         log_add(L_STRANGE, "%s %s %d [%s]", hostname, qdiskname, level, errstr);
1199         log_msgout(L_STRANGE);
1200         log_end_multiline();
1201
1202         break;
1203     }
1204
1205     if (errf) afclose(errf);
1206
1207     aclose(db->fd);
1208     if (indexfile_tmp) {
1209         amwait_t index_status;
1210
1211         /*@i@*/ aclose(indexout);
1212         waitpid(indexpid,&index_status,0);
1213         if (rename(indexfile_tmp, indexfile_real) != 0) {
1214             log_add(L_WARNING, "could not rename \"%s\" to \"%s\": %s",
1215                     indexfile_tmp, indexfile_real, strerror(errno));
1216         }
1217         amfree(indexfile_tmp);
1218         amfree(indexfile_real);
1219     }
1220
1221     if(db->compresspid != -1) {
1222         waitpid(db->compresspid,NULL,0);
1223     }
1224     if(db->encryptpid != -1) {
1225         waitpid(db->encryptpid,NULL,0);
1226     }
1227
1228     amfree(errstr);
1229
1230     return 1;
1231
1232 failed:
1233     q = squotef("[%s]", errstr);
1234     putresult(FAILED, "%s %s\n", handle, q);
1235     amfree(q);
1236
1237     aclose(db->fd);
1238     /* kill all child process */
1239     if (db->compresspid != -1) {
1240         fprintf(stderr,"%s: kill compress command\n",get_pname());
1241         if (kill(db->compresspid, SIGTERM) < 0) {
1242             if (errno != ESRCH)
1243                 fprintf(stderr,"%s: can't kill compress command: %s\n", 
1244                     get_pname(), strerror(errno));
1245         }
1246         else {
1247             waitpid(db->compresspid,NULL,0);
1248         }
1249     }
1250
1251     if (db->encryptpid != -1) {
1252         fprintf(stderr,"%s: kill encrypt command\n",get_pname());
1253         if (kill(db->encryptpid, SIGTERM) < 0) {
1254             if (errno != ESRCH)
1255                 fprintf(stderr,"%s: can't kill encrypt command: %s\n", 
1256                     get_pname(), strerror(errno));
1257         }
1258         else {
1259             waitpid(db->encryptpid,NULL,0);
1260         }
1261     }
1262
1263     if (indexpid != -1) {
1264         fprintf(stderr,"%s: kill index command\n",get_pname());
1265         if (kill(indexpid, SIGTERM) < 0) {
1266             if (errno != ESRCH)
1267                 fprintf(stderr,"%s: can't kill index command: %s\n", 
1268                     get_pname(),strerror(errno));
1269         }
1270         else {
1271             waitpid(indexpid,NULL,0);
1272         }
1273     }
1274
1275     log_start_multiline();
1276     log_add(L_FAIL, "%s %s %s %d [%s]", hostname, qdiskname, dumper_timestamp,
1277             level, errstr);
1278     if (errf) {
1279         log_msgout(L_FAIL);
1280     }
1281     log_end_multiline();
1282
1283     if (errf) afclose(errf);
1284
1285     if (indexfile_tmp) {
1286         unlink(indexfile_tmp);
1287         amfree(indexfile_tmp);
1288         amfree(indexfile_real);
1289     }
1290
1291     return 0;
1292 }
1293
1294 /*
1295  * Callback for reads on the mesgfd stream
1296  */
1297 static void
1298 read_mesgfd(
1299     void *      cookie,
1300     void *      buf,
1301     ssize_t     size)
1302 {
1303     struct databuf *db = cookie;
1304
1305     assert(db != NULL);
1306
1307     switch (size) {
1308     case -1:
1309         errstr = newstralloc2(errstr, "mesg read: ",
1310             security_stream_geterror(streams[MESGFD].fd));
1311         dump_result = 2;
1312         stop_dump();
1313         return;
1314
1315     case 0:
1316         /*
1317          * EOF.  Just shut down the mesg stream.
1318          */
1319         process_dumpeof();
1320         security_stream_close(streams[MESGFD].fd);
1321         streams[MESGFD].fd = NULL;
1322         /*
1323          * If the data fd and index fd has also shut down, then we're done.
1324          */
1325         if ((set_datafd == 0 || streams[DATAFD].fd == NULL) && 
1326             streams[INDEXFD].fd == NULL)
1327             stop_dump();
1328         return;
1329
1330     default:
1331         assert(buf != NULL);
1332         add_msg_data(buf, (size_t)size);
1333         security_stream_read(streams[MESGFD].fd, read_mesgfd, cookie);
1334         break;
1335     }
1336
1337     if (ISSET(status, GOT_INFO_ENDLINE) && !ISSET(status, HEADER_DONE)) {
1338         SET(status, HEADER_DONE);
1339         /* time to do the header */
1340         finish_tapeheader(&file);
1341         if (write_tapeheader(db->fd, &file)) {
1342             errstr = newstralloc2(errstr, "write_tapeheader: ", 
1343                                   strerror(errno));
1344             dump_result = 2;
1345             stop_dump();
1346             return;
1347         }
1348         dumpsize += (off_t)DISK_BLOCK_KB;
1349         headersize += (off_t)DISK_BLOCK_KB;
1350
1351         if (srvencrypt == ENCRYPT_SERV_CUST) {
1352             if (runencrypt(db->fd, &db->encryptpid, srvencrypt) < 0) {
1353                 dump_result = 2;
1354                 stop_dump();
1355                 return;
1356             }
1357         }
1358         /*
1359          * Now, setup the compress for the data output, and start
1360          * reading the datafd.
1361          */
1362         if ((srvcompress != COMP_NONE) && (srvcompress != COMP_CUST)) {
1363             if (runcompress(db->fd, &db->compresspid, srvcompress) < 0) {
1364                 dump_result = 2;
1365                 stop_dump();
1366                 return;
1367             }
1368         }
1369         security_stream_read(streams[DATAFD].fd, read_datafd, db);
1370         set_datafd = 1;
1371     }
1372
1373     /*
1374      * Reset the timeout for future reads
1375      */
1376     timeout(conf_dtimeout);
1377 }
1378
1379 /*
1380  * Callback for reads on the datafd stream
1381  */
1382 static void
1383 read_datafd(
1384     void *      cookie,
1385     void *      buf,
1386     ssize_t     size)
1387 {
1388     struct databuf *db = cookie;
1389
1390     assert(db != NULL);
1391
1392     /*
1393      * The read failed.  Error out
1394      */
1395     if (size < 0) {
1396         errstr = newstralloc2(errstr, "data read: ",
1397             security_stream_geterror(streams[DATAFD].fd));
1398         dump_result = 2;
1399         stop_dump();
1400         return;
1401     }
1402
1403     /* The header had better be written at this point */
1404     assert(ISSET(status, HEADER_DONE));
1405
1406     /*
1407      * EOF.  Stop and return.
1408      */
1409     if (size == 0) {
1410         databuf_flush(db);
1411         if (dumpbytes != (off_t)0) {
1412             dumpsize += (off_t)1;
1413         }
1414         security_stream_close(streams[DATAFD].fd);
1415         streams[DATAFD].fd = NULL;
1416         /*
1417          * If the mesg fd and index fd has also shut down, then we're done.
1418          */
1419         if (streams[MESGFD].fd == NULL && streams[INDEXFD].fd == NULL)
1420             stop_dump();
1421         return;
1422     }
1423
1424     /*
1425      * We read something.  Add it to the databuf and reschedule for
1426      * more data.
1427      */
1428     assert(buf != NULL);
1429     if (databuf_write(db, buf, (size_t)size) < 0) {
1430         errstr = newstralloc2(errstr, "data write: ", strerror(errno));
1431         dump_result = 2;
1432         stop_dump();
1433         return;
1434     }
1435
1436     /*
1437      * Reset the timeout for future reads
1438      */
1439     timeout(conf_dtimeout);
1440
1441     security_stream_read(streams[DATAFD].fd, read_datafd, cookie);
1442 }
1443
1444 /*
1445  * Callback for reads on the index stream
1446  */
1447 static void
1448 read_indexfd(
1449     void *      cookie,
1450     void *      buf,
1451     ssize_t     size)
1452 {
1453     int fd;
1454
1455     assert(cookie != NULL);
1456     fd = *(int *)cookie;
1457
1458     if (size < 0) {
1459         errstr = newstralloc2(errstr, "index read: ",
1460             security_stream_geterror(streams[INDEXFD].fd));
1461         dump_result = 2;
1462         stop_dump();
1463         return;
1464     }
1465
1466     /*
1467      * EOF.  Stop and return.
1468      */
1469     if (size == 0) {
1470         security_stream_close(streams[INDEXFD].fd);
1471         streams[INDEXFD].fd = NULL;
1472         /*
1473          * If the mesg fd has also shut down, then we're done.
1474          */
1475         if ((set_datafd == 0 || streams[DATAFD].fd == NULL) &&
1476              streams[MESGFD].fd == NULL)
1477             stop_dump();
1478         return;
1479     }
1480
1481     assert(buf != NULL);
1482
1483     /*
1484      * We ignore error while writing to the index file.
1485      */
1486     if (fullwrite(fd, buf, (size_t)size) < 0) {
1487         /* Ignore error, but schedule another read. */
1488         if(indexfderror == 0) {
1489             indexfderror = 1;
1490             log_add(L_INFO, "Index corrupted for %s:%s", hostname, qdiskname);
1491         }
1492     }
1493     security_stream_read(streams[INDEXFD].fd, read_indexfd, cookie);
1494 }
1495
1496 /*
1497  * Startup a timeout in the event handler.  If the arg is 0,
1498  * then remove the timeout.
1499  */
1500 static void
1501 timeout(
1502     time_t seconds)
1503 {
1504     static event_handle_t *ev_timeout = NULL;
1505
1506     /*
1507      * First, remove a timeout if one is active.
1508      */
1509     if (ev_timeout != NULL) {
1510         event_release(ev_timeout);
1511         ev_timeout = NULL;
1512     }
1513
1514     /*
1515      * Now, schedule a new one if 'seconds' is greater than 0
1516      */
1517     if (seconds > 0)
1518         ev_timeout = event_register((event_id_t)seconds, EV_TIME, timeout_callback, NULL);
1519 }
1520
1521 /*
1522  * This is the callback for timeout().  If this is reached, then we
1523  * have a data timeout.
1524  */
1525 static void
1526 timeout_callback(
1527     void *      unused)
1528 {
1529     (void)unused;       /* Quiet unused parameter warning */
1530
1531     assert(unused == NULL);
1532     errstr = newstralloc(errstr, "data timeout");
1533     dump_result = 2;
1534     stop_dump();
1535 }
1536
1537 /*
1538  * This is called when everything needs to shut down so event_loop()
1539  * will exit.
1540  */
1541 static void
1542 stop_dump(void)
1543 {
1544     int i;
1545
1546     for (i = 0; i < NSTREAMS; i++) {
1547         if (streams[i].fd != NULL) {
1548             security_stream_close(streams[i].fd);
1549             streams[i].fd = NULL;
1550         }
1551     }
1552     timeout(0);
1553 }
1554
1555
1556 /*
1557  * Runs compress with the first arg as its stdout.  Returns
1558  * 0 on success or negative if error, and it's pid via the second
1559  * argument.  The outfd arg is dup2'd to the pipe to the compress
1560  * process.
1561  */
1562 static int
1563 runcompress(
1564     int         outfd,
1565     pid_t *     pid,
1566     comp_t      comptype)
1567 {
1568     int outpipe[2], rval;
1569
1570     assert(outfd >= 0);
1571     assert(pid != NULL);
1572
1573     /* outpipe[0] is pipe's stdin, outpipe[1] is stdout. */
1574     if (pipe(outpipe) < 0) {
1575         errstr = newstralloc2(errstr, "pipe: ", strerror(errno));
1576         return (-1);
1577     }
1578
1579     switch (*pid = fork()) {
1580     case -1:
1581         errstr = newstralloc2(errstr, "couldn't fork: ", strerror(errno));
1582         aclose(outpipe[0]);
1583         aclose(outpipe[1]);
1584         return (-1);
1585     default:
1586         rval = dup2(outpipe[1], outfd);
1587         if (rval < 0)
1588             errstr = newstralloc2(errstr, "couldn't dup2: ", strerror(errno));
1589         aclose(outpipe[1]);
1590         aclose(outpipe[0]);
1591         return (rval);
1592     case 0:
1593         if (dup2(outpipe[0], 0) < 0) {
1594             error("err dup2 in: %s", strerror(errno));
1595             /*NOTREACHED*/
1596         }
1597         if (dup2(outfd, 1) == -1) {
1598             error("err dup2 out: %s", strerror(errno));
1599             /*NOTREACHED*/
1600         }
1601         safe_fd(-1, 0);
1602         if (comptype != COMP_SERVER_CUST) {
1603             execlp(COMPRESS_PATH, COMPRESS_PATH, (  comptype == COMP_BEST ?
1604                 COMPRESS_BEST_OPT : COMPRESS_FAST_OPT), (char *)NULL);
1605             error("error: couldn't exec %s: %s", COMPRESS_PATH, strerror(errno));
1606             /*NOTREACHED*/
1607         } else if (*srvcompprog) {
1608             execlp(srvcompprog, srvcompprog, (char *)0);
1609             error("error: couldn't exec server custom filter%s.\n", srvcompprog);
1610             /*NOTREACHED*/
1611         }
1612     }
1613     /*NOTREACHED*/
1614     return (-1);
1615 }
1616
1617 /*
1618  * Runs encrypt with the first arg as its stdout.  Returns
1619  * 0 on success or negative if error, and it's pid via the second
1620  * argument.  The outfd arg is dup2'd to the pipe to the encrypt
1621  * process.
1622  */
1623 static int
1624 runencrypt(
1625     int         outfd,
1626     pid_t *     pid,
1627     encrypt_t   encrypttype)
1628 {
1629     int outpipe[2], rval;
1630
1631     assert(outfd >= 0);
1632     assert(pid != NULL);
1633
1634     /* outpipe[0] is pipe's stdin, outpipe[1] is stdout. */
1635     if (pipe(outpipe) < 0) {
1636         errstr = newstralloc2(errstr, "pipe: ", strerror(errno));
1637         return (-1);
1638     }
1639
1640     switch (*pid = fork()) {
1641     case -1:
1642         errstr = newstralloc2(errstr, "couldn't fork: ", strerror(errno));
1643         aclose(outpipe[0]);
1644         aclose(outpipe[1]);
1645         return (-1);
1646     default:
1647         rval = dup2(outpipe[1], outfd);
1648         if (rval < 0)
1649             errstr = newstralloc2(errstr, "couldn't dup2: ", strerror(errno));
1650         aclose(outpipe[1]);
1651         aclose(outpipe[0]);
1652         return (rval);
1653     case 0:
1654         if (dup2(outpipe[0], 0) < 0) {
1655             error("err dup2 in: %s", strerror(errno));
1656             /*NOTREACHED*/
1657         }
1658         if (dup2(outfd, 1) < 0 ) {
1659             error("err dup2 out: %s", strerror(errno));
1660             /*NOTREACHED*/
1661         }
1662         safe_fd(-1, 0);
1663         if ((encrypttype == ENCRYPT_SERV_CUST) && *srv_encrypt) {
1664             execlp(srv_encrypt, srv_encrypt, (char *)0);
1665             error("error: couldn't exec server encryption%s.\n", srv_encrypt);
1666             /*NOTREACHED*/
1667         }
1668     }
1669     /*NOTREACHED*/
1670     return (-1);
1671 }
1672
1673
1674 /* -------------------- */
1675
1676 static void
1677 sendbackup_response(
1678     void *              datap,
1679     pkt_t *             pkt,
1680     security_handle_t * sech)
1681 {
1682     int ports[NSTREAMS], *response_error = datap, i;
1683     char *p;
1684     char *tok;
1685     char *extra;
1686
1687     assert(response_error != NULL);
1688     assert(sech != NULL);
1689
1690     if (pkt == NULL) {
1691         errstr = newvstralloc(errstr, "[request failed: ",
1692             security_geterror(sech), "]", NULL);
1693         *response_error = 1;
1694         return;
1695     }
1696
1697     security_close_connection(sech, hostname);
1698
1699     extra = NULL;
1700     memset(ports, 0, SIZEOF(ports));
1701     if (pkt->type == P_NAK) {
1702 #if defined(PACKET_DEBUG)
1703         fprintf(stderr, "got nak response:\n----\n%s\n----\n\n", pkt->body);
1704 #endif
1705
1706         tok = strtok(pkt->body, " ");
1707         if (tok == NULL || strcmp(tok, "ERROR") != 0)
1708             goto bad_nak;
1709
1710         tok = strtok(NULL, "\n");
1711         if (tok != NULL) {
1712             errstr = newvstralloc(errstr, "NAK: ", tok, NULL);
1713             *response_error = 1;
1714         } else {
1715 bad_nak:
1716             errstr = newstralloc(errstr, "request NAK");
1717             *response_error = 2;
1718         }
1719         return;
1720     }
1721
1722     if (pkt->type != P_REP) {
1723         errstr = newvstralloc(errstr, "received strange packet type ",
1724             pkt_type2str(pkt->type), ": ", pkt->body, NULL);
1725         *response_error = 1;
1726         return;
1727     }
1728
1729 #if 1
1730     fprintf(stderr, "got response:\n----\n%s\n----\n\n", pkt->body);
1731 #endif
1732
1733     for(i = 0; i < NSTREAMS; i++) {
1734         ports[i] = -1;
1735         streams[i].fd = NULL;
1736     }
1737
1738     p = pkt->body;
1739     while((tok = strtok(p, " \n")) != NULL) {
1740         p = NULL;
1741
1742         /*
1743          * Error response packets have "ERROR" followed by the error message
1744          * followed by a newline.
1745          */
1746         if (strcmp(tok, "ERROR") == 0) {
1747             tok = strtok(NULL, "\n");
1748             if (tok == NULL)
1749                 tok = "[bogus error packet]";
1750             errstr = newstralloc(errstr, tok);
1751             *response_error = 2;
1752             return;
1753         }
1754
1755         /*
1756          * Regular packets have CONNECT followed by three streams
1757          */
1758         if (strcmp(tok, "CONNECT") == 0) {
1759
1760             /*
1761              * Parse the three stream specifiers out of the packet.
1762              */
1763             for (i = 0; i < NSTREAMS; i++) {
1764                 tok = strtok(NULL, " ");
1765                 if (tok == NULL || strcmp(tok, streams[i].name) != 0) {
1766                     extra = vstralloc("CONNECT token is \"",
1767                                       tok ? tok : "(null)",
1768                                       "\": expected \"",
1769                                       streams[i].name,
1770                                       "\"",
1771                                       NULL);
1772                     goto parse_error;
1773                 }
1774                 tok = strtok(NULL, " \n");
1775                 if (tok == NULL || sscanf(tok, "%d", &ports[i]) != 1) {
1776                     extra = vstralloc("CONNECT ",
1777                                       streams[i].name,
1778                                       " token is \"",
1779                                       tok ? tok : "(null)",
1780                                       "\": expected a port number",
1781                                       NULL);
1782                     goto parse_error;
1783                 }
1784             }
1785             continue;
1786         }
1787
1788         /*
1789          * OPTIONS [options string] '\n'
1790          */
1791         if (strcmp(tok, "OPTIONS") == 0) {
1792             tok = strtok(NULL, "\n");
1793             if (tok == NULL) {
1794                 extra = stralloc("OPTIONS token is missing");
1795                 goto parse_error;
1796             }
1797
1798             while((p = strchr(tok, ';')) != NULL) {
1799                 char ch;
1800                 *p++ = '\0';
1801                 if(strncmp_const_skip(tok, "features=", tok, ch) == 0) {
1802                     am_release_feature_set(their_features);
1803                     if((their_features = am_string_to_feature(tok)) == NULL) {
1804                         errstr = newvstralloc(errstr,
1805                                               "OPTIONS: bad features value: ",
1806                                               tok,
1807                                               NULL);
1808                         goto parse_error;
1809                     }
1810                 }
1811                 tok = p;
1812             }
1813             continue;
1814         }
1815
1816         extra = vstralloc("next token is \"",
1817                           tok ? tok : "(null)",
1818                           "\": expected \"CONNECT\", \"ERROR\" or \"OPTIONS\"",
1819                           NULL);
1820         goto parse_error;
1821     }
1822
1823     /*
1824      * Connect the streams to their remote ports
1825      */
1826     for (i = 0; i < NSTREAMS; i++) {
1827         if (ports[i] == -1)
1828             continue;
1829         streams[i].fd = security_stream_client(sech, ports[i]);
1830         if (streams[i].fd == NULL) {
1831             errstr = newvstralloc(errstr,
1832                 "[could not connect ", streams[i].name, " stream: ",
1833                 security_geterror(sech), "]", NULL);
1834             goto connect_error;
1835         }
1836     }
1837
1838     /*
1839      * Authenticate the streams
1840      */
1841     for (i = 0; i < NSTREAMS; i++) {
1842         if (streams[i].fd == NULL)
1843             continue;
1844 #ifdef KRB4_SECURITY
1845         /*
1846          * XXX krb4 historically never authenticated the index stream!
1847          * We need to reproduce this lossage here to preserve compatibility
1848          * with old clients.
1849          * It is wrong to delve into sech, but we have no choice here.
1850          */
1851         if (strcasecmp(sech->driver->name, "krb4") == 0 && i == INDEXFD)
1852             continue;
1853 #endif
1854         if (security_stream_auth(streams[i].fd) < 0) {
1855             errstr = newvstralloc(errstr,
1856                 "[could not authenticate ", streams[i].name, " stream: ",
1857                 security_stream_geterror(streams[i].fd), "]", NULL);
1858             goto connect_error;
1859         }
1860     }
1861
1862     /*
1863      * The MESGFD and DATAFD streams are mandatory.  If we didn't get
1864      * them, complain.
1865      */
1866     if (streams[MESGFD].fd == NULL || streams[DATAFD].fd == NULL) {
1867         errstr = newstralloc(errstr, "[couldn't open MESG or INDEX streams]");
1868         goto connect_error;
1869     }
1870
1871     /* everything worked */
1872     *response_error = 0;
1873     return;
1874
1875 parse_error:
1876     errstr = newvstralloc(errstr,
1877                           "[parse of reply message failed: ",
1878                           extra ? extra : "(no additional information)",
1879                           "]",
1880                           NULL);
1881     amfree(extra);
1882     *response_error = 2;
1883     return;
1884
1885 connect_error:
1886     stop_dump();
1887     *response_error = 1;
1888 }
1889
1890 static char *
1891 dumper_get_security_conf(
1892     char *      string,
1893     void *      arg)
1894 {
1895         (void)arg;      /* Quiet unused parameter warning */
1896
1897         if(!string || !*string)
1898                 return(NULL);
1899
1900         if(strcmp(string, "krb5principal")==0) {
1901                 return(getconf_str(CNF_KRB5PRINCIPAL));
1902         } else if(strcmp(string, "krb5keytab")==0) {
1903                 return(getconf_str(CNF_KRB5KEYTAB));
1904         } else if(strcmp(string, "amandad_path")==0) {
1905                 return (amandad_path);
1906         } else if(strcmp(string, "client_username")==0) {
1907                 return (client_username);
1908         } else if(strcmp(string, "ssh_keys")==0) {
1909                 return (ssh_keys);
1910         }
1911         return(NULL);
1912 }
1913
1914 static int
1915 startup_dump(
1916     const char *hostname,
1917     const char *disk,
1918     const char *device,
1919     int         level,
1920     const char *dumpdate,
1921     const char *progname,
1922     const char *amandad_path,
1923     const char *client_username,
1924     const char *ssh_keys,
1925     const char *options)
1926 {
1927     char level_string[NUM_STR_SIZE];
1928     char *req = NULL;
1929     char *authopt, *endauthopt, authoptbuf[80];
1930     int response_error;
1931     const security_driver_t *secdrv;
1932     char *backup_api;
1933     int has_features;
1934     int has_hostname;
1935     int has_device;
1936     int has_config;
1937
1938     (void)disk;                 /* Quiet unused parameter warning */
1939     (void)amandad_path;         /* Quiet unused parameter warning */
1940     (void)client_username;      /* Quiet unused parameter warning */
1941     (void)ssh_keys;             /* Quiet unused parameter warning */
1942
1943     has_features = am_has_feature(their_features, fe_req_options_features);
1944     has_hostname = am_has_feature(their_features, fe_req_options_hostname);
1945     has_config   = am_has_feature(their_features, fe_req_options_config);
1946     has_device   = am_has_feature(their_features, fe_sendbackup_req_device);
1947
1948     /*
1949      * Default to bsd authentication if none specified.  This is gross.
1950      *
1951      * Options really need to be pre-parsed into some sort of structure
1952      * much earlier, and then flattened out again before transmission.
1953      */
1954     authopt = strstr(options, "auth=");
1955     if (authopt == NULL) {
1956         authopt = "BSD";
1957     } else {
1958         endauthopt = strchr(authopt, ';');
1959         if ((endauthopt == NULL) ||
1960           ((sizeof(authoptbuf) - 1) < (size_t)(endauthopt - authopt))) {
1961             authopt = "BSD";
1962         } else {
1963             authopt += strlen("auth=");
1964             strncpy(authoptbuf, authopt, (size_t)(endauthopt - authopt));
1965             authoptbuf[endauthopt - authopt] = '\0';
1966             authopt = authoptbuf;
1967         }
1968     }
1969
1970     snprintf(level_string, SIZEOF(level_string), "%d", level);
1971     if(strcmp(progname, "DUMP") == 0
1972        || strcmp(progname, "GNUTAR") == 0) {
1973         backup_api = "";
1974     } else {
1975         backup_api = "BACKUP ";
1976     }
1977     req = vstralloc("SERVICE sendbackup\n",
1978                     "OPTIONS ",
1979                     has_features ? "features=" : "",
1980                     has_features ? our_feature_string : "",
1981                     has_features ? ";" : "",
1982                     has_hostname ? "hostname=" : "",
1983                     has_hostname ? hostname : "",
1984                     has_hostname ? ";" : "",
1985                     has_config   ? "config=" : "",
1986                     has_config   ? config_name : "",
1987                     has_config   ? ";" : "",
1988                     "\n",
1989                     backup_api, progname,
1990                     " ", qdiskname,
1991                     " ", device && has_device ? device : "",
1992                     " ", level_string,
1993                     " ", dumpdate,
1994                     " OPTIONS ", options,
1995                     /* compat: if auth=krb4, send krb4-auth */
1996                     (strcasecmp(authopt, "krb4") ? "" : "krb4-auth"),
1997                     "\n",
1998                     NULL);
1999
2000 fprintf(stderr, "send request:\n----\n%s\n----\n\n", req);
2001     secdrv = security_getdriver(authopt);
2002     if (secdrv == NULL) {
2003         error("no '%s' security driver available for host '%s'",
2004             authopt, hostname);
2005         /*NOTREACHED*/
2006     }
2007
2008     protocol_sendreq(hostname, secdrv, dumper_get_security_conf, req,
2009         STARTUP_TIMEOUT, sendbackup_response, &response_error);
2010
2011     amfree(req);
2012
2013     protocol_run();
2014     return (response_error);
2015 }