]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/bextract.c
First cut 1.23 -- kes07Jul02
[bacula/bacula] / bacula / src / stored / bextract.c
1 /*
2  *
3  *  Dumb program to extract files from a Bacula backup.
4  *
5  *   Kern E. Sibbald
6  *
7  *   Version $Id$
8  *
9  */
10 /*
11    Copyright (C) 2000, 2001, 2002 Kern Sibbald and John Walker
12
13    This program is free software; you can redistribute it and/or
14    modify it under the terms of the GNU General Public License as
15    published by the Free Software Foundation; either version 2 of
16    the License, or (at your option) any later version.
17
18    This program is distributed in the hope that it will be useful,
19    but WITHOUT ANY WARRANTY; without even the implied warranty of
20    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21    General Public License for more details.
22
23    You should have received a copy of the GNU General Public
24    License along with this program; if not, write to the Free
25    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
26    MA 02111-1307, USA.
27
28  */
29
30 #include "bacula.h"
31 #include "stored.h"
32 #include "findlib/find.h"
33
34
35 static void do_extract(char *fname, char *prefix);
36 static void print_ls_output(char *fname, char *link, int type, struct stat *statp);
37
38
39 static DEVICE *dev = NULL;
40 static int ofd = -1;
41
42 static JCR *jcr;
43 static FF_PKT my_ff;
44 static FF_PKT *ff = &my_ff;
45
46 static BSR *bsr = NULL;
47
48 static void usage()
49 {
50    fprintf(stderr,
51 "Usage: bextract [-d debug_level] <bacula-archive> <directory-to-store-files>\n"
52 "       -b <file>       specify a bootstrap file\n"
53 "       -dnn            set debug level to nn\n"
54 "       -e <file>       exclude list\n"
55 "       -i <file>       include list\n"
56 "       -?              print this message\n\n");
57    exit(1);
58 }
59
60 static void my_free_jcr(JCR *jcr)
61 {
62    return;
63 }
64
65
66 int main (int argc, char *argv[])
67 {
68    int ch;   
69    FILE *fd;
70    char line[1000];
71    int got_inc = FALSE;
72
73    my_name_is(argc, argv, "bextract");
74    init_msg(NULL, NULL);              /* setup message handler */
75
76    memset(ff, 0, sizeof(FF_PKT));
77    init_include_exclude_files(ff);
78
79    while ((ch = getopt(argc, argv, "b:d:e:i:?")) != -1) {
80       switch (ch) {
81          case 'b':                    /* bootstrap file */
82             bsr = parse_bsr(optarg);
83             dump_bsr(bsr);
84             break;
85
86          case 'd':                    /* debug level */
87             debug_level = atoi(optarg);
88             if (debug_level <= 0)
89                debug_level = 1; 
90             break;
91
92          case 'e':                    /* exclude list */
93             if ((fd = fopen(optarg, "r")) == NULL) {
94                Pmsg2(0, "Could not open exclude file: %s, ERR=%s\n",
95                   optarg, strerror(errno));
96                exit(1);
97             }
98             while (fgets(line, sizeof(line), fd) != NULL) {
99                strip_trailing_junk(line);
100                Dmsg1(900, "add_exclude %s\n", line);
101                add_fname_to_exclude_list(ff, line);
102             }
103             fclose(fd);
104             break;
105
106          case 'i':                    /* include list */
107             if ((fd = fopen(optarg, "r")) == NULL) {
108                Pmsg2(0, "Could not open include file: %s, ERR=%s\n",
109                   optarg, strerror(errno));
110                exit(1);
111             }
112             while (fgets(line, sizeof(line), fd) != NULL) {
113                strip_trailing_junk(line);
114                Dmsg1(900, "add_include %s\n", line);
115                add_fname_to_include_list(ff, 0, line);
116             }
117             fclose(fd);
118             got_inc = TRUE;
119             break;
120
121          case '?':
122          default:
123             usage();
124
125       }  
126    }
127    argc -= optind;
128    argv += optind;
129
130    if (argc != 2) {
131       Pmsg0(0, "Wrong number of arguments: \n");
132       usage();
133    }
134    if (!got_inc) {                            /* If no include file, */
135       add_fname_to_include_list(ff, 0, "/");  /*   include everything */
136    }
137
138    jcr = new_jcr(sizeof(JCR), my_free_jcr);
139    jcr->VolSessionId = 1;
140    jcr->VolSessionTime = (uint32_t)time(NULL);
141    jcr->bsr = bsr;
142    strcpy(jcr->Job, "bextract");
143    jcr->dev_name = get_pool_memory(PM_FNAME);
144    strcpy(jcr->dev_name, argv[0]);
145
146    do_extract(argv[0], argv[1]);
147
148    free_jcr(jcr);
149    if (bsr) {
150       free_bsr(bsr);
151    }
152    return 0;
153 }
154   
155
156 static void do_extract(char *devname, char *where)
157 {
158    int n;     
159    char VolName[100];
160    char *p;
161    struct stat statp;
162    int extract = FALSE;
163    int type;
164    long record_file_index;
165    long total = 0;
166    DEV_RECORD rec;
167    DEV_BLOCK *block;
168    POOLMEM *fname;                    /* original file name */
169    POOLMEM *ofile;                    /* output name with prefix */
170    POOLMEM *lname;                    /* link name */
171    int wherelen;                      /* prefix length */
172    SESSION_LABEL sessrec;
173
174    if (strncmp(devname, "/dev/", 5) != 0) {
175       /* Try stripping file part */
176       p = devname + strlen(devname);
177       while (p >= devname && *p != '/') {
178          p--;
179       }
180       if (*p == '/') {
181          strcpy(VolName, p+1);
182          *p = 0;
183       }
184    }
185    strcpy(jcr->VolumeName, VolName);
186
187    dev = init_dev(NULL, devname);
188    if (!dev || !open_device(dev)) {
189       Emsg1(M_ERROR_TERM, 0, "Cannot open %s\n", devname);
190    }
191    Dmsg0(90, "Device opened for read.\n");
192
193    if (stat(where, &statp) < 0) {
194       Emsg2(M_ERROR_TERM, 0, "Cannot stat %s. It must exist. ERR=%s\n",
195          where, strerror(errno));
196    }
197    if (!S_ISDIR(statp.st_mode)) {
198       Emsg1(M_ERROR_TERM, 0, "%s must be a directory.\n", where);
199    }
200
201    wherelen = strlen(where);
202    fname = get_pool_memory(PM_FNAME);
203    ofile = get_pool_memory(PM_FNAME);
204    lname = get_pool_memory(PM_FNAME);
205
206    block = new_block(dev);
207
208    create_vol_list(jcr);
209
210    Dmsg1(20, "Found %d volumes names to restore.\n", jcr->NumVolumes);
211
212    /* 
213     * Ready device for reading, and read records
214     */
215    if (!acquire_device_for_read(jcr, dev, block)) {
216       free_block(block);
217       free_vol_list(jcr);
218       return;
219    }
220
221    memset(&rec, 0, sizeof(rec));
222    rec.data = get_memory(70000);
223
224    uint32_t compress_buf_size = 70000;
225    POOLMEM *compress_buf = get_memory(compress_buf_size);
226
227    for ( ;; ) {
228       int ok;
229       DEV_RECORD *record;             /* for reading label of multi-volumes */
230
231       if (!read_record(dev, block, &rec)) {
232          uint32_t status;
233          Dmsg1(500, "Main read record failed. rem=%d\n", rec.remainder);
234          if (dev->state & ST_EOT) {
235             if (rec.remainder) {
236                Dmsg0(500, "Not end of record.\n");
237             }
238             Dmsg2(90, "NumVolumes=%d CurVolume=%d\n", jcr->NumVolumes, jcr->CurVolume);
239             /*
240              * End Of Tape -- mount next Volume (if another specified)
241              */
242             if (jcr->NumVolumes > 1 && jcr->CurVolume < jcr->NumVolumes) {
243                VOL_LIST *vol = jcr->VolList;
244                /* Find next Volume */
245                jcr->CurVolume++;
246                for (int i=1; i<jcr->CurVolume; i++) {
247                   vol = vol->next;
248                }
249                strcpy(jcr->VolumeName, vol->VolumeName);
250                Dmsg1(400, "There is another volume %s.\n", jcr->VolumeName);
251
252                close_dev(dev);
253                dev->state &= ~ST_READ; 
254                if (!acquire_device_for_read(jcr, dev, block)) {
255                   Emsg2(M_FATAL, 0, "Cannot open Dev=%s, Vol=%s\n", dev_name(dev),
256                         jcr->VolumeName);
257                   ok = FALSE;
258                   break;
259                }
260                record = new_record();
261                Dmsg1(500, "read record after new tape. rem=%d\n", record->remainder);
262                read_record(dev, block, record); /* read vol label */
263                dump_label_record(dev, record, 0);
264                free_record(record);
265                continue;
266             }
267             Dmsg0(90, "End of Device reached.\n");
268             break;                    /* End of Tape */
269          }
270          if (dev->state & ST_EOF) {
271             continue;                 /* try again */
272          }
273          Pmsg0(0, "Read Record got a bad record\n");
274          status_dev(dev, &status);
275          Dmsg1(20, "Device status: %x\n", status);
276          if (status & MT_EOD)
277             Emsg0(M_ERROR_TERM, 0, "Unexpected End of Data\n");
278          else if (status & MT_EOT)
279             Emsg0(M_ERROR_TERM, 0, "Unexpected End of Tape\n");
280          else if (status & MT_EOF)
281             Emsg0(M_ERROR_TERM, 0, "Unexpected End of File\n");
282          else if (status & MT_DR_OPEN)
283             Emsg0(M_ERROR_TERM, 0, "Tape Door is Open\n");
284          else if (!(status & MT_ONLINE))
285             Emsg0(M_ERROR_TERM, 0, "Unexpected Tape is Off-line\n");
286          else
287             Emsg3(M_ERROR_TERM, 0, "Read error %d on Record Header %s: %s\n", n, dev_name(dev), strerror(errno));
288       }
289
290
291       /* This is no longer used */
292       if (rec.VolSessionId == 0 && rec.VolSessionTime == 0) {
293          Emsg0(M_ERROR, 0, "Zero header record. This shouldn't happen.\n");
294          break;                       /* END OF FILE */
295       }
296
297       /* 
298        * Check for Start or End of Session Record 
299        *
300        */
301       if (rec.FileIndex < 0) {
302          char *rtype;
303          memset(&sessrec, 0, sizeof(sessrec));
304          switch (rec.FileIndex) {
305             case PRE_LABEL:
306                rtype = "Fresh Volume Label";   
307                break;
308             case VOL_LABEL:
309                rtype = "Volume Label";
310                unser_volume_label(dev, &rec);
311                break;
312             case SOS_LABEL:
313                rtype = "Begin Session";
314                unser_session_label(&sessrec, &rec);
315                break;
316             case EOS_LABEL:
317                rtype = "End Session";
318                break;
319             case EOM_LABEL:
320                rtype = "End of Media";
321                break;
322             default:
323                rtype = "Unknown";
324                break;
325          }
326          if (debug_level > 0) {
327             printf("%s Record: VolSessionId=%d VolSessionTime=%d JobId=%d DataLen=%d\n",
328                rtype, rec.VolSessionId, rec.VolSessionTime, rec.Stream, rec.data_len);
329          }
330
331          Dmsg1(40, "Got label = %d\n", rec.FileIndex);
332          if (rec.FileIndex == EOM_LABEL) { /* end of tape? */
333             Dmsg0(40, "Get EOM LABEL\n");
334             break;                         /* yes, get out */
335          }
336          continue;                         /* ignore other labels */
337       } /* end if label record */
338
339       /* Is this the file we want? */
340       if (bsr && !match_bsr(bsr, &rec, &dev->VolHdr, &sessrec)) {
341          continue;
342       }
343
344       /* File Attributes stream */
345       if (rec.Stream == STREAM_UNIX_ATTRIBUTES) {
346          char *ap, *lp, *fp;
347
348          /* If extracting, it was from previous stream, so
349           * close the output file.
350           */
351          if (extract) {
352             if (ofd < 0) {
353                Emsg0(M_ERROR_TERM, 0, "Logic error output file should be open\n");
354             }
355             close(ofd);
356             ofd = -1;
357             extract = FALSE;
358             set_statp(jcr, fname, ofile, lname, type, &statp);
359          }
360
361          if (sizeof_pool_memory(fname) < rec.data_len) {
362             fname = realloc_pool_memory(fname, rec.data_len + 1);
363          }
364          if (sizeof_pool_memory(ofile) < sizeof_pool_memory(fname) + wherelen + 1) {
365             ofile = realloc_pool_memory(ofile, sizeof_pool_memory(fname) + wherelen + 1);
366          }
367          if (sizeof_pool_memory(lname) < rec.data_len) {
368             ofile = realloc_pool_memory(ofile, rec.data_len + 1);
369          }
370          *fname = 0;
371          *lname = 0;
372
373          /*              
374           * An Attributes record consists of:
375           *    File_index
376           *    Type   (FT_types)
377           *    Filename
378           *    Attributes
379           *    Link name (if file linked i.e. FT_LNK)
380           *
381           */
382          sscanf(rec.data, "%ld %d", &record_file_index, &type);
383          if (record_file_index != rec.FileIndex)
384             Emsg2(M_ERROR_TERM, 0, "Record header file index %ld not equal record index %ld\n",
385                rec.FileIndex, record_file_index);
386          ap = rec.data;
387          while (*ap++ != ' ')         /* skip record file index */
388             ;
389          while (*ap++ != ' ')         /* skip type */
390             ;
391          /* Save filename and position to attributes */
392          fp = fname;
393          while (*ap != 0) {
394             *fp++  = *ap++;
395          }
396          *fp = *ap++;                 /* terminate filename & point to attribs */
397
398          /* Skip to Link name */
399          if (type == FT_LNK) {
400             lp = ap;
401             while (*lp++ != 0) {
402                ;
403             }
404             strcat(lname, lp);        /* "save" link name */
405          } else {
406             *lname = 0;
407          }
408
409             
410          if (file_is_included(ff, fname) && !file_is_excluded(ff, fname)) {
411
412             decode_stat(ap, &statp);
413             /*
414              * Prepend the where directory so that the
415              * files are put where the user wants.
416              *
417              * We do a little jig here to handle Win32 files with
418              * a drive letter.  
419              *   If where is null and we are running on a win32 client,
420              *      change nothing.
421              *   Otherwise, if the second character of the filename is a
422              *   colon (:), change it into a slash (/) -- this creates
423              *   a reasonable pathname on most systems.
424              */
425             strcpy(ofile, where);
426             if (fname[1] == ':') {
427                fname[1] = '/';
428                strcat(ofile, fname);
429                fname[1] = ':';
430             } else {
431                strcat(ofile, fname);
432             }
433 /*          Pmsg1(000, "Restoring: %s\n", ofile); */
434
435             extract = create_file(jcr, fname, ofile, lname, type, &statp, &ofd);
436
437             if (extract) {
438                 print_ls_output(ofile, lname, type, &statp);   
439             }
440          }
441
442       /* Data stream and extracting */
443       } else if (rec.Stream == STREAM_FILE_DATA) {
444          if (extract) {
445             total += rec.data_len;
446             Dmsg2(8, "Write %ld bytes, total=%ld\n", rec.data_len, total);
447             if ((uint32_t)write(ofd, rec.data, rec.data_len) != rec.data_len) {
448                Emsg1(M_ERROR_TERM, 0, "Write error: %s\n", strerror(errno));
449             }
450          }
451  
452       } else if (rec.Stream == STREAM_GZIP_DATA) {
453 #ifdef HAVE_LIBZ
454          if (extract) {
455             uLongf compress_len;
456
457             compress_len = compress_buf_size;
458             if (uncompress((Bytef *)compress_buf, &compress_len, 
459                   (const Bytef *)rec.data, (uLong)rec.data_len) != Z_OK) {
460                Emsg0(M_ERROR_TERM, 0, _("Uncompression error.\n"));
461             }
462
463             Dmsg2(100, "Write uncompressed %d bytes, total before write=%d\n", compress_len, total);
464             if ((uLongf)write(ofd, compress_buf, (size_t)compress_len) != compress_len) {
465                Pmsg0(0, "===Write error===\n");
466                Emsg2(M_ERROR_TERM, 0, "Write error on %s: %s\n", ofile, strerror(errno));
467             }
468             total += compress_len;
469             Dmsg2(100, "Compress len=%d uncompressed=%d\n", rec.data_len,
470                compress_len);
471          }
472 #else
473          if (extract) {
474             Emsg0(M_ERROR_TERM, 0, "GZIP data stream found, but GZIP not configured!\n");
475          }
476 #endif
477
478
479       /* If extracting, wierd stream (not 1 or 2), close output file anyway */
480       } else if (extract) {
481          if (ofd < 0) {
482             Emsg0(M_ERROR_TERM, 0, "Logic error output file should be open\n");
483          }
484          close(ofd);
485          ofd = -1;
486          extract = FALSE;
487          set_statp(jcr, fname, ofile, lname, type, &statp);
488       } else if (rec.Stream != STREAM_MD5_SIGNATURE) {
489          Pmsg2(0, "None of above!!! stream=%d data=%s\n", rec.Stream, rec.data);
490       }
491    }
492
493    /* If output file is still open, it was the last one in the
494     * archive since we just hit an end of file, so close the file. 
495     */
496    if (ofd >= 0) {
497       close(ofd);
498       set_statp(jcr, fname, ofile, lname, type, &statp);
499    }
500    release_device(jcr, dev, block);
501
502    free_pool_memory(fname);
503    free_pool_memory(ofile);
504    free_pool_memory(lname);
505    free_pool_memory(compress_buf);
506    term_dev(dev);
507    free_block(block);
508    return;
509 }
510
511 extern char *getuser(uid_t uid);
512 extern char *getgroup(gid_t gid);
513
514 static void print_ls_output(char *fname, char *link, int type, struct stat *statp)
515 {
516    char buf[1000]; 
517    char ec1[30];
518    char *p, *f;
519    int n;
520
521    p = encode_mode(statp->st_mode, buf);
522    n = sprintf(p, "  %2d ", (uint32_t)statp->st_nlink);
523    p += n;
524    n = sprintf(p, "%-8.8s %-8.8s", getuser(statp->st_uid), getgroup(statp->st_gid));
525    p += n;
526    n = sprintf(p, "%8.8s ", edit_uint64(statp->st_size, ec1));
527    p += n;
528    p = encode_time(statp->st_ctime, p);
529    *p++ = ' ';
530    *p++ = ' ';
531    /* Copy file name */
532    for (f=fname; *f && (p-buf) < (int)sizeof(buf); )
533       *p++ = *f++;
534    if (type == FT_LNK) {
535       *p++ = ' ';
536       *p++ = '-';
537       *p++ = '>';
538       *p++ = ' ';
539       /* Copy link name */
540       for (f=link; *f && (p-buf) < (int)sizeof(buf); )
541          *p++ = *f++;
542    }
543    *p++ = '\n';
544    *p = 0;
545    fputs(buf, stdout);
546 }
547
548 /* Dummies to replace askdir.c */
549 int     dir_get_volume_info(JCR *jcr) { return 1;}
550 int     dir_find_next_appendable_volume(JCR *jcr) { return 1;}
551 int     dir_update_volume_info(JCR *jcr, VOLUME_CAT_INFO *vol, int relabel) { return 1; }
552 int     dir_ask_sysop_to_mount_next_volume(JCR *jcr, DEVICE *dev) { return 1; }
553 int     dir_update_file_attributes(JCR *jcr, DEV_RECORD *rec) { return 1;}
554 int     dir_send_job_status(JCR *jcr) {return 1;}
555
556
557 int dir_ask_sysop_to_mount_volume(JCR *jcr, DEVICE *dev)
558 {
559    fprintf(stderr, "Mount Volume %s on device %s and press return when ready: ",
560       jcr->VolumeName, dev_name(dev));
561    getchar();   
562    return 1;
563 }