]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/ua_tree.c
Restructure tree.c + misc
[bacula/bacula] / bacula / src / dird / ua_tree.c
1 /*
2  *
3  *   Bacula Director -- User Agent Database File tree for Restore
4  *      command. This file interacts with the user implementing the
5  *      UA tree commands.
6  *
7  *     Kern Sibbald, July MMII
8  *
9  *   Version $Id$
10  */
11
12 /*
13    Copyright (C) 2002-2004 Kern Sibbald and John Walker
14
15    This program is free software; you can redistribute it and/or
16    modify it under the terms of the GNU General Public License as
17    published by the Free Software Foundation; either version 2 of
18    the License, or (at your option) any later version.
19
20    This program is distributed in the hope that it will be useful,
21    but WITHOUT ANY WARRANTY; without even the implied warranty of
22    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23    General Public License for more details.
24
25    You should have received a copy of the GNU General Public
26    License along with this program; if not, write to the Free
27    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
28    MA 02111-1307, USA.
29
30  */
31
32 #include "bacula.h"
33 #include "dird.h"
34 #include <fnmatch.h>
35 #include "findlib/find.h"
36
37
38 /* Forward referenced commands */
39
40 static int markcmd(UAContext *ua, TREE_CTX *tree);
41 static int markdircmd(UAContext *ua, TREE_CTX *tree);
42 static int countcmd(UAContext *ua, TREE_CTX *tree);
43 static int findcmd(UAContext *ua, TREE_CTX *tree);
44 static int lscmd(UAContext *ua, TREE_CTX *tree);
45 static int lsmarkcmd(UAContext *ua, TREE_CTX *tree);
46 static int dircmd(UAContext *ua, TREE_CTX *tree);
47 static int estimatecmd(UAContext *ua, TREE_CTX *tree);
48 static int helpcmd(UAContext *ua, TREE_CTX *tree);
49 static int cdcmd(UAContext *ua, TREE_CTX *tree);
50 static int pwdcmd(UAContext *ua, TREE_CTX *tree);
51 static int unmarkcmd(UAContext *ua, TREE_CTX *tree);
52 static int unmarkdircmd(UAContext *ua, TREE_CTX *tree);
53 static int quitcmd(UAContext *ua, TREE_CTX *tree);
54 static int donecmd(UAContext *ua, TREE_CTX *tree);
55
56
57 struct cmdstruct { const char *key; int (*func)(UAContext *ua, TREE_CTX *tree); const char *help; }; 
58 static struct cmdstruct commands[] = {
59  { N_("cd"),         cdcmd,        _("change current directory")},
60  { N_("count"),      countcmd,     _("count marked files in and below the cd")},
61  { N_("dir"),        dircmd,       _("list current directory")},    
62  { N_("done"),       donecmd,      _("leave file selection mode")},
63  { N_("estimate"),   estimatecmd,  _("estimate restore size")},
64  { N_("exit"),       donecmd,      _("exit = done")},
65  { N_("find"),       findcmd,      _("find files -- wildcards allowed")},
66  { N_("help"),       helpcmd,      _("print help")},
67  { N_("ls"),         lscmd,        _("list current directory -- wildcards allowed")},    
68  { N_("lsmark"),     lsmarkcmd,    _("list the marked files in and below the cd")},    
69  { N_("mark"),       markcmd,      _("mark file to be restored")},
70  { N_("markdir"),    markdircmd,   _("mark directory entry to be restored -- nonrecursive")},
71  { N_("pwd"),        pwdcmd,       _("print current working directory")},
72  { N_("unmark"),     unmarkcmd,    _("unmark file to be restored")},
73  { N_("unmarkdir"),  unmarkdircmd, _("unmark directory -- no recursion")},
74  { N_("quit"),       quitcmd,      _("quit")},
75  { N_("?"),          helpcmd,      _("print help")},    
76              };
77 #define comsize (sizeof(commands)/sizeof(struct cmdstruct))
78
79
80 /*
81  * Enter a prompt mode where the user can select/deselect
82  *  files to be restored. This is sort of like a mini-shell
83  *  that allows "cd", "pwd", "add", "rm", ...
84  */
85 bool user_select_files_from_tree(TREE_CTX *tree)
86 {
87    char cwd[2000];
88    bool stat;
89    /* Get a new context so we don't destroy restore command args */
90    UAContext *ua = new_ua_context(tree->ua->jcr);
91    ua->UA_sock = tree->ua->UA_sock;   /* patch in UA socket */
92
93    bsendmsg(tree->ua, _( 
94       "\nYou are now entering file selection mode where you add and\n"
95       "remove files to be restored. All files are initially added.\n"
96       "Enter \"done\" to leave this mode.\n\n"));
97    /*
98     * Enter interactive command handler allowing selection
99     *  of individual files.
100     */
101    tree->node = (TREE_NODE *)tree->root;
102    tree_getpath(tree->node, cwd, sizeof(cwd));
103    bsendmsg(tree->ua, _("cwd is: %s\n"), cwd);
104    for ( ;; ) {       
105       int found, len, i;
106       if (!get_cmd(ua, "$ ")) {
107          break;
108       }
109       parse_ua_args(ua);
110       if (ua->argc == 0) {
111          break;
112       }
113
114       len = strlen(ua->argk[0]);
115       found = 0;
116       stat = false;
117       for (i=0; i<(int)comsize; i++)       /* search for command */
118          if (strncasecmp(ua->argk[0],  _(commands[i].key), len) == 0) {
119             stat = (*commands[i].func)(ua, tree);   /* go execute command */
120             found = 1;
121             break;
122          }
123       if (!found) {
124          bsendmsg(tree->ua, _("Illegal command. Enter \"done\" to exit.\n"));
125          continue;
126       }
127       if (!stat) {
128          break;
129       }
130    }
131    ua->UA_sock = NULL;                /* don't release restore socket */
132    stat = !ua->quit;
133    ua->quit = false;
134    free_ua_context(ua);               /* get rid of temp UA context */
135    return stat;
136 }
137
138
139 /*
140  * This callback routine is responsible for inserting the
141  *  items it gets into the directory tree. For each JobId selected
142  *  this routine is called once for each file. We do not allow
143  *  duplicate filenames, but instead keep the info from the most
144  *  recent file entered (i.e. the JobIds are assumed to be sorted)
145  *
146  *   See uar_sel_files in sql_cmds.c for query that calls us.
147  *      row[0]=Path, row[1]=Filename, row[2]=FileIndex
148  *      row[3]=JobId row[4]=LStat
149  */
150 int insert_tree_handler(void *ctx, int num_fields, char **row)
151 {
152    struct stat statp;
153    TREE_CTX *tree = (TREE_CTX *)ctx;
154    TREE_NODE *node;
155    int type;
156    bool hard_link, ok;
157    int FileIndex;
158    JobId_t JobId;
159
160    strip_trailing_junk(row[1]);
161    if (*row[1] == 0) {                /* no filename => directory */
162       if (*row[0] != '/') {           /* Must be Win32 directory */
163          type = TN_DIR_NLS;
164       } else {
165          type = TN_DIR;
166       }
167    } else {
168       type = TN_FILE;
169    }
170    hard_link = (decode_LinkFI(row[4], &statp) != 0);
171    node = insert_tree_node(row[0], row[1], NULL, tree->root, NULL);
172    /* Note, if node already exists, save new one for next time */
173    JobId = (JobId_t)str_to_int64(row[3]);
174    FileIndex = atoi(row[2]);
175    /*
176     * - The first time we see a file (node->inserted==true), we accept it.
177     * - In the same JobId, we accept only the first copy of a
178     *   hard linked file (the others are simply pointers).
179     * - In the same JobId, we accept the last copy of any other
180     *   file -- in particular directories.
181     *
182     * All the code to set ok could be condensed to a single
183     *  line, but it would be even harder to read.
184     */
185    ok = true;
186    if (!node->inserted && JobId == node->JobId) {
187       if ((hard_link && FileIndex > node->FileIndex) ||
188           (!hard_link && FileIndex < node->FileIndex)) {
189          ok = false;
190       }
191    }
192    if (ok) {
193       node->hard_link = hard_link;
194       node->FileIndex = FileIndex;
195       node->JobId = JobId;
196       node->type = type;
197       node->soft_link = S_ISLNK(statp.st_mode) != 0;
198       if (tree->all) {
199          node->extract = true;          /* extract all by default */
200          if (type == TN_DIR || type == TN_DIR_NLS) {
201             node->extract_dir = true;   /* if dir, extract it */
202          }
203       }
204    }
205    tree->cnt++;
206    return 0;
207 }
208
209
210 /*
211  * Set extract to value passed. We recursively walk
212  *  down the tree setting all children if the 
213  *  node is a directory.
214  */
215 static int set_extract(UAContext *ua, TREE_NODE *node, TREE_CTX *tree, bool extract)
216 {
217    TREE_NODE *n;
218    FILE_DBR fdbr;
219    struct stat statp;
220    int count = 0;
221
222    node->extract = extract;
223    if (node->type == TN_DIR || node->type == TN_DIR_NLS) {
224       node->extract_dir = extract;    /* set/clear dir too */
225    }
226    if (node->type != TN_NEWDIR) {
227       count++;
228    }
229    /* For a non-file (i.e. directory), we see all the children */
230    if (node->type != TN_FILE || (node->soft_link && tree_node_has_child(node))) {
231       /* Recursive set children within directory */
232       foreach_child(n, node) {
233          count += set_extract(ua, n, tree, extract);
234       }
235       /*
236        * Walk up tree marking any unextracted parent to be
237        * extracted.
238        */
239       if (extract) {
240          while (node->parent && !node->parent->extract_dir) {
241             node = node->parent;
242             node->extract_dir = true;
243          }
244       }
245    } else if (extract) {
246       char cwd[2000];
247       /*
248        * Ordinary file, we get the full path, look up the
249        * attributes, decode them, and if we are hard linked to
250        * a file that was saved, we must load that file too.
251        */
252       tree_getpath(node, cwd, sizeof(cwd));
253       fdbr.FileId = 0;
254       fdbr.JobId = node->JobId;
255       if (node->hard_link && db_get_file_attributes_record(ua->jcr, ua->db, cwd, NULL, &fdbr)) {
256          int32_t LinkFI;
257          decode_stat(fdbr.LStat, &statp, &LinkFI); /* decode stat pkt */
258          /*
259           * If we point to a hard linked file, traverse the tree to
260           * find that file, and mark it to be restored as well. It
261           * must have the Link we just obtained and the same JobId.
262           */
263          if (LinkFI) {
264             for (n=first_tree_node(tree->root); n; n=next_tree_node(n)) {
265                if (n->FileIndex == LinkFI && n->JobId == node->JobId) {
266                   n->extract = true;
267                   if (n->type == TN_DIR || n->type == TN_DIR_NLS) {
268                      n->extract_dir = true;
269                   }
270                   break;
271                }
272             }
273          }
274       }
275    }
276    return count;
277 }
278
279 /*
280  * Recursively mark the current directory to be restored as 
281  *  well as all directories and files below it.
282  */
283 static int markcmd(UAContext *ua, TREE_CTX *tree)
284 {
285    TREE_NODE *node;
286    int count = 0;
287
288    if (ua->argc < 2 || !tree_node_has_child(tree->node)) {
289       bsendmsg(ua, _("No files marked.\n"));
290       return 1;
291    }
292    for (int i=1; i < ua->argc; i++) {
293       foreach_child(node, tree->node) {
294          if (fnmatch(ua->argk[i], node->fname, 0) == 0) {
295             count += set_extract(ua, node, tree, true);
296          }
297       }
298    }
299    if (count == 0) {
300       bsendmsg(ua, _("No files marked.\n"));
301    } else {
302       bsendmsg(ua, _("%d file%s marked.\n"), count, count==0?"":"s");
303    }
304    return 1;
305 }
306
307 static int markdircmd(UAContext *ua, TREE_CTX *tree)
308 {
309    TREE_NODE *node;
310    int count = 0;
311
312    if (ua->argc < 2 || !tree_node_has_child(tree->node)) {
313       bsendmsg(ua, _("No files marked.\n"));
314       return 1;
315    }
316    for (int i=1; i < ua->argc; i++) {
317       foreach_child(node, tree->node) {
318          if (fnmatch(ua->argk[i], node->fname, 0) == 0) {
319             if (node->type == TN_DIR || node->type == TN_DIR_NLS) {
320                node->extract_dir = true;
321                count++;
322             }
323          }
324       }
325    }
326    if (count == 0) {
327       bsendmsg(ua, _("No directories marked.\n"));
328    } else {
329       bsendmsg(ua, _("%d director%s marked.\n"), count, count==1?"y":"ies");
330    }
331    return 1;
332 }
333
334
335 static int countcmd(UAContext *ua, TREE_CTX *tree)
336 {
337    int total, num_extract;
338
339    total = num_extract = 0;
340    for (TREE_NODE *node=first_tree_node(tree->root); node; node=next_tree_node(node)) {
341       if (node->type != TN_NEWDIR) {
342          total++;
343          if (node->extract || node->extract_dir) {
344             num_extract++;
345          }
346       }
347    }
348    bsendmsg(ua, "%d total files/dirs. %d marked to be restored.\n", total, num_extract);
349    return 1;
350 }
351
352 static int findcmd(UAContext *ua, TREE_CTX *tree)
353 {
354    char cwd[2000];
355
356    if (ua->argc == 1) {
357       bsendmsg(ua, _("No file specification given.\n"));
358       return 0;
359    }
360    
361    for (int i=1; i < ua->argc; i++) {
362       for (TREE_NODE *node=first_tree_node(tree->root); node; node=next_tree_node(node)) {
363          if (fnmatch(ua->argk[i], node->fname, 0) == 0) {
364             const char *tag;
365             tree_getpath(node, cwd, sizeof(cwd));
366             if (node->extract) {
367                tag = "*";
368             } else if (node->extract_dir) {
369                tag = "+";
370             } else {
371                tag = "";
372             }
373             bsendmsg(ua, "%s%s\n", tag, cwd);
374          }
375       }
376    }
377    return 1;
378 }
379
380
381
382 static int lscmd(UAContext *ua, TREE_CTX *tree)
383 {
384    TREE_NODE *node;
385
386    if (!tree_node_has_child(tree->node)) {     
387       return 1;
388    }
389    foreach_child(node, tree->node) {
390       if (ua->argc == 1 || fnmatch(ua->argk[1], node->fname, 0) == 0) {
391          const char *tag;
392          if (node->extract) {
393             tag = "*";
394          } else if (node->extract_dir) {
395             tag = "+";
396          } else {
397             tag = "";
398          }
399          bsendmsg(ua, "%s%s%s\n", tag, node->fname, tree_node_has_child(node)?"/":"");
400       }
401    }
402    return 1;
403 }
404
405 /*
406  * Ls command that lists only the marked files
407  */
408 static void rlsmark(UAContext *ua, TREE_NODE *node) 
409 {
410    if (!tree_node_has_child(node)) {     
411       return;
412    }
413    foreach_child(node, node) {
414       if ((ua->argc == 1 || fnmatch(ua->argk[1], node->fname, 0) == 0) &&
415           (node->extract || node->extract_dir)) {
416          const char *tag;
417          if (node->extract) {
418             tag = "*";
419          } else if (node->extract_dir) {
420             tag = "+";
421          } else {
422             tag = "";
423          }
424          bsendmsg(ua, "%s%s%s\n", tag, node->fname, tree_node_has_child(node)?"/":"");
425          if (tree_node_has_child(node)) {
426             rlsmark(ua, node);
427          }
428       }
429    }
430 }
431
432 static int lsmarkcmd(UAContext *ua, TREE_CTX *tree)
433 {
434    rlsmark(ua, tree->node);
435    return 1;
436 }
437
438
439
440 extern char *getuser(uid_t uid);
441 extern char *getgroup(gid_t gid);
442
443 /*
444  * This is actually the long form used for "dir"
445  */
446 static void ls_output(char *buf, const char *fname, const char *tag, struct stat *statp)
447 {
448    char *p;
449    const char *f;
450    char ec1[30];
451    int n;
452
453    p = encode_mode(statp->st_mode, buf);
454    n = sprintf(p, "  %2d ", (uint32_t)statp->st_nlink);
455    p += n;
456    n = sprintf(p, "%-8.8s %-8.8s", getuser(statp->st_uid), getgroup(statp->st_gid));
457    p += n;
458    n = sprintf(p, "%8.8s  ", edit_uint64(statp->st_size, ec1));
459    p += n;
460    p = encode_time(statp->st_ctime, p);
461    *p++ = ' ';
462    *p++ = *tag;
463    for (f=fname; *f; ) {
464       *p++ = *f++;
465    }
466    *p = 0;
467 }
468
469
470 /*
471  * Like ls command, but give more detail on each file
472  */
473 static int dircmd(UAContext *ua, TREE_CTX *tree)
474 {
475    TREE_NODE *node;
476    FILE_DBR fdbr;
477    struct stat statp;
478    char buf[1100];
479    char cwd[1100], *pcwd;
480
481    if (!tree_node_has_child(tree->node)) {     
482       bsendmsg(ua, "Node %s has no children.\n", tree->node->fname);
483       return 1;
484    }
485
486    foreach_child(node, tree->node) {
487       const char *tag;
488       if (ua->argc == 1 || fnmatch(ua->argk[1], node->fname, 0) == 0) {
489          if (node->extract) {
490             tag = "*";
491          } else if (node->extract_dir) {
492             tag = "+";
493          } else {
494             tag = " ";
495          }
496          tree_getpath(node, cwd, sizeof(cwd));
497          fdbr.FileId = 0;
498          fdbr.JobId = node->JobId;
499          /*
500           * Strip / from soft links to directories.
501           *   This is because soft links to files have a trailing slash
502           *   when returned from tree_getpath, but db_get_file_attr...
503           *   treats soft links as files, so they do not have a trailing
504           *   slash like directory names.
505           */
506          if (node->type == TN_FILE && tree_node_has_child(node)) {
507             bstrncpy(buf, cwd, sizeof(buf));
508             pcwd = buf;
509             int len = strlen(buf);
510             if (len > 1) {
511                buf[len-1] = 0;        /* strip trailing / */
512             }
513          } else {
514             pcwd = cwd;
515          }
516          if (db_get_file_attributes_record(ua->jcr, ua->db, pcwd, NULL, &fdbr)) {
517             int32_t LinkFI;
518             decode_stat(fdbr.LStat, &statp, &LinkFI); /* decode stat pkt */
519          } else {
520             /* Something went wrong getting attributes -- print name */
521             memset(&statp, 0, sizeof(statp));
522          }
523          ls_output(buf, cwd, tag, &statp);
524          bsendmsg(ua, "%s\n", buf);
525       }
526    }
527    return 1;
528 }
529
530
531 static int estimatecmd(UAContext *ua, TREE_CTX *tree)
532 {
533    int total, num_extract;
534    uint64_t total_bytes = 0;
535    FILE_DBR fdbr;
536    struct stat statp;
537    char cwd[1100];
538    char ec1[50];
539
540    total = num_extract = 0;
541    for (TREE_NODE *node=first_tree_node(tree->root); node; node=next_tree_node(node)) {
542       if (node->type != TN_NEWDIR) {
543          total++;
544          /* If regular file, get size */
545          if (node->extract && node->type == TN_FILE) {
546             num_extract++;
547             tree_getpath(node, cwd, sizeof(cwd));
548             fdbr.FileId = 0;
549             fdbr.JobId = node->JobId;
550             if (db_get_file_attributes_record(ua->jcr, ua->db, cwd, NULL, &fdbr)) {
551                int32_t LinkFI;
552                decode_stat(fdbr.LStat, &statp, &LinkFI); /* decode stat pkt */
553                if (S_ISREG(statp.st_mode) && statp.st_size > 0) {
554                   total_bytes += statp.st_size;
555                }
556             }
557          /* Directory, count only */
558          } else if (node->extract || node->extract_dir) {
559             num_extract++;
560          }
561       }
562    }
563    bsendmsg(ua, "%d total files; %d marked to be restored; %s bytes.\n", 
564             total, num_extract, edit_uint64_with_commas(total_bytes, ec1));
565    return 1;
566 }
567
568
569
570 static int helpcmd(UAContext *ua, TREE_CTX *tree) 
571 {
572    unsigned int i;
573
574 /* usage(); */
575    bsendmsg(ua, _("  Command    Description\n  =======    ===========\n"));
576    for (i=0; i<comsize; i++) {
577       bsendmsg(ua, _("  %-10s %s\n"), _(commands[i].key), _(commands[i].help));
578    }
579    bsendmsg(ua, "\n");
580    return 1;
581 }
582
583 /*
584  * Change directories.  Note, if the user specifies x: and it fails,
585  *   we assume it is a Win32 absolute cd rather than relative and
586  *   try a second time with /x: ...  Win32 kludge.
587  */
588 static int cdcmd(UAContext *ua, TREE_CTX *tree) 
589 {
590    TREE_NODE *node;
591    char cwd[2000];
592
593    if (ua->argc != 2) {
594       return 1;
595    }
596    node = tree_cwd(ua->argk[1], tree->root, tree->node);
597    if (!node) {
598       /* Try once more if Win32 drive -- make absolute */
599       if (ua->argk[1][1] == ':') {  /* win32 drive */
600          bstrncpy(cwd, "/", sizeof(cwd));
601          bstrncat(cwd, ua->argk[1], sizeof(cwd));
602          node = tree_cwd(cwd, tree->root, tree->node);
603       }
604       if (!node) {
605          bsendmsg(ua, _("Invalid path given.\n"));
606       } else {
607          tree->node = node;
608       }
609    } else {
610       tree->node = node;
611    }
612    tree_getpath(tree->node, cwd, sizeof(cwd));
613    bsendmsg(ua, _("cwd is: %s\n"), cwd);
614    return 1;
615 }
616
617 static int pwdcmd(UAContext *ua, TREE_CTX *tree) 
618 {
619    char cwd[2000];
620    tree_getpath(tree->node, cwd, sizeof(cwd));
621    bsendmsg(ua, _("cwd is: %s\n"), cwd);
622    return 1;
623 }
624
625
626 static int unmarkcmd(UAContext *ua, TREE_CTX *tree)
627 {
628    TREE_NODE *node;
629    int count = 0;
630
631    if (ua->argc < 2 || !tree_node_has_child(tree->node)) {     
632       bsendmsg(ua, _("No files unmarked.\n"));
633       return 1;
634    }
635    for (int i=1; i < ua->argc; i++) {
636       foreach_child(node, tree->node) {
637          if (fnmatch(ua->argk[i], node->fname, 0) == 0) {
638             count += set_extract(ua, node, tree, false);
639          }
640       }
641    }
642    if (count == 0) {
643       bsendmsg(ua, _("No files unmarked.\n"));
644    } else {
645       bsendmsg(ua, _("%d file%s unmarked.\n"), count, count==0?"":"s");
646    }
647    return 1;
648 }
649
650 static int unmarkdircmd(UAContext *ua, TREE_CTX *tree)
651 {
652    TREE_NODE *node;
653    int count = 0;
654
655    if (ua->argc < 2 || !tree_node_has_child(tree->node)) {
656       bsendmsg(ua, _("No directories unmarked.\n"));
657       return 1;
658    }
659
660    for (int i=1; i < ua->argc; i++) {
661       foreach_child(node, tree->node) {
662          if (fnmatch(ua->argk[i], node->fname, 0) == 0) {
663             if (node->type == TN_DIR || node->type == TN_DIR_NLS) {
664                node->extract_dir = false;
665                count++;
666             }
667          }
668       }
669    }
670
671    if (count == 0) {
672       bsendmsg(ua, _("No directories unmarked.\n"));
673    } else {
674       bsendmsg(ua, _("%d director%s unmarked.\n"), count, count==1?"y":"ies");
675    }
676    return 1;
677 }
678
679
680 static int donecmd(UAContext *ua, TREE_CTX *tree) 
681 {
682    return 0;
683 }
684
685 static int quitcmd(UAContext *ua, TREE_CTX *tree) 
686 {
687    ua->quit = true;
688    return 0;
689 }