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