Imported Upstream version 2.6.1
[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     g_printf("\n");
435     fflush(stdout);
436     if (freopen("/dev/null", "w", stdout) == NULL) {
437         dbprintf(_("Error redirecting stdout to /dev/null: %s\n"),
438                  strerror(errno));
439         exit(1);
440     }
441
442     if(interactive) {
443       if((datafd = open("/dev/null", O_RDWR)) < 0) {
444         error(_("ERROR [open of /dev/null for debug data stream: %s]\n"),
445                 strerror(errno));
446         /*NOTREACHED*/
447       }
448       mesgfd = 2;
449       indexfd = 1;
450     }
451
452     if(!interactive) {
453       if(datafd == -1 || mesgfd == -1 || (dle->create_index && indexfd == -1)) {
454         dbclose();
455         exit(1);
456       }
457     }
458
459     mesgstream = fdopen(mesgfd,"w");
460     run_client_scripts(EXECUTE_ON_PRE_DLE_BACKUP, g_options, dle, mesgstream);
461     fflush(mesgstream);
462
463     if (dle->program_is_application_api==1) {
464         int i, j, k;
465         char *cmd=NULL;
466         char **argvchild;
467         char levelstr[20];
468         backup_support_option_t *bsu;
469         char *compopt = NULL;
470         char *encryptopt = skip_argument;
471         int compout, dumpout;
472         GSList    *scriptlist;
473         script_t  *script;
474         time_t     cur_dumptime;
475         int        result;
476         GPtrArray *errarray;
477         int        errfd[2];
478         FILE      *dumperr;
479
480         /*  apply client-side encryption here */
481         if ( dle->encrypt == ENCRYPT_CUST ) {
482             encpid = pipespawn(dle->clnt_encrypt, STDIN_PIPE, 0,
483                                &compout, &datafd, &mesgfd,
484                                dle->clnt_encrypt, encryptopt, NULL);
485             dbprintf(_("encrypt: pid %ld: %s\n"), (long)encpid, dle->clnt_encrypt);
486         } else {
487             compout = datafd;
488             encpid = -1;
489         }
490
491         /*  now do the client-side compression */
492         if(dle->compress == COMP_FAST || dle->compress == COMP_BEST) {
493             compopt = skip_argument;
494 #if defined(COMPRESS_BEST_OPT) && defined(COMPRESS_FAST_OPT)
495             if(dle->compress == COMP_BEST) {
496                 compopt = COMPRESS_BEST_OPT;
497             } else {
498                 compopt = COMPRESS_FAST_OPT;
499             }
500 #endif
501             comppid = pipespawn(COMPRESS_PATH, STDIN_PIPE, 0,
502                                 &dumpout, &compout, &mesgfd,
503                                 COMPRESS_PATH, compopt, NULL);
504             dbprintf(_("gnutar: pid %ld: %s"), (long)comppid, COMPRESS_PATH);
505             if(compopt != skip_argument) {
506                 dbprintf(_("pid %ld: %s %s\n"),
507                          (long)comppid, COMPRESS_PATH, compopt);
508             } else {
509                 dbprintf(_("pid %ld: %s\n"), (long)comppid, COMPRESS_PATH);
510             }
511         } else if (dle->compress == COMP_CUST) {
512             compopt = skip_argument;
513             comppid = pipespawn(dle->compprog, STDIN_PIPE, 0,
514                                 &dumpout, &compout, &mesgfd,
515                                 dle->compprog, compopt, NULL);
516             if(compopt != skip_argument) {
517                 dbprintf(_("pid %ld: %s %s\n"),
518                          (long)comppid, dle->compprog, compopt);
519             } else {
520                 dbprintf(_("pid %ld: %s\n"), (long)comppid, dle->compprog);
521             }
522         } else {
523             dumpout = compout;
524             comppid = -1;
525         }
526
527         cur_dumptime = time(0);
528         bsu = backup_support_option(dle->program, g_options, dle->disk,
529                                     dle->device, &errarray);
530         if (!bsu) {
531             char  *errmsg;
532             char  *qerrmsg;
533             guint  i;
534             for (i=0; i < errarray->len; i++) {
535                 errmsg = g_ptr_array_index(errarray, i);
536                 qerrmsg = quote_string(errmsg);
537                 fdprintf(mesgfd,
538                           _("sendbackup: error [Application '%s': %s]\n"),
539                           dle->program, errmsg);
540                 dbprintf("aa: %s\n",qerrmsg);
541                 amfree(qerrmsg);
542             }
543             if (i == 0) { /* no errarray */
544                 errmsg = vstrallocf(_("Can't execute application '%s'"),
545                                     dle->program);
546                 qerrmsg = quote_string(errmsg);
547                 fdprintf(mesgfd, _("sendbackup: error [%s]\n"), errmsg);
548                 dbprintf(_("ERROR %s\n"), qerrmsg);
549                 amfree(qerrmsg);
550                 amfree(errmsg);
551             }
552             return 0;
553         }
554
555         if (pipe(errfd) < 0) {
556             char  *errmsg;
557             char  *qerrmsg;
558             errmsg = vstrallocf(_("Application '%s': can't create pipe"),
559                                     dle->program);
560             qerrmsg = quote_string(errmsg);
561             fdprintf(mesgfd, _("sendbackup: error [%s]\n"), errmsg);
562             dbprintf(_("ERROR %s\n"), qerrmsg);
563             amfree(qerrmsg);
564             amfree(errmsg);
565             return 0;
566         }
567
568         switch(application_api_pid=fork()) {
569         case 0:
570             cmd = vstralloc(APPLICATION_DIR, "/", dle->program, NULL);
571             k = application_property_argv_size(dle);
572             for (scriptlist = dle->scriptlist; scriptlist != NULL;
573                  scriptlist = scriptlist->next) {
574                 script = (script_t *)scriptlist->data;
575                 if (script->result && script->result->proplist) {
576                     k += property_argv_size(script->result->proplist);
577                 }
578             }
579             argvchild = g_new0(char *, 20 + k);
580             i=0;
581             argvchild[i++] = dle->program;
582             argvchild[i++] = "backup";
583             if (bsu->message_line == 1) {
584                 argvchild[i++] = "--message";
585                 argvchild[i++] = "line";
586             }
587             if (g_options->config && bsu->config == 1) {
588                 argvchild[i++] = "--config";
589                 argvchild[i++] = g_options->config;
590             }
591             if (g_options->hostname && bsu->host == 1) {
592                 argvchild[i++] = "--host";
593                 argvchild[i++] = g_options->hostname;
594             }
595             if (dle->disk && bsu->disk == 1) {
596                 argvchild[i++] = "--disk";
597                 argvchild[i++] = dle->disk;
598             }
599             argvchild[i++] = "--device";
600             argvchild[i++] = dle->device;
601             if (level <= bsu->max_level) {
602                 argvchild[i++] = "--level";
603                 g_snprintf(levelstr,19,"%d",level);
604                 argvchild[i++] = levelstr;
605             }
606             if (indexfd != -1 && bsu->index_line == 1) {
607                 argvchild[i++] = "--index";
608                 argvchild[i++] = "line";
609             }
610             if (dle->record && bsu->record == 1) {
611                 argvchild[i++] = "--record";
612             }
613             i += application_property_add_to_argv(&argvchild[i], dle, bsu);
614
615             for (scriptlist = dle->scriptlist; scriptlist != NULL;
616                  scriptlist = scriptlist->next) {
617                 script = (script_t *)scriptlist->data;
618                 if (script->result && script->result->proplist) {
619                     i += property_add_to_argv(&argvchild[i],
620                                               script->result->proplist);
621                 }
622             }
623
624             argvchild[i] = NULL;
625             dbprintf(_("%s: running \"%s\n"), get_pname(), cmd);
626             for(j=1;j<i;j++) dbprintf(" %s\n",argvchild[j]);
627             dbprintf(_("\"\n"));
628             if(dup2(dumpout, 1) == -1) {
629                 error(_("Can't dup2: %s"),strerror(errno));
630                 /*NOTREACHED*/
631             }
632             if (dup2(errfd[1], 2) == -1) {
633                 error(_("Can't dup2: %s"),strerror(errno));
634                 /*NOTREACHED*/
635             }
636             if(dup2(mesgfd, 3) == -1) {
637                 error(_("Can't dup2: %s"),strerror(errno));
638                 /*NOTREACHED*/
639             }
640             if(indexfd > 0) {
641                 if(dup2(indexfd, 4) == -1) {
642                     error(_("Can't dup2: %s"),strerror(errno));
643                     /*NOTREACHED*/
644                 }
645                 fcntl(indexfd, F_SETFD, 0);
646             }
647             application_api_info_tapeheader(mesgfd, dle->program, dle);
648             if (indexfd != 0) {
649                 safe_fd(3, 2);
650             } else {
651                 safe_fd(3, 1);
652             }
653             execve(cmd, argvchild, safe_env());
654             exit(1);
655             break;
656  
657         default:
658             break;
659         case -1:
660             error(_("%s: fork returned: %s"), get_pname(), strerror(errno));
661         }
662
663         close(errfd[1]);
664         dumperr = fdopen(errfd[0],"r");
665         if (!dumperr) {
666             error(_("Can't fdopen: %s"), strerror(errno));
667             /*NOTREACHED*/
668         }
669
670         while ((line = agets(dumperr)) != NULL) {
671             if (strlen(line) > 0) {
672                 fdprintf(mesgfd, "sendbackup: error [%s]\n", line);
673                 dbprintf("error: %s\n", line);
674             }
675             amfree(line);
676         }
677
678         result = check_result(mesgfd);
679         if (result == 0) {
680             char *amandates_file;
681
682             amandates_file = getconf_str(CNF_AMANDATES);
683             if(start_amandates(amandates_file, 1)) {
684                 amandates_updateone(dle->disk, level, cur_dumptime);
685                 finish_amandates();
686                 free_amandates();
687             } else {
688                 if (dle->calcsize && bsu->calcsize) {
689                     error(_("error [opening %s for writing: %s]"),
690                           amandates_file, strerror(errno));
691                 } else {
692                     g_debug(_("non-fatal error opening '%s' for writing: %s]"),
693                             amandates_file, strerror(errno));
694                 }
695             }
696         }
697         amfree(bsu);
698      } else {
699         if(!interactive) {
700             /* redirect stderr */
701             if(dup2(mesgfd, 2) == -1) {
702                 dbprintf(_("Error redirecting stderr to fd %d: %s\n"),
703                          mesgfd, strerror(errno));
704                 dbclose();
705                 exit(1);
706             }
707         }
708  
709         if(pipe(mesgpipe) == -1) {
710             s = strerror(errno);
711             dbprintf(_("error [opening mesg pipe: %s]\n"), s);
712             error(_("error [opening mesg pipe: %s]"), s);
713         }
714
715         program->start_backup(dle, g_options->hostname,
716                               datafd, mesgpipe[1], indexfd);
717         dbprintf(_("Started backup\n"));
718         parse_backup_messages(dle, mesgpipe[0]);
719         dbprintf(_("Parsed backup messages\n"));
720     }
721
722     run_client_scripts(EXECUTE_ON_POST_DLE_BACKUP, g_options, dle, mesgstream);
723     fflush(mesgstream);
724
725     amfree(qdisk);
726     amfree(qamdevice);
727     amfree(dumpdate);
728     amfree(stroptions);
729     amfree(our_feature_string);
730     am_release_feature_set(our_features);
731     our_features = NULL;
732     free_g_options(g_options);
733
734     dbclose();
735
736     return 0;
737
738  err:
739     if (err_extra) {
740         g_printf(_("ERROR FORMAT ERROR IN REQUEST PACKET '%s'\n"), err_extra);
741         dbprintf(_("REQ packet is bogus: %s\n"), err_extra);
742     } else {
743         g_printf(_("ERROR FORMAT ERROR IN REQUEST PACKET\n"));
744         dbprintf(_("REQ packet is bogus\n"));
745     }
746
747     amfree(qdisk);
748     amfree(qamdevice);
749     amfree(dumpdate);
750     amfree(stroptions);
751     amfree(our_feature_string);
752
753     dbclose();
754     return 1;
755 }
756
757
758 /*
759  * Returns a string for a child process.  Checks the saved dump and
760  * compress pids to see which it is.
761  */
762
763 char *
764 childstr(
765     pid_t pid)
766 {
767     if(pid == dumppid) return program->backup_name;
768     if(pid == comppid) return "compress";
769     if(pid == encpid) return "encrypt";
770     if(pid == indexpid) return "index";
771     if(pid == application_api_pid) {
772         if (!gdle) {
773             dbprintf("gdle == NULL\n");
774             return "gdle == NULL";
775         }
776         return gdle->program;
777     }
778     return "unknown";
779 }
780
781
782 /*
783  * Determine if the child return status really indicates an error.
784  * If so, add the error message to the error string; more than one
785  * child can have an error.
786  */
787
788 int
789 check_status(
790     pid_t       pid,
791     amwait_t    w,
792     int         mesgfd)
793 {
794     char *thiserr = NULL;
795     char *str, *strX;
796     int ret, sig, rc;
797
798     str = childstr(pid);
799
800     if(WIFSIGNALED(w)) {
801         ret = 0;
802         rc = sig = WTERMSIG(w);
803     } else {
804         sig = 0;
805         rc = ret = WEXITSTATUS(w);
806     }
807
808     if(pid == indexpid) {
809         /*
810          * Treat an index failure (other than signal) as a "STRANGE"
811          * rather than an error so the dump goes ahead and gets processed
812          * but the failure is noted.
813          */
814         if(ret != 0) {
815             fdprintf(mesgfd, _("? index %s returned %d\n"), str, ret);
816             rc = 0;
817         }
818         indexpid = -1;
819         strX = "index";
820     } else if(pid == comppid) {
821         /*
822          * compress returns 2 sometimes, but it is ok.
823          */
824 #ifndef HAVE_GZIP
825         if(ret == 2) {
826             rc = 0;
827         }
828 #endif
829         comppid = -1;
830         strX = "compress";
831     } else if(pid == dumppid && tarpid == -1) {
832         /*
833          * Ultrix dump returns 1 sometimes, but it is ok.
834          */
835 #ifdef DUMP_RETURNS_1
836         if(ret == 1) {
837             rc = 0;
838         }
839 #endif
840         dumppid = -1;
841         strX = "dump";
842     } else if(pid == tarpid) {
843         if (ret == 1) {
844             rc = 0;
845         }
846         /*
847          * tar bitches about active filesystems, but we do not care.
848          */
849 #ifdef IGNORE_TAR_ERRORS
850         if(ret == 2) {
851             rc = 0;
852         }
853 #endif
854         dumppid = tarpid = -1;
855         strX = "dump";
856     } else if(pid == application_api_pid) {
857         strX = "Application";
858     } else {
859         strX = "unknown";
860     }
861
862     if(rc == 0) {
863         return 0;                               /* normal exit */
864     }
865
866     if(ret == 0) {
867         thiserr = vstrallocf(_("%s (%d) %s got signal %d"), strX, (int)pid, str,
868                              sig);
869     } else {
870         thiserr = vstrallocf(_("%s (%d) %s returned %d"), strX, (int)pid, str, ret);
871     }
872
873     fdprintf(mesgfd, "? %s\n", thiserr);
874
875     if(errorstr) {
876         errorstr =  newvstrallocf(errorstr, "%s, %s", errorstr, thiserr);
877         amfree(thiserr);
878     } else {
879         errorstr = thiserr;
880         thiserr = NULL;
881     }
882     return 1;
883 }
884
885
886 /*
887  *Send header info to the message file.
888  */
889 void
890 info_tapeheader(
891     dle_t *dle)
892 {
893     g_fprintf(stderr, "%s: info BACKUP=%s\n", get_pname(), program->backup_name);
894
895     g_fprintf(stderr, "%s: info RECOVER_CMD=", get_pname());
896     if (dle->compress == COMP_FAST || dle->compress == COMP_BEST)
897         g_fprintf(stderr, "%s %s |", UNCOMPRESS_PATH,
898 #ifdef UNCOMPRESS_OPT
899                 UNCOMPRESS_OPT
900 #else
901                 ""
902 #endif
903                 );
904
905     g_fprintf(stderr, "%s -xpGf - ...\n", program->restore_name);
906
907     if (dle->compress == COMP_FAST || dle->compress == COMP_BEST)
908         g_fprintf(stderr, "%s: info COMPRESS_SUFFIX=%s\n",
909                         get_pname(), COMPRESS_SUFFIX);
910
911     g_fprintf(stderr, "%s: info end\n", get_pname());
912 }
913
914 void
915 application_api_info_tapeheader(
916     int       mesgfd,
917     char     *prog,
918     dle_t *dle)
919 {
920     char line[1024];
921
922     g_snprintf(line, 1024, "%s: info BACKUP=APPLICATION\n", get_pname());
923     if (full_write(mesgfd, line, strlen(line)) != strlen(line)) {
924         dbprintf(_("error writing to mesgfd socket: %s"), strerror(errno));
925         return;
926     }
927
928     g_snprintf(line, 1024, "%s: info APPLICATION=%s\n", get_pname(), prog);
929     if (full_write(mesgfd, line, strlen(line)) != strlen(line)) {
930         dbprintf(_("error writing to mesgfd socket: %s"), strerror(errno));
931         return;
932     }
933
934     g_snprintf(line, 1024, "%s: info RECOVER_CMD=", get_pname());
935     if (full_write(mesgfd, line, strlen(line)) != strlen(line)) {
936         dbprintf(_("error writing to mesgfd socket: %s"), strerror(errno));
937         return;
938     }
939
940     if (dle->compress == COMP_FAST || dle->compress == COMP_BEST) {
941         g_snprintf(line, 1024, "%s %s |", UNCOMPRESS_PATH,
942 #ifdef UNCOMPRESS_OPT
943                  UNCOMPRESS_OPT
944 #else
945                  ""
946 #endif
947                  );
948         if (full_write(mesgfd, line, strlen(line)) != strlen(line)) {
949             dbprintf(_("error writing to mesgfd socket: %s"), strerror(errno));
950             return;
951         }
952     }
953     g_snprintf(line, 1024, "%s/%s restore [./file-to-restore]+\n",
954                APPLICATION_DIR, prog);
955     if (full_write(mesgfd, line, strlen(line)) != strlen(line)) {
956         dbprintf(_("error writing to mesgfd socket: %s"), strerror(errno));
957         return;
958     }
959
960     if (dle->compress) {
961         g_snprintf(line, 1024, "%s: info COMPRESS_SUFFIX=%s\n",
962                  get_pname(), COMPRESS_SUFFIX);
963         if (full_write(mesgfd, line, strlen(line)) != strlen(line)) {
964             dbprintf(_("error writing to mesgfd socket: %s"), strerror(errno));
965             return;
966         }
967     }
968
969     g_snprintf(line, 1024, "%s: info end\n", get_pname());
970     if (full_write(mesgfd, line, strlen(line)) != strlen(line)) {
971         dbprintf(_("error writing to mesgfd socket: %s"), strerror(errno));
972         return;
973     }
974 }
975
976 pid_t
977 pipefork(
978     void        (*func)(void),
979     char *      fname,
980     int *       stdinfd,
981     int         stdoutfd,
982     int         stderrfd)
983 {
984     int inpipe[2];
985     pid_t pid;
986
987     dbprintf(_("Forking function %s in pipeline\n"), fname);
988
989     if(pipe(inpipe) == -1) {
990         error(_("error [open pipe to %s: %s]"), fname, strerror(errno));
991         /*NOTREACHED*/
992     }
993
994     switch(pid = fork()) {
995     case -1:
996         error(_("error [fork %s: %s]"), fname, strerror(errno));
997         /*NOTREACHED*/
998     default:    /* parent process */
999         aclose(inpipe[0]);      /* close input side of pipe */
1000         *stdinfd = inpipe[1];
1001         break;
1002     case 0:             /* child process */
1003         aclose(inpipe[1]);      /* close output side of pipe */
1004
1005         if(dup2(inpipe[0], 0) == -1) {
1006             error(_("error [fork %s: dup2(%d, in): %s]"),
1007                   fname, inpipe[0], strerror(errno));
1008             /*NOTRACHED*/
1009         }
1010         if(dup2(stdoutfd, 1) == -1) {
1011             error(_("error [fork %s: dup2(%d, out): %s]"),
1012                   fname, stdoutfd, strerror(errno));
1013             /*NOTRACHED*/
1014         }
1015         if(dup2(stderrfd, 2) == -1) {
1016             error(_("error [fork %s: dup2(%d, err): %s]"),
1017                   fname, stderrfd, strerror(errno));
1018             /*NOTRACHED*/
1019         }
1020
1021         func();
1022         exit(0);
1023         /*NOTREACHED*/
1024     }
1025     return pid;
1026 }
1027
1028 int
1029 check_result(
1030     int mesgfd)
1031 {
1032     int goterror;
1033     pid_t wpid;
1034     amwait_t retstat;
1035
1036     goterror = 0;
1037
1038
1039     while((wpid = waitpid((pid_t)-1, &retstat, WNOHANG)) > 0) {
1040         if(check_status(wpid, retstat, mesgfd)) goterror = 1;
1041     }
1042
1043     if (dumppid != -1) {
1044         sleep(5);
1045         while((wpid = waitpid((pid_t)-1, &retstat, WNOHANG)) > 0) {
1046             if(check_status(wpid, retstat, mesgfd)) goterror = 1;
1047         }
1048     }
1049     if (dumppid != -1) {
1050         dbprintf(_("Sending SIGHUP to dump process %d\n"),
1051                   (int)dumppid);
1052         if(dumppid != -1) {
1053             if(kill(dumppid, SIGHUP) == -1) {
1054                 dbprintf(_("Can't send SIGHUP to %d: %s\n"),
1055                           (int)dumppid,
1056                           strerror(errno));
1057             }
1058         }
1059         sleep(5);
1060         while((wpid = waitpid((pid_t)-1, &retstat, WNOHANG)) > 0) {
1061             if(check_status(wpid, retstat, mesgfd)) goterror = 1;
1062         }
1063     }
1064     if (dumppid != -1) {
1065         dbprintf(_("Sending SIGKILL to dump process %d\n"),
1066                   (int)dumppid);
1067         if(dumppid != -1) {
1068             if(kill(dumppid, SIGKILL) == -1) {
1069                 dbprintf(_("Can't send SIGKILL to %d: %s\n"),
1070                           (int)dumppid,
1071                           strerror(errno));
1072             }
1073         }
1074         sleep(5);
1075         while((wpid = waitpid((pid_t)-1, &retstat, WNOHANG)) > 0) {
1076             if(check_status(wpid, retstat, mesgfd)) goterror = 1;
1077         }
1078     }
1079
1080     return goterror;
1081 }
1082
1083 void
1084 parse_backup_messages(
1085     dle_t      *dle,
1086     int         mesgin)
1087 {
1088     int goterror;
1089     char *line;
1090
1091     amfree(errorstr);
1092
1093     for(; (line = areads(mesgin)) != NULL; free(line)) {
1094         process_dumpline(line);
1095     }
1096
1097     if(errno) {
1098         error(_("error [read mesg pipe: %s]"), strerror(errno));
1099         /*NOTREACHED*/
1100     }
1101
1102     goterror = check_result(mesgfd);
1103
1104     if(errorstr) {
1105         error(_("error [%s]"), errorstr);
1106         /*NOTREACHED*/
1107     } else if(dump_size == -1) {
1108         error(_("error [no backup size line]"));
1109         /*NOTREACHED*/
1110     }
1111
1112     program->end_backup(dle, goterror);
1113
1114     fdprintf(mesgfd, _("%s: size %ld\n"), get_pname(), dump_size);
1115     fdprintf(mesgfd, _("%s: end\n"), get_pname());
1116 }
1117
1118
1119 static void
1120 process_dumpline(
1121     char *      str)
1122 {
1123     amregex_t *rp;
1124     char *type;
1125     char startchr;
1126
1127     for(rp = program->re_table; rp->regex != NULL; rp++) {
1128         if(match(rp->regex, str)) {
1129             break;
1130         }
1131     }
1132     if(rp->typ == DMP_SIZE) {
1133         dump_size = (long)((the_num(str, rp->field)* rp->scale+1023.0)/1024.0);
1134     }
1135     switch(rp->typ) {
1136     case DMP_NORMAL:
1137         type = "normal";
1138         startchr = '|';
1139         break;
1140     case DMP_STRANGE:
1141         type = "strange";
1142         startchr = '?';
1143         break;
1144     case DMP_SIZE:
1145         type = "size";
1146         startchr = '|';
1147         break;
1148     case DMP_ERROR:
1149         type = "error";
1150         startchr = '?';
1151         break;
1152     default:
1153         /*
1154          * Should never get here.
1155          */
1156         type = "unknown";
1157         startchr = '!';
1158         break;
1159     }
1160     dbprintf("%3d: %7s(%c): %s\n",
1161               rp->srcline,
1162               type,
1163               startchr,
1164               str);
1165     fdprintf(mesgfd, "%c %s\n", startchr, str);
1166 }
1167
1168
1169 /*
1170  * start_index.  Creates an index file from the output of dump/tar.
1171  * It arranges that input is the fd to be written by the dump process.
1172  * If createindex is not enabled, it does nothing.  If it is not, a
1173  * new process will be created that tees input both to a pipe whose
1174  * read fd is dup2'ed input and to a program that outputs an index
1175  * file to `index'.
1176  *
1177  * make sure that the chat from restore doesn't go to stderr cause
1178  * this goes back to amanda which doesn't expect to see it
1179  * (2>/dev/null should do it)
1180  *
1181  * Originally by Alan M. McIvor, 13 April 1996
1182  *
1183  * Adapted by Alexandre Oliva, 1 May 1997
1184  *
1185  * This program owes a lot to tee.c from GNU sh-utils and dumptee.c
1186  * from the DeeJay backup package.
1187  */
1188
1189 static void
1190 save_fd(
1191     int *       fd,
1192     int         min)
1193 {
1194   int origfd = *fd;
1195
1196   while (*fd >= 0 && *fd < min) {
1197     int newfd = dup(*fd);
1198     if (newfd == -1)
1199       dbprintf(_("Unable to save file descriptor [%s]\n"), strerror(errno));
1200     *fd = newfd;
1201   }
1202   if (origfd != *fd)
1203     dbprintf(_("Dupped file descriptor %i to %i\n"), origfd, *fd);
1204 }
1205
1206 void
1207 start_index(
1208     int         createindex,
1209     int         input,
1210     int         mesg,
1211     int         index,
1212     char *      cmd)
1213 {
1214   int pipefd[2];
1215   FILE *pipe_fp;
1216   int exitcode;
1217
1218   if (!createindex)
1219     return;
1220
1221   if (pipe(pipefd) != 0) {
1222     error(_("creating index pipe: %s"), strerror(errno));
1223     /*NOTREACHED*/
1224   }
1225
1226   switch(indexpid = fork()) {
1227   case -1:
1228     error(_("forking index tee process: %s"), strerror(errno));
1229     /*NOTREACHED*/
1230
1231   default:
1232     aclose(pipefd[0]);
1233     if (dup2(pipefd[1], input) == -1) {
1234       error(_("dup'ping index tee output: %s"), strerror(errno));
1235       /*NOTREACHED*/
1236     }
1237     aclose(pipefd[1]);
1238     return;
1239
1240   case 0:
1241     break;
1242   }
1243
1244   /* now in a child process */
1245   save_fd(&pipefd[0], 4);
1246   save_fd(&index, 4);
1247   save_fd(&mesg, 4);
1248   save_fd(&input, 4);
1249   dup2(pipefd[0], 0);
1250   dup2(index, 1);
1251   dup2(mesg, 2);
1252   dup2(input, 3);
1253   for(index = 4; index < (int)FD_SETSIZE; index++) {
1254     if (index != dbfd()) {
1255       close(index);
1256     }
1257   }
1258
1259   if ((pipe_fp = popen(cmd, "w")) == NULL) {
1260     error(_("couldn't start index creator [%s]"), strerror(errno));
1261     /*NOTREACHED*/
1262   }
1263
1264   dbprintf(_("Started index creator: \"%s\"\n"), cmd);
1265   while(1) {
1266     char buffer[BUFSIZ], *ptr;
1267     ssize_t bytes_read;
1268     size_t bytes_written;
1269     size_t just_written;
1270
1271     do {
1272         bytes_read = read(0, buffer, SIZEOF(buffer));
1273     } while ((bytes_read < 0) && ((errno == EINTR) || (errno == EAGAIN)));
1274
1275     if (bytes_read < 0) {
1276       error(_("index tee cannot read [%s]"), strerror(errno));
1277       /*NOTREACHED*/
1278     }
1279
1280     if (bytes_read == 0)
1281       break; /* finished */
1282
1283     /* write the stuff to the subprocess */
1284     ptr = buffer;
1285     bytes_written = 0;
1286     just_written = full_write(fileno(pipe_fp), ptr, (size_t)bytes_read);
1287     if (just_written < (size_t)bytes_read) {
1288         /* 
1289          * just as we waited for write() to complete.
1290          */
1291         if (errno != EPIPE) {
1292             dbprintf(_("Index tee cannot write to index creator [%s]\n"),
1293                             strerror(errno));
1294         }
1295     } else {
1296         bytes_written += just_written;
1297         ptr += just_written;
1298     }
1299
1300     /* write the stuff to stdout, ensuring none lost when interrupt
1301        occurs */
1302     ptr = buffer;
1303     bytes_written = 0;
1304     just_written = full_write(3, ptr, bytes_read);
1305     if (just_written < (size_t)bytes_read) {
1306         error(_("index tee cannot write [%s]"), strerror(errno));
1307         /*NOTREACHED*/
1308     } else {
1309         bytes_written += just_written;
1310         ptr += just_written;
1311     }
1312   }
1313
1314   aclose(pipefd[1]);
1315
1316   /* finished */
1317   /* check the exit code of the pipe and moan if not 0 */
1318   if ((exitcode = pclose(pipe_fp)) != 0) {
1319     char *exitstr = str_exit_status("Index pipe", exitcode);
1320     dbprintf("%s\n", exitstr);
1321     amfree(exitstr);
1322   } else {
1323     dbprintf(_("Index created successfully\n"));
1324   }
1325   pipe_fp = NULL;
1326
1327   exit(exitcode);
1328 }
1329
1330 extern backup_program_t dump_program, gnutar_program;
1331
1332 backup_program_t *programs[] = {
1333   &dump_program, &gnutar_program, NULL
1334 };