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