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