Imported Upstream version 2.5.1p1
[debian/amanda] / restore-src / amfetchdump.c
1 /*
2  * Amanda, The Advanced Maryland Automatic Network Disk Archiver
3  * Copyright (c) 1991-1998 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: amfetchdump.c,v 1.16.2.1 2006/09/27 12:04:09 martinea Exp $
28  *
29  * retrieves specific dumps from a set of amanda tapes
30  */
31
32 #include "amanda.h"
33 #include "tapeio.h"
34 #include "fileheader.h"
35 #include "util.h"
36 #include "restore.h"
37 #include "diskfile.h"
38 #include "tapefile.h"
39 #include "find.h"
40 #include "changer.h"
41 #include "logfile.h"
42
43 #define CREAT_MODE      0640
44
45 extern char *rst_conf_logfile;
46 extern char *config_dir;
47 int get_lock = 0;
48
49 typedef struct needed_tapes_s {
50     char *label;
51     int isafile;
52     find_result_t *files;
53     struct needed_tapes_s *next;
54     struct needed_tapes_s *prev;
55 } needed_tape_t;
56
57 /* local functions */
58
59 void errexit(void);
60 tapelist_t *list_needed_tapes(match_list_t *match_list);
61 void usage(void);
62 int main(int argc, char **argv);
63
64 /* exit routine */
65 static pid_t parent_pid = -1;
66 static void cleanup(void);
67
68
69 /*
70  * Do exit(2) after an error, rather than exit(1).
71  */
72
73 void
74 errexit(void)
75 {
76     exit(2);
77 }
78
79
80 /*
81  * Print usage message and terminate.
82  */
83
84 void
85 usage(void)
86 {
87     fprintf(stderr, "Usage: amfetchdump [options] config hostname [diskname [datestamp [level [hostname [diskname [datestamp [level ... ]]]]]]] [-o configoption]*\n\n");
88     fprintf(stderr, "Goes and grabs a dump from tape, moving tapes around and assembling parts as\n");
89     fprintf(stderr, "necessary.  Files are restored to the current directory, unless otherwise\nspecified.\n\n");
90     fprintf(stderr, "  -p Pipe exactly *one* complete dumpfile to stdout, instead of to disk.\n");
91     fprintf(stderr, "  -O <output dir> Restore files to this directory.\n");
92     fprintf(stderr, "  -d <device> Force restoration from a particular tape device.\n");
93     fprintf(stderr, "  -c Compress output, fastest method available.\n");
94     fprintf(stderr, "  -C Compress output, best filesize method available.\n");
95     fprintf(stderr, "  -l Leave dumps (un)compressed, whichever way they were originally on tape.\n");
96     fprintf(stderr, "  -a Assume all tapes are available via changer, do not prompt for initial load.\n");
97     fprintf(stderr, "  -i <dst_file> Search through tapes and write out an inventory while we\n     restore.  Useful only if normal logs are unavailable.\n");
98     fprintf(stderr, "  -w Wait to put split dumps together until all chunks have been restored.\n");
99     fprintf(stderr, "  -n Do not reassemble split dumpfiles.\n");
100     fprintf(stderr, "  -k Skip the rewind/label read when reading a new tape.\n");
101     fprintf(stderr, "  -s Do not use fast forward to skip files we won't restore.  Use only if fsf\n     causes your tapes to skip too far.\n");
102     fprintf(stderr, "  -b <blocksize> Force a particular block size (default is 32kb).\n");
103     exit(1);
104 }
105
106 /*
107  * Build the list of tapes we'll be wanting, and include data about the
108  * files we want from said tapes while we're at it (the whole find_result
109  * should do fine)
110  */
111 tapelist_t *
112 list_needed_tapes(
113     match_list_t *      match_list)
114 {
115     needed_tape_t *needed_tapes = NULL, *curtape = NULL;
116     disklist_t diskqp;
117     match_list_t *me = NULL;
118     find_result_t *alldumps = NULL;
119     tapelist_t *tapes = NULL;
120     int numtapes = 0;
121     char *conf_diskfile, *conf_tapelist;
122
123     /* For disks and tape lists */
124     conf_diskfile = getconf_str(CNF_DISKFILE);
125     conf_tapelist = getconf_str(CNF_TAPELIST);
126     if (*conf_diskfile == '/') {
127         conf_diskfile = stralloc(conf_diskfile);
128     } else {
129         conf_diskfile = stralloc2(config_dir, conf_diskfile);
130     }
131     if(read_diskfile(conf_diskfile, &diskqp) != 0) {
132         error("could not load disklist \"%s\"", conf_diskfile);
133         /*NOTREACHED*/
134     }
135     if (*conf_tapelist == '/') {
136         conf_tapelist = stralloc(conf_tapelist);
137     } else {
138         conf_tapelist = stralloc2(config_dir, conf_tapelist);
139     }
140     if(read_tapelist(conf_tapelist)) {
141         error("could not load tapelist \"%s\"", conf_tapelist);
142         /*NOTREACHED*/
143     }
144     amfree(conf_diskfile);
145     amfree(conf_tapelist);
146
147     /* Grab a find_output_t of all logged dumps */
148     alldumps = find_dump(1, &diskqp);
149     free_disklist(&diskqp);
150     if(alldumps == NULL){
151         fprintf(stderr, "No dump records found\n");
152         exit(1);
153     }
154
155     /* Compare all known dumps to our match list, note what we'll need */
156     for(me = match_list; me; me = me->next) {
157         find_result_t *curmatch = NULL; 
158         find_result_t *matches = NULL;  
159
160         matches = dumps_match(alldumps, me->hostname, me->diskname,
161                                  me->datestamp, me->level, 1);
162         sort_find_result("Dhklp", &matches);
163         for(curmatch = matches; curmatch; curmatch = curmatch->next){
164             int havetape = 0;
165             if(strcmp("OK", curmatch->status)){
166                 fprintf(stderr,"Dump %s %s %s %d had status '%s', skipping\n",
167                                  curmatch->timestamp, curmatch->hostname,
168                                  curmatch->diskname, curmatch->level,
169                                  curmatch->status);
170                 continue;
171             }
172             for(curtape = needed_tapes; curtape; curtape = curtape->next) {
173                 if(!strcmp(curtape->label, curmatch->label)){
174                     find_result_t *rsttemp = NULL;
175                     find_result_t *rstfile = alloc(SIZEOF(find_result_t));
176                     int keep = 1;
177
178                     memcpy(rstfile, curmatch, SIZEOF(find_result_t));
179
180                     havetape = 1;
181
182                     for(rsttemp = curtape->files;
183                             rsttemp;
184                             rsttemp=rsttemp->next){
185                         if(rstfile->filenum == rsttemp->filenum){
186                             fprintf(stderr, "Seeing multiple entries for tape "
187                                    "%s file " OFF_T_FMT ", using most recent\n",
188                                     curtape->label,
189                                     (OFF_T_FMT_TYPE)rstfile->filenum);
190                             keep = 0;
191                         }
192                     }
193                     if(!keep){
194                         amfree(rstfile);
195                         break;
196                     }
197                     rstfile->next = curtape->files;
198
199                     if(curmatch->filenum < 1) curtape->isafile = 1;
200                     else curtape->isafile = 0;
201                     curtape->files = rstfile;
202                     break;
203                 }
204             }
205             if(!havetape){
206                 find_result_t *rstfile = alloc(SIZEOF(find_result_t));
207                 needed_tape_t *newtape =
208                                           alloc(SIZEOF(needed_tape_t));
209                 memcpy(rstfile, curmatch, SIZEOF(find_result_t));
210                 rstfile->next = NULL;
211                 newtape->files = rstfile;
212                 if(curmatch->filenum < 1) newtape->isafile = 1;
213                 else newtape->isafile = 0;
214                 newtape->label = curmatch->label;
215                 if(needed_tapes){
216                     needed_tapes->prev->next = newtape;
217                     newtape->prev = needed_tapes->prev;
218                     needed_tapes->prev = newtape;
219                 }
220                 else{
221                     needed_tapes = newtape;
222                     needed_tapes->prev = needed_tapes;
223                 }
224                 newtape->next = NULL;
225                 numtapes++;
226 #if 0
227 //              free_find_result(rstfile);
228 #endif
229             } /* if(!havetape) */
230
231         } /* for(curmatch = matches ... */
232     } /* for(me = match_list ... */
233
234     if(numtapes == 0){
235       fprintf(stderr, "No matching dumps found\n");
236       exit(1);
237       /* NOTREACHED */
238     }
239
240     /* stick that list in a structure that librestore will understand */
241     for(curtape = needed_tapes; curtape; curtape = curtape->next) {
242         find_result_t *curfind = NULL;
243         for(curfind = curtape->files; curfind; curfind = curfind->next) {
244             tapes = append_to_tapelist(tapes, curtape->label,
245                                        curfind->filenum, curtape->isafile);
246         }
247     }
248
249     fprintf(stderr, "%d tape(s) needed for restoration\n", numtapes);
250     return(tapes);
251 }
252
253
254 /*
255  * Parses command line, then loops through all files on tape, restoring
256  * files that match the command line criteria.
257  */
258
259 int
260 main(
261     int         argc,
262     char **     argv)
263 {
264     extern int optind;
265     int opt;
266     char *errstr;
267     match_list_t *match_list = NULL;
268     match_list_t *me = NULL;
269     int fd;
270     char *config_name = NULL;
271     char *conffile = NULL;
272     tapelist_t *needed_tapes = NULL;
273     char *e;
274     int arg_state;
275     rst_flags_t *rst_flags;
276     struct passwd *pwent;
277     int    new_argc,   my_argc;
278     char **new_argv, **my_argv;
279
280     for(fd = 3; fd < (int)FD_SETSIZE; fd++) {
281         /*
282          * Make sure nobody spoofs us with a lot of extra open files
283          * that would cause an open we do to get a very high file
284          * descriptor, which in turn might be used as an index into
285          * an array (e.g. an fd_set).
286          */
287         close(fd);
288     }
289
290     set_pname("amfetchdump");
291
292     dbopen(DBG_SUBDIR_SERVER);
293
294 #ifdef FORCE_USERID
295
296     /* we'd rather not run as root */
297
298     if(client_uid == (uid_t) -1 && (pwent = getpwnam(CLIENT_LOGIN)) != NULL) {
299         client_uid = pwent->pw_uid;
300         client_gid = pwent->pw_gid;
301         endpwent();
302     }
303     if(geteuid() == 0) {
304         if(client_uid == (uid_t) -1) {
305             error("error [cannot find user %s in passwd file]\n", CLIENT_LOGIN);
306             /*NOTREACHED*/
307         }
308
309         /*@ignore@*/
310         initgroups(CLIENT_LOGIN, client_gid);
311         /*@end@*/
312         setgid(client_gid);
313         setuid(client_uid);
314     }
315
316 #endif  /* FORCE_USERID */
317
318     /* Don't die when child closes pipe */
319     signal(SIGPIPE, SIG_IGN);
320
321     erroutput_type = ERR_INTERACTIVE;
322
323     onerror(errexit);
324
325     parse_server_conf(argc, argv, &new_argc, &new_argv);
326     my_argc = new_argc;
327     my_argv = new_argv;
328
329     if(my_argc <= 1) {
330         usage();
331         /*NOTREACHED*/
332     }
333
334     rst_flags = new_rst_flags();
335     rst_flags->wait_tape_prompt = 1;
336
337     /* handle options */
338     while( (opt = getopt(my_argc, my_argv, "alht:scCpb:nwi:d:O:")) != -1) {
339         switch(opt) {
340         case 'b':
341             rst_flags->blocksize = (ssize_t)strtol(optarg, &e, 10);
342             if(*e == 'k' || *e == 'K') {
343                 rst_flags->blocksize *= 1024;
344             } else if(*e == 'm' || *e == 'M') {
345                 rst_flags->blocksize *= 1024 * 1024;
346             } else if(*e != '\0') {
347                 error("invalid blocksize value \"%s\"", optarg);
348                 /*NOTREACHED*/
349             }
350             if(rst_flags->blocksize < DISK_BLOCK_BYTES) {
351                 error("minimum block size is %dk", DISK_BLOCK_BYTES / 1024);
352                 /*NOTREACHED*/
353             }
354             break;
355         case 'c': rst_flags->compress = 1; break;
356         case 'O': rst_flags->restore_dir = stralloc(optarg) ; break;
357         case 'd': rst_flags->alt_tapedev = stralloc(optarg) ; break;
358         case 'C':
359             rst_flags->compress = 1;
360             rst_flags->comp_type = COMPRESS_BEST_OPT;
361             break;
362         case 'p': rst_flags->pipe_to_fd = fileno(stdout); break;
363         case 's': rst_flags->fsf = (off_t)0; break;
364         case 'l': rst_flags->leave_comp = 1; break;
365         case 'i': rst_flags->inventory_log = stralloc(optarg); break;
366         case 'n': rst_flags->inline_assemble = 0; break;
367         case 'w': rst_flags->delay_assemble = 1; break;
368         case 'a': rst_flags->wait_tape_prompt = 0; break;
369         case 'h': rst_flags->headers = 1; break;
370         default:
371             usage();
372             /*NOTREACHED*/
373         }
374     }
375
376     /* Check some flags that affect inventorying */
377     if(rst_flags->inventory_log){
378         if(rst_flags->inline_assemble) rst_flags->delay_assemble = 1;
379         rst_flags->inline_assemble = 0;
380         rst_flags->leave_comp = 1;
381         if(rst_flags->compress){
382             error("Cannot force compression when doing inventory/search");
383             /*NOTREACHED*/
384         }
385         fprintf(stderr, "Doing inventory/search, dumps will not be uncompressed or assembled on-the-fly.\n");
386     }
387     else{
388         if(rst_flags->delay_assemble){
389             fprintf(stderr, "Using -w, split dumpfiles will *not* be automatically uncompressed.\n");
390         }
391     }
392
393     /* make sure our options all make sense otherwise */
394     if(check_rst_flags(rst_flags) == -1) {
395         usage();
396         /*NOTREACHED*/
397     }
398
399     config_name = my_argv[optind++];
400     config_dir = vstralloc(CONFIG_DIR, "/", config_name, "/", NULL);
401     conffile = stralloc2(config_dir, CONFFILE_NAME);
402     if (read_conffile(conffile)) {
403         error("errors processing config file \"%s\"", conffile);
404         /*NOTREACHED*/
405     }
406     amfree(conffile);
407
408     dbrename(config_name, DBG_SUBDIR_SERVER);
409
410     if((my_argc - optind) < 1 && !rst_flags->inventory_log){
411         fprintf(stderr, "Not enough arguments\n\n");
412         usage();
413         /*NOTREACHED*/
414     }
415
416 #define ARG_GET_HOST 0
417 #define ARG_GET_DISK 1
418 #define ARG_GET_DATE 2
419 #define ARG_GET_LEVL 3
420
421     arg_state = ARG_GET_HOST;
422     while(optind < my_argc) {
423         switch(arg_state) {
424         case ARG_GET_HOST:
425             /*
426              * New host/disk/date/level set, so allocate a match_list.
427              */
428             me = alloc(SIZEOF(*me));
429             me->hostname = my_argv[optind++];
430             me->diskname = "";
431             me->datestamp = "";
432             me->level = "";
433             me->next = match_list;
434             match_list = me;
435             if(me->hostname[0] != '\0'
436                && (errstr=validate_regexp(me->hostname)) != NULL) {
437                 fprintf(stderr, "%s: bad hostname regex \"%s\": %s\n",
438                         get_pname(), me->hostname, errstr);
439                 usage();
440                 /*NOTREACHED*/
441             }
442             arg_state = ARG_GET_DISK;
443             break;
444         case ARG_GET_DISK:
445             me->diskname = my_argv[optind++];
446             if(me->diskname[0] != '\0'
447                && (errstr=validate_regexp(me->diskname)) != NULL) {
448                 fprintf(stderr, "%s: bad diskname regex \"%s\": %s\n",
449                         get_pname(), me->diskname, errstr);
450                 usage();
451                 /*NOTREACHED*/
452             }
453             arg_state = ARG_GET_DATE;
454             break;
455         case ARG_GET_DATE:
456             me->datestamp = my_argv[optind++];
457             if(me->datestamp[0] != '\0'
458                && (errstr=validate_regexp(me->datestamp)) != NULL) {
459                 fprintf(stderr, "%s: bad datestamp regex \"%s\": %s\n",
460                         get_pname(), me->datestamp, errstr);
461                 usage();
462                 /*NOTREACHED*/
463             }
464             arg_state = ARG_GET_LEVL;
465             break;
466         case ARG_GET_LEVL:
467             me->level = my_argv[optind++];
468             if(me->level[0] != '\0'
469                && (errstr=validate_regexp(me->level)) != NULL) {
470                 fprintf(stderr, "%s: bad level regex \"%s\": %s\n",
471                         get_pname(), me->level, errstr);
472                 usage();
473                 /*NOTREACHED*/
474             }
475         }
476     }
477
478     /* XXX I don't think this can happen */
479     if(match_list == NULL && !rst_flags->inventory_log) {
480         match_list = alloc(SIZEOF(*match_list));
481         match_list->hostname = "";
482         match_list->diskname = "";
483         match_list->datestamp = "";
484         match_list->level = "";
485         match_list->next = NULL;
486     }
487
488     /*
489      * We've been told explicitly to go and search through the tapes the hard
490      * way.
491      */
492     if(rst_flags->inventory_log){
493         fprintf(stderr, "Beginning tape-by-tape search.\n");
494         search_tapes(stderr, stdin, 1, NULL, match_list, rst_flags, NULL);
495         exit(0);
496     }
497
498
499     /* Decide what tapes we'll need */
500     needed_tapes = list_needed_tapes(match_list);
501
502     parent_pid = getpid();
503     atexit(cleanup);
504     get_lock = lock_logfile(); /* config is loaded, should be ok here */
505     if(get_lock == 0) {
506         error("%s exists: amdump or amflush is already running, or you must run amcleanup", rst_conf_logfile);
507     }
508     search_tapes(NULL, stdin, 1, needed_tapes, match_list, rst_flags, NULL);
509     cleanup();
510
511     free_match_list(match_list);
512
513     if(rst_flags->inline_assemble || rst_flags->delay_assemble)
514         flush_open_outputs(1, NULL);
515     else flush_open_outputs(0, NULL);
516
517     free_rst_flags(rst_flags);
518     free_new_argv(new_argc, new_argv);
519
520     return(0);
521 }
522
523 static void
524 cleanup(void)
525 {
526     if(parent_pid == getpid()) {
527         if(get_lock) unlink(rst_conf_logfile);
528     }
529 }