44caf87fcc90cae8e1577ee7dba21bf32b4eb602
[debian/amanda] / client-src / sendbackup.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 /* 
27  * $Id: sendbackup.c,v 1.88 2006/07/25 18:27:56 martinea Exp $
28  *
29  * common code for the sendbackup-* programs.
30  */
31
32 #include "amanda.h"
33 #include "sendbackup.h"
34 #include "clock.h"
35 #include "pipespawn.h"
36 #include "amfeatures.h"
37 #include "amandad.h"
38 #include "arglist.h"
39 #include "getfsent.h"
40 #include "version.h"
41 #include "conffile.h"
42 #include "amandates.h"
43
44 #define sendbackup_debug(i, ...) do {   \
45         if ((i) <= debug_sendbackup) {  \
46             dbprintf(__VA_LIST__);      \
47         }                               \
48 } while (0)
49
50 #define TIMEOUT 30
51
52 pid_t comppid = (pid_t)-1;
53 pid_t dumppid = (pid_t)-1;
54 pid_t tarpid = (pid_t)-1;
55 pid_t encpid = (pid_t)-1;
56 pid_t indexpid = (pid_t)-1;
57 pid_t application_api_pid = (pid_t)-1;
58 char *errorstr = NULL;
59
60 int datafd;
61 int mesgfd;
62 int indexfd;
63
64 g_option_t *g_options = NULL;
65
66 long dump_size = -1;
67
68 backup_program_t *program = NULL;
69 dle_t *gdle = NULL;
70
71 static am_feature_t *our_features = NULL;
72 static char *our_feature_string = NULL;
73 static char *amandad_auth = NULL;
74
75 /* local functions */
76 int main(int argc, char **argv);
77 char *childstr(pid_t pid);
78 int check_status(pid_t pid, amwait_t w, int mesgfd);
79
80 pid_t pipefork(void (*func)(void), char *fname, int *stdinfd,
81                 int stdoutfd, int stderrfd);
82 int check_result(int mesgfd);
83 void parse_backup_messages(dle_t *dle, int mesgin);
84 static void process_dumpline(char *str);
85 static void save_fd(int *, int);
86 void application_api_info_tapeheader(int mesgfd, char *prog, dle_t *dle);
87
88 int fdprintf(int fd, char *format, ...) G_GNUC_PRINTF(2, 3);
89
90 int
91 fdprintf(
92     int   fd,
93     char *format,
94     ...)
95 {
96     va_list  argp;
97     char    *s;
98     int      r;
99
100     arglist_start(argp, format);
101     s = g_strdup_vprintf(format, argp);
102     arglist_end(argp);
103
104     r = full_write(fd, s, strlen(s));
105     amfree(s);
106     return r;
107 }
108
109 int
110 main(
111     int         argc,
112     char **     argv)
113 {
114     int interactive = 0;
115     int level = 0;
116     int mesgpipe[2];
117     dle_t *dle = NULL;
118     char *dumpdate, *stroptions;
119     char *qdisk = NULL;
120     char *qamdevice = NULL;
121     char *line = NULL;
122     char *err_extra = NULL;
123     char *s;
124     int i;
125     int ch;
126     GSList *errlist;
127     FILE   *mesgstream;
128
129     /* initialize */
130     /*
131      * Configure program for internationalization:
132      *   1) Only set the message locale for now.
133      *   2) Set textdomain for all amanda related programs to "amanda"
134      *      We don't want to be forced to support dozens of message catalogs.
135      */  
136     setlocale(LC_MESSAGES, "C");
137     textdomain("amanda"); 
138
139     safe_fd(DATA_FD_OFFSET, DATA_FD_COUNT*2);
140
141     safe_cd();
142
143     set_pname("sendbackup");
144
145     /* Don't die when child closes pipe */
146     signal(SIGPIPE, SIG_IGN);
147
148     /* Don't die when interrupt received */
149     signal(SIGINT, SIG_IGN);
150
151     if(argc > 1 && strcmp(argv[1],"-t") == 0) {
152         interactive = 1;
153         argc--;
154         argv++;
155     } else {
156         interactive = 0;
157     }
158
159     erroutput_type = (ERR_INTERACTIVE|ERR_SYSLOG);
160     dbopen(DBG_SUBDIR_CLIENT);
161     startclock();
162     dbprintf(_("Version %s\n"), version());
163
164     if(argc > 2 && strcmp(argv[1], "amandad") == 0) {
165         amandad_auth = stralloc(argv[2]);
166     }
167
168     our_features = am_init_feature_set();
169     our_feature_string = am_feature_to_string(our_features);
170
171     config_init(CONFIG_INIT_CLIENT, NULL);
172     /* (check for config errors comes later) */
173
174     check_running_as(RUNNING_AS_CLIENT_LOGIN);
175
176     if(interactive) {
177         /*
178          * In interactive (debug) mode, the backup data is sent to
179          * /dev/null and none of the network connections back to driver
180          * programs on the tape host are set up.  The index service is
181          * run and goes to stdout.
182          */
183         g_fprintf(stderr, _("%s: running in interactive test mode\n"), get_pname());
184         fflush(stderr);
185     }
186
187     qdisk = NULL;
188     dumpdate = NULL;
189     stroptions = NULL;
190
191     for(; (line = agets(stdin)) != NULL; free(line)) {
192         if (line[0] == '\0')
193             continue;
194         if(interactive) {
195             g_fprintf(stderr, "%s> ", get_pname());
196             fflush(stderr);
197         }
198         if(strncmp_const(line, "OPTIONS ") == 0) {
199             g_options = parse_g_options(line+8, 1);
200             if(!g_options->hostname) {
201                 g_options->hostname = alloc(MAX_HOSTNAME_LENGTH+1);
202                 gethostname(g_options->hostname, MAX_HOSTNAME_LENGTH);
203                 g_options->hostname[MAX_HOSTNAME_LENGTH] = '\0';
204             }
205
206             if (g_options->config) {
207                 /* overlay this configuration on the existing (nameless) configuration */
208                 config_init(CONFIG_INIT_CLIENT | CONFIG_INIT_EXPLICIT_NAME | CONFIG_INIT_OVERLAY,
209                             g_options->config);
210
211                 dbrename(get_config_name(), DBG_SUBDIR_CLIENT);
212             }
213
214             /* check for any config errors now */
215             if (config_errors(&errlist) >= CFGERR_ERRORS) {
216                 char *errstr = config_errors_to_error_string(errlist);
217                 g_printf("%s\n", errstr);
218                 dbclose();
219                 return 1;
220             }
221
222             if (am_has_feature(g_options->features, fe_req_xml)) {
223                 break;
224             }
225             continue;
226         }
227
228         if (dle && dle->program != NULL) {
229             err_extra = _("multiple requests");
230             goto err;
231         }
232
233         dbprintf(_("  sendbackup req: <%s>\n"), line);
234         dle = alloc_dle();
235
236         s = line;
237         ch = *s++;
238
239         skip_whitespace(s, ch);                 /* find the program name */
240         if(ch == '\0') {
241             err_extra = _("no program name");
242             goto err;                           /* no program name */
243         }
244         dle->program = s - 1;
245         skip_non_whitespace(s, ch);
246         s[-1] = '\0';
247
248         if (strcmp(dle->program, "APPLICATION")==0) {
249             dle->program_is_application_api=1;
250             skip_whitespace(s, ch);             /* find dumper name */
251             if (ch == '\0') {
252                 goto err;                       /* no program */
253             }
254             dle->program = s - 1;
255             skip_non_whitespace(s, ch);
256             s[-1] = '\0';
257         }
258         dle->program = stralloc(dle->program);
259
260         skip_whitespace(s, ch);                 /* find the disk name */
261         if(ch == '\0') {
262             err_extra = _("no disk name");
263             goto err;                           /* no disk name */
264         }
265
266         amfree(qdisk);
267         qdisk = s - 1;
268         ch = *qdisk;
269         skip_quoted_string(s, ch);
270         s[-1] = '\0';
271         qdisk = stralloc(qdisk);
272         dle->disk = unquote_string(qdisk);
273
274         skip_whitespace(s, ch);                 /* find the device or level */
275         if (ch == '\0') {
276             err_extra = _("bad level");
277             goto err;
278         }
279
280         if(!isdigit((int)s[-1])) {
281             amfree(qamdevice);
282             qamdevice = s - 1;
283             ch = *qamdevice;
284             skip_quoted_string(s, ch);
285             s[-1] = '\0';
286             qamdevice = stralloc(qamdevice);
287             dle->device = unquote_string(qamdevice);
288             skip_whitespace(s, ch);             /* find level number */
289         }
290         else {
291             dle->device = stralloc(dle->disk);
292             qamdevice = stralloc(qdisk);
293         }
294                                                 /* find the level number */
295         if(ch == '\0' || sscanf(s - 1, "%d", &level) != 1) {
296             err_extra = _("bad level");
297             goto err;                           /* bad level */
298         }
299         skip_integer(s, ch);
300         dle->level = g_slist_append(dle->level, GINT_TO_POINTER(level));
301
302         skip_whitespace(s, ch);                 /* find the dump date */
303         if(ch == '\0') {
304             err_extra = _("no dumpdate");
305             goto err;                           /* no dumpdate */
306         }
307         amfree(dumpdate);
308         dumpdate = s - 1;
309         skip_non_whitespace(s, ch);
310         s[-1] = '\0';
311         dumpdate = stralloc(dumpdate);
312
313         skip_whitespace(s, ch);                 /* find the options keyword */
314         if(ch == '\0') {
315             err_extra = _("no options");
316             goto err;                           /* no options */
317         }
318         if(strncmp_const_skip(s - 1, "OPTIONS ", s, ch) != 0) {
319             err_extra = _("no OPTIONS keyword");
320             goto err;                           /* no options */
321         }
322         skip_whitespace(s, ch);                 /* find the options string */
323         if(ch == '\0') {
324             err_extra = _("bad options string");
325             goto err;                           /* no options */
326         }
327         amfree(stroptions);
328         stroptions = stralloc(s - 1);
329     }
330     amfree(line);
331     if (g_options == NULL) {
332         g_printf(_("ERROR [Missing OPTIONS line in sendbackup input]\n"));
333         error(_("Missing OPTIONS line in sendbackup input\n"));
334         /*NOTREACHED*/
335     }
336
337     if (am_has_feature(g_options->features, fe_req_xml)) {
338         char *errmsg = NULL;
339
340         dle = amxml_parse_node_FILE(stdin, &errmsg);
341         if (errmsg) {
342             err_extra = errmsg;
343             goto err;
344         }
345         if (!dle) {
346             err_extra = _("One DLE required");
347             goto err;
348         } else if (dle->next) {
349             err_extra = _("Only one DLE allowed");
350             goto err;
351         }
352
353         qdisk = quote_string(dle->disk);
354         if (dle->device == NULL)
355             dle->device = stralloc(dle->disk);
356         qamdevice = quote_string(dle->device);
357         dumpdate = stralloc("NODATE");
358         stroptions = stralloc("");
359     } else {
360         parse_options(stroptions, dle, g_options->features, 0);
361     }
362     gdle = dle;
363
364     if (dle->program == NULL ||
365         dle->disk    == NULL ||
366         dle->device  == NULL ||
367         dle->level   == NULL ||
368         dumpdate     == NULL) {
369         err_extra = _("no valid sendbackup request");
370         goto err;
371     }
372
373     if (g_slist_length(dle->level) != 1) {
374         err_extra = _("Too many level");
375         goto err;
376     }
377
378     level = GPOINTER_TO_INT(dle->level->data);
379     dbprintf(_("  Parsed request as: program `%s'\n"), dle->program);
380     dbprintf(_("                     disk `%s'\n"), qdisk);
381     dbprintf(_("                     device `%s'\n"), qamdevice);
382     dbprintf(_("                     level %d\n"), level);
383     dbprintf(_("                     since %s\n"), dumpdate);
384     dbprintf(_("                     options `%s'\n"), stroptions);
385
386     if (dle->program_is_application_api==1) {
387         /* check that the application_api exist */
388     } else {
389         for(i = 0; programs[i]; i++) {
390             if (strcmp(programs[i]->name, dle->program) == 0) {
391                 break;
392             }
393         }
394         if (programs[i] == NULL) {
395             dbprintf(_("ERROR [%s: unknown program %s]\n"), get_pname(),
396                      dle->program);
397             error(_("ERROR [%s: unknown program %s]"), get_pname(),
398                   dle->program);
399             /*NOTREACHED*/
400         }
401         program = programs[i];
402     }
403
404     if(!interactive) {
405         datafd = DATA_FD_OFFSET + 0;
406         mesgfd = DATA_FD_OFFSET + 2;
407         indexfd = DATA_FD_OFFSET + 4;
408     }
409     if (!dle->create_index)
410         indexfd = -1;
411
412     if (dle->auth && amandad_auth) {
413         if(strcasecmp(dle->auth, amandad_auth) != 0) {
414             g_printf(_("ERROR [client configured for auth=%s while server requested '%s']\n"),
415                    amandad_auth, dle->auth);
416             exit(-1);
417         }
418     }
419
420     if (dle->kencrypt) {
421         g_printf("KENCRYPT\n");
422     }
423
424     g_printf(_("CONNECT DATA %d MESG %d INDEX %d\n"),
425            DATA_FD_OFFSET, DATA_FD_OFFSET+1,
426            indexfd == -1 ? -1 : DATA_FD_OFFSET+2);
427     g_printf(_("OPTIONS "));
428     if(am_has_feature(g_options->features, fe_rep_options_features)) {
429         g_printf("features=%s;", our_feature_string);
430     }
431     if(am_has_feature(g_options->features, fe_rep_options_hostname)) {
432         g_printf("hostname=%s;", g_options->hostname);
433     }
434     if (!am_has_feature(g_options->features, fe_rep_options_features) &&
435         !am_has_feature(g_options->features, fe_rep_options_hostname)) {
436         g_printf(";");
437     }
438     g_printf("\n");
439     fflush(stdout);
440     if (freopen("/dev/null", "w", stdout) == NULL) {
441         dbprintf(_("Error redirecting stdout to /dev/null: %s\n"),
442                  strerror(errno));
443         exit(1);
444     }
445
446     if(interactive) {
447       if((datafd = open("/dev/null", O_RDWR)) < 0) {
448         error(_("ERROR [open of /dev/null for debug data stream: %s]\n"),
449                 strerror(errno));
450         /*NOTREACHED*/
451       }
452       mesgfd = 2;
453       indexfd = 1;
454     }
455
456     if(!interactive) {
457       if(datafd == -1 || mesgfd == -1 || (dle->create_index && indexfd == -1)) {
458         dbclose();
459         exit(1);
460       }
461     }
462
463     mesgstream = fdopen(mesgfd,"w");
464     run_client_scripts(EXECUTE_ON_PRE_DLE_BACKUP, g_options, dle, mesgstream);
465     fflush(mesgstream);
466
467     if (dle->program_is_application_api==1) {
468         int i, j, k;
469         char *cmd=NULL;
470         char **argvchild;
471         char levelstr[20];
472         backup_support_option_t *bsu;
473         char *compopt = NULL;
474         char *encryptopt = skip_argument;
475         int compout, dumpout;
476         GSList    *scriptlist;
477         script_t  *script;
478         time_t     cur_dumptime;
479         int        result;
480         GPtrArray *errarray;
481         int        errfd[2];
482         FILE      *dumperr;
483
484         /*  apply client-side encryption here */
485         if ( dle->encrypt == ENCRYPT_CUST ) {
486             encpid = pipespawn(dle->clnt_encrypt, STDIN_PIPE, 0,
487                                &compout, &datafd, &mesgfd,
488                                dle->clnt_encrypt, encryptopt, NULL);
489             dbprintf(_("encrypt: pid %ld: %s\n"), (long)encpid, dle->clnt_encrypt);
490         } else {
491             compout = datafd;
492             encpid = -1;
493         }
494
495         /*  now do the client-side compression */
496         if(dle->compress == COMP_FAST || dle->compress == COMP_BEST) {
497             compopt = skip_argument;
498 #if defined(COMPRESS_BEST_OPT) && defined(COMPRESS_FAST_OPT)
499             if(dle->compress == COMP_BEST) {
500                 compopt = COMPRESS_BEST_OPT;
501             } else {
502                 compopt = COMPRESS_FAST_OPT;
503             }
504 #endif
505             comppid = pipespawn(COMPRESS_PATH, STDIN_PIPE, 0,
506                                 &dumpout, &compout, &mesgfd,
507                                 COMPRESS_PATH, compopt, NULL);
508             if(compopt != skip_argument) {
509                 dbprintf(_("compress pid %ld: %s %s\n"),
510                          (long)comppid, COMPRESS_PATH, compopt);
511             } else {
512                 dbprintf(_("compress pid %ld: %s\n"), (long)comppid, COMPRESS_PATH);
513             }
514         } else if (dle->compress == COMP_CUST) {
515             compopt = skip_argument;
516             comppid = pipespawn(dle->compprog, STDIN_PIPE, 0,
517                                 &dumpout, &compout, &mesgfd,
518                                 dle->compprog, compopt, NULL);
519             if(compopt != skip_argument) {
520                 dbprintf(_("pid %ld: %s %s\n"),
521                          (long)comppid, dle->compprog, compopt);
522             } else {
523                 dbprintf(_("pid %ld: %s\n"), (long)comppid, dle->compprog);
524             }
525         } else {
526             dumpout = compout;
527             comppid = -1;
528         }
529
530         cur_dumptime = time(0);
531         bsu = backup_support_option(dle->program, g_options, dle->disk,
532                                     dle->device, &errarray);
533         if (!bsu) {
534             char  *errmsg;
535             char  *qerrmsg;
536             guint  i;
537             for (i=0; i < errarray->len; i++) {
538                 errmsg = g_ptr_array_index(errarray, i);
539                 qerrmsg = quote_string(errmsg);
540                 fdprintf(mesgfd,
541                           _("sendbackup: error [Application '%s': %s]\n"),
542                           dle->program, errmsg);
543                 dbprintf("aa: %s\n",qerrmsg);
544                 amfree(qerrmsg);
545             }
546             if (i == 0) { /* no errarray */
547                 errmsg = vstrallocf(_("Can't execute application '%s'"),
548                                     dle->program);
549                 qerrmsg = quote_string(errmsg);
550                 fdprintf(mesgfd, _("sendbackup: error [%s]\n"), errmsg);
551                 dbprintf(_("ERROR %s\n"), qerrmsg);
552                 amfree(qerrmsg);
553                 amfree(errmsg);
554             }
555             return 0;
556         }
557
558         if (pipe(errfd) < 0) {
559             char  *errmsg;
560             char  *qerrmsg;
561             errmsg = vstrallocf(_("Application '%s': can't create pipe"),
562                                     dle->program);
563             qerrmsg = quote_string(errmsg);
564             fdprintf(mesgfd, _("sendbackup: error [%s]\n"), errmsg);
565             dbprintf(_("ERROR %s\n"), qerrmsg);
566             amfree(qerrmsg);
567             amfree(errmsg);
568             return 0;
569         }
570
571         switch(application_api_pid=fork()) {
572         case 0:
573             cmd = vstralloc(APPLICATION_DIR, "/", dle->program, NULL);
574             k = application_property_argv_size(dle);
575             for (scriptlist = dle->scriptlist; scriptlist != NULL;
576                  scriptlist = scriptlist->next) {
577                 script = (script_t *)scriptlist->data;
578                 if (script->result && script->result->proplist) {
579                     k += property_argv_size(script->result->proplist);
580                 }
581             }
582             argvchild = g_new0(char *, 20 + k);
583             i=0;
584             argvchild[i++] = dle->program;
585             argvchild[i++] = "backup";
586             if (bsu->message_line == 1) {
587                 argvchild[i++] = "--message";
588                 argvchild[i++] = "line";
589             }
590             if (g_options->config && bsu->config == 1) {
591                 argvchild[i++] = "--config";
592                 argvchild[i++] = g_options->config;
593             }
594             if (g_options->hostname && bsu->host == 1) {
595                 argvchild[i++] = "--host";
596                 argvchild[i++] = g_options->hostname;
597             }
598             if (dle->disk && bsu->disk == 1) {
599                 argvchild[i++] = "--disk";
600                 argvchild[i++] = dle->disk;
601             }
602             argvchild[i++] = "--device";
603             argvchild[i++] = dle->device;
604             if (level <= bsu->max_level) {
605                 argvchild[i++] = "--level";
606                 g_snprintf(levelstr,19,"%d",level);
607                 argvchild[i++] = levelstr;
608             }
609             if (indexfd != -1 && bsu->index_line == 1) {
610                 argvchild[i++] = "--index";
611                 argvchild[i++] = "line";
612             }
613             if (dle->record && bsu->record == 1) {
614                 argvchild[i++] = "--record";
615             }
616             i += application_property_add_to_argv(&argvchild[i], dle, bsu);
617
618             for (scriptlist = dle->scriptlist; scriptlist != NULL;
619                  scriptlist = scriptlist->next) {
620                 script = (script_t *)scriptlist->data;
621                 if (script->result && script->result->proplist) {
622                     i += property_add_to_argv(&argvchild[i],
623                                               script->result->proplist);
624                 }
625             }
626
627             argvchild[i] = NULL;
628             dbprintf(_("%s: running \"%s\n"), get_pname(), cmd);
629             for(j=1;j<i;j++) dbprintf(" %s\n",argvchild[j]);
630             dbprintf(_("\"\n"));
631             if(dup2(dumpout, 1) == -1) {
632                 error(_("Can't dup2: %s"),strerror(errno));
633                 /*NOTREACHED*/
634             }
635             if (dup2(errfd[1], 2) == -1) {
636                 error(_("Can't dup2: %s"),strerror(errno));
637                 /*NOTREACHED*/
638             }
639             if(dup2(mesgfd, 3) == -1) {
640                 error(_("Can't dup2: %s"),strerror(errno));
641                 /*NOTREACHED*/
642             }
643             if(indexfd > 0) {
644                 if(dup2(indexfd, 4) == -1) {
645                     error(_("Can't dup2: %s"),strerror(errno));
646                     /*NOTREACHED*/
647                 }
648                 fcntl(indexfd, F_SETFD, 0);
649             }
650             application_api_info_tapeheader(mesgfd, dle->program, dle);
651             if (indexfd != 0) {
652                 safe_fd(3, 2);
653             } else {
654                 safe_fd(3, 1);
655             }
656             execve(cmd, argvchild, safe_env());
657             exit(1);
658             break;
659  
660         default:
661             break;
662         case -1:
663             error(_("%s: fork returned: %s"), get_pname(), strerror(errno));
664         }
665
666         close(errfd[1]);
667         dumperr = fdopen(errfd[0],"r");
668         if (!dumperr) {
669             error(_("Can't fdopen: %s"), strerror(errno));
670             /*NOTREACHED*/
671         }
672
673         result = 0;
674         while ((line = agets(dumperr)) != NULL) {
675             if (strlen(line) > 0) {
676                 fdprintf(mesgfd, "sendbackup: error [%s]\n", line);
677                 dbprintf("error: %s\n", line);
678                 result = 1;
679             }
680             amfree(line);
681         }
682
683         result |= check_result(mesgfd);
684         if (result == 0) {
685             char *amandates_file;
686
687             amandates_file = getconf_str(CNF_AMANDATES);
688             if(start_amandates(amandates_file, 1)) {
689                 amandates_updateone(dle->disk, level, cur_dumptime);
690                 finish_amandates();
691                 free_amandates();
692             } else {
693                 if (dle->calcsize && bsu->calcsize) {
694                     error(_("error [opening %s for writing: %s]"),
695                           amandates_file, strerror(errno));
696                 } else {
697                     g_debug(_("non-fatal error opening '%s' for writing: %s]"),
698                             amandates_file, strerror(errno));
699                 }
700             }
701         }
702         amfree(bsu);
703      } else {
704         if(!interactive) {
705             /* redirect stderr */
706             if(dup2(mesgfd, 2) == -1) {
707                 dbprintf(_("Error redirecting stderr to fd %d: %s\n"),
708                          mesgfd, strerror(errno));
709                 dbclose();
710                 exit(1);
711             }
712         }
713  
714         if(pipe(mesgpipe) == -1) {
715             s = strerror(errno);
716             dbprintf(_("error [opening mesg pipe: %s]\n"), s);
717             error(_("error [opening mesg pipe: %s]"), s);
718         }
719
720         program->start_backup(dle, g_options->hostname,
721                               datafd, mesgpipe[1], indexfd);
722         dbprintf(_("Started backup\n"));
723         parse_backup_messages(dle, mesgpipe[0]);
724         dbprintf(_("Parsed backup messages\n"));
725     }
726
727     run_client_scripts(EXECUTE_ON_POST_DLE_BACKUP, g_options, dle, mesgstream);
728     fflush(mesgstream);
729
730     amfree(qdisk);
731     amfree(qamdevice);
732     amfree(dumpdate);
733     amfree(stroptions);
734     amfree(our_feature_string);
735     am_release_feature_set(our_features);
736     our_features = NULL;
737     free_g_options(g_options);
738
739     dbclose();
740
741     return 0;
742
743  err:
744     if (err_extra) {
745         g_printf(_("ERROR FORMAT ERROR IN REQUEST PACKET '%s'\n"), err_extra);
746         dbprintf(_("REQ packet is bogus: %s\n"), err_extra);
747     } else {
748         g_printf(_("ERROR FORMAT ERROR IN REQUEST PACKET\n"));
749         dbprintf(_("REQ packet is bogus\n"));
750     }
751
752     amfree(qdisk);
753     amfree(qamdevice);
754     amfree(dumpdate);
755     amfree(stroptions);
756     amfree(our_feature_string);
757
758     dbclose();
759     return 1;
760 }
761
762
763 /*
764  * Returns a string for a child process.  Checks the saved dump and
765  * compress pids to see which it is.
766  */
767
768 char *
769 childstr(
770     pid_t pid)
771 {
772     if(pid == dumppid) return program->backup_name;
773     if(pid == comppid) return "compress";
774     if(pid == encpid) return "encrypt";
775     if(pid == indexpid) return "index";
776     if(pid == application_api_pid) {
777         if (!gdle) {
778             dbprintf("gdle == NULL\n");
779             return "gdle == NULL";
780         }
781         return gdle->program;
782     }
783     return "unknown";
784 }
785
786
787 /*
788  * Determine if the child return status really indicates an error.
789  * If so, add the error message to the error string; more than one
790  * child can have an error.
791  */
792
793 int
794 check_status(
795     pid_t       pid,
796     amwait_t    w,
797     int         mesgfd)
798 {
799     char *thiserr = NULL;
800     char *str, *strX;
801     int ret, sig, rc;
802
803     str = childstr(pid);
804
805     if(WIFSIGNALED(w)) {
806         ret = 0;
807         rc = sig = WTERMSIG(w);
808     } else {
809         sig = 0;
810         rc = ret = WEXITSTATUS(w);
811     }
812
813     if(pid == indexpid) {
814         /*
815          * Treat an index failure (other than signal) as a "STRANGE"
816          * rather than an error so the dump goes ahead and gets processed
817          * but the failure is noted.
818          */
819         if(ret != 0) {
820             fdprintf(mesgfd, _("? index %s returned %d\n"), str, ret);
821             rc = 0;
822         }
823         indexpid = -1;
824         strX = "index";
825     } else if(pid == comppid) {
826         /*
827          * compress returns 2 sometimes, but it is ok.
828          */
829 #ifndef HAVE_GZIP
830         if(ret == 2) {
831             rc = 0;
832         }
833 #endif
834         comppid = -1;
835         strX = "compress";
836     } else if(pid == dumppid && tarpid == -1) {
837         /*
838          * Ultrix dump returns 1 sometimes, but it is ok.
839          */
840 #ifdef DUMP_RETURNS_1
841         if(ret == 1) {
842             rc = 0;
843         }
844 #endif
845         dumppid = -1;
846         strX = "dump";
847     } else if(pid == tarpid) {
848         if (ret == 1) {
849             rc = 0;
850         }
851         /*
852          * tar bitches about active filesystems, but we do not care.
853          */
854 #ifdef IGNORE_TAR_ERRORS
855         if(ret == 2) {
856             rc = 0;
857         }
858 #endif
859         dumppid = tarpid = -1;
860         strX = "dump";
861     } else if(pid == application_api_pid) {
862         strX = "Application";
863     } else {
864         strX = "unknown";
865     }
866
867     if(rc == 0) {
868         return 0;                               /* normal exit */
869     }
870
871     if(ret == 0) {
872         thiserr = vstrallocf(_("%s (%d) %s got signal %d"), strX, (int)pid, str,
873                              sig);
874     } else {
875         thiserr = vstrallocf(_("%s (%d) %s returned %d"), strX, (int)pid, str, ret);
876     }
877
878     fdprintf(mesgfd, "? %s\n", thiserr);
879
880     if(errorstr) {
881         errorstr =  newvstrallocf(errorstr, "%s, %s", errorstr, thiserr);
882         amfree(thiserr);
883     } else {
884         errorstr = thiserr;
885         thiserr = NULL;
886     }
887     return 1;
888 }
889
890
891 /*
892  *Send header info to the message file.
893  */
894 void
895 info_tapeheader(
896     dle_t *dle)
897 {
898     g_fprintf(stderr, "%s: info BACKUP=%s\n", get_pname(), program->backup_name);
899
900     g_fprintf(stderr, "%s: info RECOVER_CMD=", get_pname());
901     if (dle->compress == COMP_FAST || dle->compress == COMP_BEST)
902         g_fprintf(stderr, "%s %s |", UNCOMPRESS_PATH,
903 #ifdef UNCOMPRESS_OPT
904                 UNCOMPRESS_OPT
905 #else
906                 ""
907 #endif
908                 );
909
910     g_fprintf(stderr, "%s -xpGf - ...\n", program->restore_name);
911
912     if (dle->compress == COMP_FAST || dle->compress == COMP_BEST)
913         g_fprintf(stderr, "%s: info COMPRESS_SUFFIX=%s\n",
914                         get_pname(), COMPRESS_SUFFIX);
915
916     g_fprintf(stderr, "%s: info end\n", get_pname());
917 }
918
919 void
920 application_api_info_tapeheader(
921     int       mesgfd,
922     char     *prog,
923     dle_t *dle)
924 {
925     char line[1024];
926
927     g_snprintf(line, 1024, "%s: info BACKUP=APPLICATION\n", get_pname());
928     if (full_write(mesgfd, line, strlen(line)) != strlen(line)) {
929         dbprintf(_("error writing to mesgfd socket: %s"), strerror(errno));
930         return;
931     }
932
933     g_snprintf(line, 1024, "%s: info APPLICATION=%s\n", get_pname(), prog);
934     if (full_write(mesgfd, line, strlen(line)) != strlen(line)) {
935         dbprintf(_("error writing to mesgfd socket: %s"), strerror(errno));
936         return;
937     }
938
939     g_snprintf(line, 1024, "%s: info RECOVER_CMD=", get_pname());
940     if (full_write(mesgfd, line, strlen(line)) != strlen(line)) {
941         dbprintf(_("error writing to mesgfd socket: %s"), strerror(errno));
942         return;
943     }
944
945     if (dle->compress == COMP_FAST || dle->compress == COMP_BEST) {
946         g_snprintf(line, 1024, "%s %s |", UNCOMPRESS_PATH,
947 #ifdef UNCOMPRESS_OPT
948                  UNCOMPRESS_OPT
949 #else
950                  ""
951 #endif
952                  );
953         if (full_write(mesgfd, line, strlen(line)) != strlen(line)) {
954             dbprintf(_("error writing to mesgfd socket: %s"), strerror(errno));
955             return;
956         }
957     }
958     g_snprintf(line, 1024, "%s/%s restore [./file-to-restore]+\n",
959                APPLICATION_DIR, prog);
960     if (full_write(mesgfd, line, strlen(line)) != strlen(line)) {
961         dbprintf(_("error writing to mesgfd socket: %s"), strerror(errno));
962         return;
963     }
964
965     if (dle->compress) {
966         g_snprintf(line, 1024, "%s: info COMPRESS_SUFFIX=%s\n",
967                  get_pname(), COMPRESS_SUFFIX);
968         if (full_write(mesgfd, line, strlen(line)) != strlen(line)) {
969             dbprintf(_("error writing to mesgfd socket: %s"), strerror(errno));
970             return;
971         }
972     }
973
974     g_snprintf(line, 1024, "%s: info end\n", get_pname());
975     if (full_write(mesgfd, line, strlen(line)) != strlen(line)) {
976         dbprintf(_("error writing to mesgfd socket: %s"), strerror(errno));
977         return;
978     }
979 }
980
981 pid_t
982 pipefork(
983     void        (*func)(void),
984     char *      fname,
985     int *       stdinfd,
986     int         stdoutfd,
987     int         stderrfd)
988 {
989     int inpipe[2];
990     pid_t pid;
991
992     dbprintf(_("Forking function %s in pipeline\n"), fname);
993
994     if(pipe(inpipe) == -1) {
995         error(_("error [open pipe to %s: %s]"), fname, strerror(errno));
996         /*NOTREACHED*/
997     }
998
999     switch(pid = fork()) {
1000     case -1:
1001         error(_("error [fork %s: %s]"), fname, strerror(errno));
1002         /*NOTREACHED*/
1003     default:    /* parent process */
1004         aclose(inpipe[0]);      /* close input side of pipe */
1005         *stdinfd = inpipe[1];
1006         break;
1007     case 0:             /* child process */
1008         aclose(inpipe[1]);      /* close output side of pipe */
1009
1010         if(dup2(inpipe[0], 0) == -1) {
1011             error(_("error [fork %s: dup2(%d, in): %s]"),
1012                   fname, inpipe[0], strerror(errno));
1013             /*NOTRACHED*/
1014         }
1015         if(dup2(stdoutfd, 1) == -1) {
1016             error(_("error [fork %s: dup2(%d, out): %s]"),
1017                   fname, stdoutfd, strerror(errno));
1018             /*NOTRACHED*/
1019         }
1020         if(dup2(stderrfd, 2) == -1) {
1021             error(_("error [fork %s: dup2(%d, err): %s]"),
1022                   fname, stderrfd, strerror(errno));
1023             /*NOTRACHED*/
1024         }
1025
1026         func();
1027         exit(0);
1028         /*NOTREACHED*/
1029     }
1030     return pid;
1031 }
1032
1033 int
1034 check_result(
1035     int mesgfd)
1036 {
1037     int goterror;
1038     pid_t wpid;
1039     amwait_t retstat;
1040
1041     goterror = 0;
1042
1043
1044     while((wpid = waitpid((pid_t)-1, &retstat, WNOHANG)) > 0) {
1045         if(check_status(wpid, retstat, mesgfd)) goterror = 1;
1046     }
1047
1048     if (dumppid != -1) {
1049         sleep(5);
1050         while((wpid = waitpid((pid_t)-1, &retstat, WNOHANG)) > 0) {
1051             if(check_status(wpid, retstat, mesgfd)) goterror = 1;
1052         }
1053     }
1054     if (dumppid != -1) {
1055         dbprintf(_("Sending SIGHUP to dump process %d\n"),
1056                   (int)dumppid);
1057         if(dumppid != -1) {
1058             if(kill(dumppid, SIGHUP) == -1) {
1059                 dbprintf(_("Can't send SIGHUP to %d: %s\n"),
1060                           (int)dumppid,
1061                           strerror(errno));
1062             }
1063         }
1064         sleep(5);
1065         while((wpid = waitpid((pid_t)-1, &retstat, WNOHANG)) > 0) {
1066             if(check_status(wpid, retstat, mesgfd)) goterror = 1;
1067         }
1068     }
1069     if (dumppid != -1) {
1070         dbprintf(_("Sending SIGKILL to dump process %d\n"),
1071                   (int)dumppid);
1072         if(dumppid != -1) {
1073             if(kill(dumppid, SIGKILL) == -1) {
1074                 dbprintf(_("Can't send SIGKILL to %d: %s\n"),
1075                           (int)dumppid,
1076                           strerror(errno));
1077             }
1078         }
1079         sleep(5);
1080         while((wpid = waitpid((pid_t)-1, &retstat, WNOHANG)) > 0) {
1081             if(check_status(wpid, retstat, mesgfd)) goterror = 1;
1082         }
1083     }
1084
1085     return goterror;
1086 }
1087
1088 void
1089 parse_backup_messages(
1090     dle_t      *dle,
1091     int         mesgin)
1092 {
1093     int goterror;
1094     char *line;
1095
1096     amfree(errorstr);
1097
1098     for(; (line = areads(mesgin)) != NULL; free(line)) {
1099         process_dumpline(line);
1100     }
1101
1102     if(errno) {
1103         error(_("error [read mesg pipe: %s]"), strerror(errno));
1104         /*NOTREACHED*/
1105     }
1106
1107     goterror = check_result(mesgfd);
1108
1109     if(errorstr) {
1110         error(_("error [%s]"), errorstr);
1111         /*NOTREACHED*/
1112     } else if(dump_size == -1) {
1113         error(_("error [no backup size line]"));
1114         /*NOTREACHED*/
1115     }
1116
1117     program->end_backup(dle, goterror);
1118
1119     fdprintf(mesgfd, _("%s: size %ld\n"), get_pname(), dump_size);
1120     fdprintf(mesgfd, _("%s: end\n"), get_pname());
1121 }
1122
1123
1124 static void
1125 process_dumpline(
1126     char *      str)
1127 {
1128     amregex_t *rp;
1129     char *type;
1130     char startchr;
1131
1132     for(rp = program->re_table; rp->regex != NULL; rp++) {
1133         if(match(rp->regex, str)) {
1134             break;
1135         }
1136     }
1137     if(rp->typ == DMP_SIZE) {
1138         dump_size = (long)((the_num(str, rp->field)* rp->scale+1023.0)/1024.0);
1139     }
1140     switch(rp->typ) {
1141     case DMP_NORMAL:
1142         type = "normal";
1143         startchr = '|';
1144         break;
1145     case DMP_STRANGE:
1146         type = "strange";
1147         startchr = '?';
1148         break;
1149     case DMP_SIZE:
1150         type = "size";
1151         startchr = '|';
1152         break;
1153     case DMP_ERROR:
1154         type = "error";
1155         startchr = '?';
1156         break;
1157     default:
1158         /*
1159          * Should never get here.
1160          */
1161         type = "unknown";
1162         startchr = '!';
1163         break;
1164     }
1165     dbprintf("%3d: %7s(%c): %s\n",
1166               rp->srcline,
1167               type,
1168               startchr,
1169               str);
1170     fdprintf(mesgfd, "%c %s\n", startchr, str);
1171 }
1172
1173
1174 /*
1175  * start_index.  Creates an index file from the output of dump/tar.
1176  * It arranges that input is the fd to be written by the dump process.
1177  * If createindex is not enabled, it does nothing.  If it is not, a
1178  * new process will be created that tees input both to a pipe whose
1179  * read fd is dup2'ed input and to a program that outputs an index
1180  * file to `index'.
1181  *
1182  * make sure that the chat from restore doesn't go to stderr cause
1183  * this goes back to amanda which doesn't expect to see it
1184  * (2>/dev/null should do it)
1185  *
1186  * Originally by Alan M. McIvor, 13 April 1996
1187  *
1188  * Adapted by Alexandre Oliva, 1 May 1997
1189  *
1190  * This program owes a lot to tee.c from GNU sh-utils and dumptee.c
1191  * from the DeeJay backup package.
1192  */
1193
1194 static void
1195 save_fd(
1196     int *       fd,
1197     int         min)
1198 {
1199   int origfd = *fd;
1200
1201   while (*fd >= 0 && *fd < min) {
1202     int newfd = dup(*fd);
1203     if (newfd == -1)
1204       dbprintf(_("Unable to save file descriptor [%s]\n"), strerror(errno));
1205     *fd = newfd;
1206   }
1207   if (origfd != *fd)
1208     dbprintf(_("Dupped file descriptor %i to %i\n"), origfd, *fd);
1209 }
1210
1211 void
1212 start_index(
1213     int         createindex,
1214     int         input,
1215     int         mesg,
1216     int         index,
1217     char *      cmd)
1218 {
1219   int pipefd[2];
1220   FILE *pipe_fp;
1221   int exitcode;
1222
1223   if (!createindex)
1224     return;
1225
1226   if (pipe(pipefd) != 0) {
1227     error(_("creating index pipe: %s"), strerror(errno));
1228     /*NOTREACHED*/
1229   }
1230
1231   switch(indexpid = fork()) {
1232   case -1:
1233     error(_("forking index tee process: %s"), strerror(errno));
1234     /*NOTREACHED*/
1235
1236   default:
1237     aclose(pipefd[0]);
1238     if (dup2(pipefd[1], input) == -1) {
1239       error(_("dup'ping index tee output: %s"), strerror(errno));
1240       /*NOTREACHED*/
1241     }
1242     aclose(pipefd[1]);
1243     return;
1244
1245   case 0:
1246     break;
1247   }
1248
1249   /* now in a child process */
1250   save_fd(&pipefd[0], 4);
1251   save_fd(&index, 4);
1252   save_fd(&mesg, 4);
1253   save_fd(&input, 4);
1254   dup2(pipefd[0], 0);
1255   dup2(index, 1);
1256   dup2(mesg, 2);
1257   dup2(input, 3);
1258   for(index = 4; index < (int)FD_SETSIZE; index++) {
1259     if (index != dbfd()) {
1260       close(index);
1261     }
1262   }
1263
1264   if ((pipe_fp = popen(cmd, "w")) == NULL) {
1265     error(_("couldn't start index creator [%s]"), strerror(errno));
1266     /*NOTREACHED*/
1267   }
1268
1269   dbprintf(_("Started index creator: \"%s\"\n"), cmd);
1270   while(1) {
1271     char buffer[BUFSIZ], *ptr;
1272     ssize_t bytes_read;
1273     size_t bytes_written;
1274     size_t just_written;
1275
1276     do {
1277         bytes_read = read(0, buffer, SIZEOF(buffer));
1278     } while ((bytes_read < 0) && ((errno == EINTR) || (errno == EAGAIN)));
1279
1280     if (bytes_read < 0) {
1281       error(_("index tee cannot read [%s]"), strerror(errno));
1282       /*NOTREACHED*/
1283     }
1284
1285     if (bytes_read == 0)
1286       break; /* finished */
1287
1288     /* write the stuff to the subprocess */
1289     ptr = buffer;
1290     bytes_written = 0;
1291     just_written = full_write(fileno(pipe_fp), ptr, (size_t)bytes_read);
1292     if (just_written < (size_t)bytes_read) {
1293         /* 
1294          * just as we waited for write() to complete.
1295          */
1296         if (errno != EPIPE) {
1297             dbprintf(_("Index tee cannot write to index creator [%s]\n"),
1298                             strerror(errno));
1299         }
1300     } else {
1301         bytes_written += just_written;
1302         ptr += just_written;
1303     }
1304
1305     /* write the stuff to stdout, ensuring none lost when interrupt
1306        occurs */
1307     ptr = buffer;
1308     bytes_written = 0;
1309     just_written = full_write(3, ptr, bytes_read);
1310     if (just_written < (size_t)bytes_read) {
1311         error(_("index tee cannot write [%s]"), strerror(errno));
1312         /*NOTREACHED*/
1313     } else {
1314         bytes_written += just_written;
1315         ptr += just_written;
1316     }
1317   }
1318
1319   aclose(pipefd[1]);
1320
1321   /* finished */
1322   /* check the exit code of the pipe and moan if not 0 */
1323   if ((exitcode = pclose(pipe_fp)) != 0) {
1324     char *exitstr = str_exit_status("Index pipe", exitcode);
1325     dbprintf("%s\n", exitstr);
1326     amfree(exitstr);
1327   } else {
1328     dbprintf(_("Index created successfully\n"));
1329   }
1330   pipe_fp = NULL;
1331
1332   exit(exitcode);
1333 }
1334
1335 extern backup_program_t dump_program, gnutar_program;
1336
1337 backup_program_t *programs[] = {
1338   &dump_program, &gnutar_program, NULL
1339 };