]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/bextract.c
66834f6f12f5f76566452fe269cee233dc928870
[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 static void do_extract(char *fname, char *prefix);
35 static void print_ls_output(char *fname, struct stat *statp);
36
37
38 static DEVICE *dev = NULL;
39 static int ofd = -1;
40
41 static JCR *jcr;
42 static FF_PKT my_ff;
43 static FF_PKT *ff = &my_ff;
44
45 static void usage()
46 {
47    fprintf(stderr,
48 "Usage: bextract [-d debug_level] <bacula-archive> <directory-to-store-files>\n"
49 "       -dnn            set debug level to nn\n"
50 "       -e <file>       exclude list\n"
51 "       -i <file>       include list\n"
52 "       -?              print this message\n\n");
53    exit(1);
54 }
55
56 static void my_free_jcr(JCR *jcr)
57 {
58    return;
59 }
60
61 int main (int argc, char *argv[])
62 {
63    int ch;   
64    FILE *fd;
65    char line[1000];
66    int got_inc = FALSE;
67
68    my_name_is(argc, argv, "bextract");
69    init_msg(NULL, NULL);              /* setup message handler */
70
71    memset(ff, 0, sizeof(FF_PKT));
72    init_include_exclude_files(ff);
73
74    while ((ch = getopt(argc, argv, "d:e:i:?")) != -1) {
75       switch (ch) {
76          case 'd':                    /* debug level */
77             debug_level = atoi(optarg);
78             if (debug_level <= 0)
79                debug_level = 1; 
80             break;
81
82          case 'e':                    /* exclude list */
83             if ((fd = fopen(optarg, "r")) == NULL) {
84                Dmsg2(0, "Could not open exclude file: %s, ERR=%s\n",
85                   optarg, strerror(errno));
86                exit(1);
87             }
88             while (fgets(line, sizeof(line), fd) != NULL) {
89                strip_trailing_junk(line);
90                Dmsg1(900, "add_exclude %s\n", line);
91                add_fname_to_exclude_list(ff, line);
92             }
93             fclose(fd);
94             break;
95
96          case 'i':                    /* include list */
97             if ((fd = fopen(optarg, "r")) == NULL) {
98                Dmsg2(0, "Could not open include file: %s, ERR=%s\n",
99                   optarg, strerror(errno));
100                exit(1);
101             }
102             while (fgets(line, sizeof(line), fd) != NULL) {
103                strip_trailing_junk(line);
104                Dmsg1(900, "add_include %s\n", line);
105                add_fname_to_include_list(ff, 0, line);
106             }
107             fclose(fd);
108             got_inc = TRUE;
109             break;
110
111          case '?':
112          default:
113             usage();
114
115       }  
116    }
117    argc -= optind;
118    argv += optind;
119
120    if (argc != 2) {
121       Dmsg0(0, "Wrong number of arguments: \n");
122       usage();
123    }
124    if (!got_inc) {                            /* If no include file, */
125       add_fname_to_include_list(ff, 0, "/");  /*   include everything */
126    }
127
128    jcr = new_jcr(sizeof(JCR), my_free_jcr);
129    jcr->VolSessionId = 1;
130    jcr->VolSessionTime = (uint32_t)time(NULL);
131    jcr->NumVolumes = 1;
132
133    do_extract(argv[0], argv[1]);
134
135    free_jcr(jcr);
136    return 0;
137 }
138   
139
140 static void do_extract(char *devname, char *where)
141 {
142    int n;     
143    char VolName[100];
144    char *p;
145    struct stat statp;
146    int extract = FALSE;
147    int type;
148    long record_file_index;
149    long total = 0;
150    DEV_RECORD rec;
151    DEV_BLOCK *block;
152    POOLMEM *fname;                    /* original file name */
153    POOLMEM *ofile;                    /* output name with prefix */
154    POOLMEM *lname;                    /* link name */
155    int wherelen;                      /* prefix length */
156
157    if (strncmp(devname, "/dev/", 5) != 0) {
158       /* Try stripping file part */
159       p = devname + strlen(devname);
160       while (p >= devname && *p != '/') {
161          p--;
162       }
163       if (*p == '/') {
164          strcpy(VolName, p+1);
165          *p = 0;
166       }
167    }
168
169    dev = init_dev(NULL, devname);
170    if (!dev || !open_device(dev)) {
171       Emsg1(M_ABORT, 0, "Cannot open %s\n", devname);
172    }
173    Dmsg0(90, "Device opened for read.\n");
174
175    if (stat(where, &statp) < 0) {
176       Emsg2(M_ABORT, 0, "Cannot stat %s. It must exist. ERR=%s\n",
177          where, strerror(errno));
178    }
179    if (!S_ISDIR(statp.st_mode)) {
180       Emsg1(M_ABORT, 0, "%s must be a directory.\n", where);
181    }
182
183    wherelen = strlen(where);
184    fname = get_pool_memory(PM_FNAME);
185    ofile = get_pool_memory(PM_FNAME);
186    lname = get_pool_memory(PM_FNAME);
187
188    block = new_block(dev);
189
190    strcpy(jcr->VolumeName, VolName);
191    Dmsg1(100, "Volume=%s\n", jcr->VolumeName);
192
193    if (!acquire_device_for_read(jcr, dev, block)) {
194       Emsg1(M_ABORT, 0, "Cannot open %s\n", devname);
195    }
196
197    memset(&rec, 0, sizeof(rec));
198    rec.data = get_memory(70000);
199
200    uint32_t compress_buf_size = 70000;
201    POOLMEM *compress_buf = get_memory(compress_buf_size);
202
203    for ( ;; ) {
204
205       if (!read_record(dev, block, &rec)) {
206          uint32_t status;
207          if (dev->state & ST_EOT) {
208             break;
209          }
210          if (dev->state & ST_EOF) {
211             continue;                 /* try again */
212          }
213          Dmsg0(0, "Read Record got a bad record\n");
214          status_dev(dev, &status);
215          Dmsg1(20, "Device status: %x\n", status);
216          if (status & MT_EOD)
217             Emsg0(M_ABORT, 0, "Unexpected End of Data\n");
218          else if (status & MT_EOT)
219             Emsg0(M_ABORT, 0, "Unexpected End of Tape\n");
220          else if (status & MT_EOF)
221             Emsg0(M_ABORT, 0, "Unexpected End of File\n");
222          else if (status & MT_DR_OPEN)
223             Emsg0(M_ABORT, 0, "Tape Door is Open\n");
224          else if (!(status & MT_ONLINE))
225             Emsg0(M_ABORT, 0, "Unexpected Tape is Off-line\n");
226          else
227             Emsg3(M_ABORT, 0, "Read error %d on Record Header %s: %s\n", n, dev_name(dev), strerror(errno));
228       }
229
230
231       /* This is no longer used */
232       if (rec.VolSessionId == 0 && rec.VolSessionTime == 0) {
233          Emsg0(M_ERROR, 0, "Zero header record. This shouldn't happen.\n");
234          break;                       /* END OF FILE */
235       }
236
237       /* 
238        * Check for Start or End of Session Record 
239        *
240        */
241       if (rec.FileIndex < 0) {
242          char *rtype;
243          switch (rec.FileIndex) {
244             case PRE_LABEL:
245                rtype = "Fresh Volume Label";   
246                break;
247             case VOL_LABEL:
248                rtype = "Volume Label";
249                break;
250             case SOS_LABEL:
251                rtype = "Begin Session";
252                break;
253             case EOS_LABEL:
254                rtype = "End Session";
255                break;
256             case EOM_LABEL:
257                rtype = "End of Media";
258                break;
259             default:
260                rtype = "Unknown";
261                break;
262          }
263          if (debug_level > 0) {
264             printf("%s Record: VolSessionId=%d VolSessionTime=%d JobId=%d DataLen=%d\n",
265                rtype, rec.VolSessionId, rec.VolSessionTime, rec.Stream, rec.data_len);
266          }
267          continue;
268       }
269
270       /* File Attributes stream */
271       if (rec.Stream == STREAM_UNIX_ATTRIBUTES) {
272          char *ap, *lp, *fp;
273
274          /* If extracting, it was from previous stream, so
275           * close the output file.
276           */
277          if (extract) {
278             if (ofd < 0) {
279                Emsg0(M_ABORT, 0, "Logic error output file should be open\n");
280             }
281             close(ofd);
282             ofd = -1;
283             extract = FALSE;
284             set_statp(jcr, fname, ofile, lname, type, &statp);
285          }
286
287          if (sizeof_pool_memory(fname) < rec.data_len) {
288             fname = realloc_pool_memory(fname, rec.data_len + 1);
289          }
290          if (sizeof_pool_memory(ofile) < sizeof_pool_memory(fname) + wherelen + 1) {
291             ofile = realloc_pool_memory(ofile, sizeof_pool_memory(fname) + wherelen + 1);
292          }
293          if (sizeof_pool_memory(lname) < rec.data_len) {
294             ofile = realloc_pool_memory(ofile, rec.data_len + 1);
295          }
296          *fname = 0;
297          *lname = 0;
298
299          /*              
300           * An Attributes record consists of:
301           *    File_index
302           *    Type   (FT_types)
303           *    Filename
304           *    Attributes
305           *    Link name (if file linked i.e. FT_LNK)
306           *
307           */
308          sscanf(rec.data, "%ld %d", &record_file_index, &type);
309          if (record_file_index != rec.FileIndex)
310             Emsg2(M_ABORT, 0, "Record header file index %ld not equal record index %ld\n",
311                rec.FileIndex, record_file_index);
312          ap = rec.data;
313          while (*ap++ != ' ')         /* skip record file index */
314             ;
315          while (*ap++ != ' ')         /* skip type */
316             ;
317          /* Save filename and position to attributes */
318          fp = fname;
319          while (*ap != 0) {
320             *fp++  = *ap++;
321          }
322          *fp = *ap++;                 /* terminate filename & point to attribs */
323
324          /* Skip to Link name */
325          if (type == FT_LNK) {
326             lp = ap;
327             while (*lp++ != 0) {
328                ;
329             }
330             strcat(lname, lp);        /* "save" link name */
331          } else {
332             *lname = 0;
333          }
334
335          /* Is this the file we want? */
336          if (file_is_included(ff, fname) && !file_is_excluded(ff, fname)) {
337
338             decode_stat(ap, &statp);
339             /*
340              * Prepend the where directory so that the
341              * files are put where the user wants.
342              *
343              * We do a little jig here to handle Win32 files with
344              * a drive letter.  
345              *   If where is null and we are running on a win32 client,
346              *      change nothing.
347              *   Otherwise, if the second character of the filename is a
348              *   colon (:), change it into a slash (/) -- this creates
349              *   a reasonable pathname on most systems.
350              */
351             strcpy(ofile, where);
352             if (fname[1] == ':') {
353                fname[1] = '/';
354                strcat(ofile, fname);
355                fname[1] = ':';
356             } else {
357                strcat(ofile, fname);
358             }
359 /*          Dmsg1(000, "Restoring: %s\n", ofile); */
360
361             extract = create_file(jcr, fname, ofile, lname, type, &statp, &ofd);
362
363             if (extract) {
364                 print_ls_output(ofile, &statp);   
365             }
366          }
367
368       /* Data stream and extracting */
369       } else if (rec.Stream == STREAM_FILE_DATA) {
370          if (extract) {
371             total += rec.data_len;
372             Dmsg2(8, "Write %ld bytes, total=%ld\n", rec.data_len, total);
373             if ((uint32_t)write(ofd, rec.data, rec.data_len) != rec.data_len) {
374                Emsg1(M_ABORT, 0, "Write error: %s\n", strerror(errno));
375             }
376          }
377  
378       } else if (rec.Stream == STREAM_GZIP_DATA) {
379 #ifdef HAVE_LIBZ
380          if (extract) {
381             uLongf compress_len;
382
383             compress_len = compress_buf_size;
384             if (uncompress((Bytef *)compress_buf, &compress_len, 
385                   (const Bytef *)rec.data, (uLong)rec.data_len) != Z_OK) {
386                Emsg0(M_ABORT, 0, _("Uncompression error.\n"));
387             }
388
389             Dmsg2(100, "Write uncompressed %d bytes, total before write=%d\n", compress_len, total);
390             if ((uLongf)write(ofd, compress_buf, (size_t)compress_len) != compress_len) {
391                Dmsg0(0, "===Write error===\n");
392                Emsg2(M_ABORT, 0, "Write error on %s: %s\n", ofile, strerror(errno));
393             }
394             total += compress_len;
395             Dmsg2(100, "Compress len=%d uncompressed=%d\n", rec.data_len,
396                compress_len);
397          }
398 #else
399          if (extract) {
400             Emsg0(M_ABORT, 0, "GZIP data stream found, but GZIP not configured!\n");
401          }
402 #endif
403
404
405       /* If extracting, wierd stream (not 1 or 2), close output file anyway */
406       } else if (extract) {
407          if (ofd < 0) {
408             Emsg0(M_ABORT, 0, "Logic error output file should be open\n");
409          }
410          close(ofd);
411          ofd = -1;
412          extract = FALSE;
413          set_statp(jcr, fname, ofile, lname, type, &statp);
414       } else if (rec.Stream != STREAM_MD5_SIGNATURE) {
415          Dmsg2(0, "None of above!!! stream=%d data=%s\n", rec.Stream, rec.data);
416       }
417    }
418
419    /* If output file is still open, it was the last one in the
420     * archive since we just hit an end of file, so close the file. 
421     */
422    if (ofd >= 0) {
423       close(ofd);
424       set_statp(jcr, fname, ofile, lname, type, &statp);
425    }
426    release_device(jcr, dev, block);
427
428    free_pool_memory(fname);
429    free_pool_memory(ofile);
430    free_pool_memory(lname);
431    free_pool_memory(compress_buf);
432    term_dev(dev);
433    free_block(block);
434    return;
435 }
436
437 extern char *getuser(uid_t uid);
438 extern char *getgroup(gid_t gid);
439
440 static void print_ls_output(char *fname, struct stat *statp)
441 {
442    char buf[1000]; 
443    char *p, *f;
444    int n;
445
446    p = encode_mode(statp->st_mode, buf);
447    n = sprintf(p, "  %2d ", (uint32_t)statp->st_nlink);
448    p += n;
449    n = sprintf(p, "%-8.8s %-8.8s", getuser(statp->st_uid), getgroup(statp->st_gid));
450    p += n;
451    n = sprintf(p, "%8lld  ", (uint64_t)statp->st_size);
452    p += n;
453    p = encode_time(statp->st_ctime, p);
454    *p++ = ' ';
455    *p++ = ' ';
456    for (f=fname; *f; )
457       *p++ = *f++;
458    *p++ = '\n';
459    *p = 0;
460    fputs(buf, stdout);
461 }