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