]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/util.c
restore cmd + misc -- see kes04Aug02
[bacula/bacula] / bacula / src / lib / util.c
1 /*
2  *   util.c  miscellaneous utility subroutines for Bacula
3  * 
4  *    Kern Sibbald, MM
5  *
6  *   Version $Id$
7  */
8
9 /*
10    Copyright (C) 2000, 2001, 2002 Kern Sibbald and John Walker
11
12    This program is free software; you can redistribute it and/or
13    modify it under the terms of the GNU General Public License as
14    published by the Free Software Foundation; either version 2 of
15    the License, or (at your option) any later version.
16
17    This program is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20    General Public License for more details.
21
22    You should have received a copy of the GNU General Public
23    License along with this program; if not, write to the Free
24    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
25    MA 02111-1307, USA.
26
27  */
28
29 #include "bacula.h"
30 #include "jcr.h"
31 #include "findlib/find.h"
32
33 /*
34  * Various Bacula Utility subroutines
35  *
36  */
37
38 /*
39  * Convert a string to btime_t (64 bit seconds)
40  * Returns 0: if error
41            1: if OK, and value stored in value
42  */
43 int string_to_btime(char *str, btime_t *value)
44 {
45    int i, ch, len;
46    btime_t val;
47    static int  mod[] = {'*', 's', 'n', 'h', 'd', 'w', 'm', 'q', 'y', 0};
48    static int mult[] = {1,    1,  60, 60*60, 60*60*24, 60*60*24*7, 60*60*24*30, 
49                   60*60*24*91, 60*60*24*365};
50
51    /* Look for modifier */
52    len = strlen(str);
53    ch = str[len - 1];
54    i = 0;
55    if (ISALPHA(ch)) {
56       if (ISUPPER(ch)) {
57          ch = tolower(ch);
58       }
59       while (mod[++i] != 0) {
60          if (ch == mod[i]) {
61             len--;
62             str[len] = 0; /* strip modifier */
63             break;
64          }
65       }
66    }
67    if (mod[i] == 0 || !is_a_number(str)) {
68       return 0;
69    }
70    val = (btime_t)strtod(str, NULL);
71    if (errno != 0 || val < 0) {
72       return 0;
73    }
74    *value = val * mult[i];
75    return 1;
76
77 }
78
79 char *edit_btime(btime_t val, char *buf)
80 {
81    char mybuf[30];
82    static int mult[] = {60*60*24*365, 60*60*24*30, 60*60*24, 60*60, 60};
83    static char *mod[]  = {"year",  "month",  "day", "hour", "min"};
84    int i;
85    uint32_t times;
86
87    *buf = 0;
88    for (i=0; i<5; i++) {
89       times = val / mult[i];
90       if (times > 0) {
91          val = val - (btime_t)times * mult[i];
92          sprintf(mybuf, "%d %s%s ", times, mod[i], times>1?"s":"");
93          strcat(buf, mybuf);
94       }
95    }
96    if (val == 0 && strlen(buf) == 0) {     
97       strcat(buf, "0 secs");
98    } else if (val != 0) {
99       sprintf(mybuf, "%d sec%s", (uint32_t)val, val>1?"s":"");
100       strcat(buf, mybuf);
101    }
102    return buf;
103 }
104
105 /*
106  * Check if specified string is a number or not.
107  *  Taken from SQLite, cool, thanks.
108  */
109 int is_a_number(const char *n)
110 {
111    int digit_seen = 0;
112
113    if( *n == '-' || *n == '+' ) {
114       n++;
115    }
116    while (ISDIGIT(*n)) {
117       digit_seen = 1;
118       n++;
119    }
120    if (digit_seen && *n == '.') {
121       n++;
122       while (ISDIGIT(*n)) { n++; }
123    }
124    if (digit_seen && (*n == 'e' || *n == 'E')
125        && (ISDIGIT(n[1]) || ((n[1]=='-' || n[1] == '+') && ISDIGIT(n[2])))) {
126       n += 2;                         /* skip e- or e+ or e digit */
127       while (ISDIGIT(*n)) { n++; }
128    }
129    return digit_seen && *n==0;
130 }
131
132
133 /*
134  * Edit an integer number with commas, the supplied buffer
135  * must be at least 27 bytes long.  The incoming number
136  * is always widened to 64 bits.
137  */
138 char *edit_uint64_with_commas(uint64_t val, char *buf)
139 {
140    sprintf(buf, "%" lld, val);
141    return add_commas(buf, buf);
142 }
143
144 /*
145  * Edit an integer number, the supplied buffer
146  * must be at least 27 bytes long.  The incoming number
147  * is always widened to 64 bits.
148  */
149 char *edit_uint64(uint64_t val, char *buf)
150 {
151    sprintf(buf, "%" lld, val);
152    return buf;
153 }
154
155
156 /*
157  * Add commas to a string, which is presumably
158  * a number.  
159  */
160 char *add_commas(char *val, char *buf)
161 {
162    int len, nc;
163    char *p, *q;
164    int i;
165
166    if (val != buf) {
167       strcpy(buf, val);
168    }
169    len = strlen(buf);
170    if (len < 1) {
171       len = 1;
172    }
173    nc = (len - 1) / 3;
174    p = buf+len;
175    q = p + nc;
176    *q-- = *p--;
177    for ( ; nc; nc--) {
178       for (i=0; i < 3; i++) {
179           *q-- = *p--;
180       }
181       *q-- = ',';
182    }   
183    return buf;
184 }
185
186
187 /* Convert a string in place to lower case */
188 void lcase(char *str)
189 {
190    while (*str) {
191       if (ISUPPER(*str))
192          *str = tolower((int)(*str));
193        str++;
194    }
195 }
196
197 /* Convert spaces to non-space character. 
198  * This makes scanf of fields containing spaces easier.
199  */
200 void
201 bash_spaces(char *str)
202 {
203    while (*str) {
204       if (*str == ' ')
205          *str = 0x1;
206       str++;
207    }
208 }
209
210 /* Convert non-space characters (0x1) back into spaces */
211 void
212 unbash_spaces(char *str)
213 {
214    while (*str) {
215      if (*str == 0x1)
216         *str = ' ';
217      str++;
218    }
219 }
220
221 /* Strip any trailing junk from the command */
222 void strip_trailing_junk(char *cmd)
223 {
224    char *p;
225    p = cmd + strlen(cmd) - 1;
226
227    /* strip trailing junk from command */
228    while ((p >= cmd) && (*p == '\n' || *p == '\r' || *p == ' '))
229       *p-- = 0;
230 }
231
232 /* Strip any trailing slashes from a directory path */
233 void strip_trailing_slashes(char *dir)
234 {
235    char *p;
236    p = dir + strlen(dir) - 1;
237
238    /* strip trailing slashes */
239    while ((p >= dir) && (*p == '/'))
240       *p-- = 0;
241 }
242
243 /*
244  * Skip spaces
245  *  Returns: 0 on failure (EOF)             
246  *           1 on success
247  *           new address in passed parameter 
248  */
249 int skip_spaces(char **msg)
250 {
251    char *p = *msg;
252    if (!p) {
253       return 0;
254    }
255    while (*p && *p == ' ') {
256       p++;
257    }
258    *msg = p;
259    return *p ? 1 : 0;
260 }
261
262 /*
263  * Skip nonspaces
264  *  Returns: 0 on failure (EOF)             
265  *           1 on success
266  *           new address in passed parameter 
267  */
268 int skip_nonspaces(char **msg)
269 {
270    char *p = *msg;
271
272    if (!p) {
273       return 0;
274    }
275    while (*p && *p != ' ') {
276       p++;
277    }
278    *msg = p;
279    return *p ? 1 : 0;
280 }
281
282 /* folded search for string - case insensitive */
283 int
284 fstrsch(char *a, char *b)   /* folded case search */
285 {
286    register char *s1,*s2;
287    register char c1, c2;
288
289    s1=a;
290    s2=b;
291    while (*s1) {                      /* do it the fast way */
292       if ((*s1++ | 0x20) != (*s2++ | 0x20))
293          return 0;                    /* failed */
294    }
295    while (*a) {                       /* do it over the correct slow way */
296       if (ISUPPER(c1 = *a)) {
297          c1 = tolower((int)c1);
298       }
299       if (ISUPPER(c2 = *b)) {
300          c2 = tolower((int)c2);
301       }
302       if (c1 != c2) {
303          return 0;
304       }
305       a++;
306       b++;
307    }
308    return 1;
309 }
310
311
312 char *encode_time(time_t time, char *buf)
313 {
314    struct tm tm;
315    int n;
316
317    if (localtime_r(&time, &tm)) {
318       n = sprintf(buf, "%04d-%02d-%02d %02d:%02d:%02d",
319                    tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
320                    tm.tm_hour, tm.tm_min, tm.tm_sec);
321    }
322    return buf+n;
323 }
324
325 /*
326  * Concatenate a string (str) onto a poolmem message (msg)
327  *  return new message pointer. The base of the pool memory
328  *  is base.
329  */
330 void add_str_to_pool_mem(POOLMEM **base, char **msg, char *str)
331 {
332    int len = strlen(str) + 1;
333    char *b, *m;
334
335    b = *base;
336    *base = check_pool_memory_size(*base, len);
337    m = *base - b + *msg;
338    while (*str) {
339       *m++ = *str++;
340    }
341    *msg = m;
342 }
343
344
345 /*
346  * Convert a JobStatus code into a human readable form
347  */
348 void jobstatus_to_ascii(int JobStatus, char *msg, int maxlen)
349 {
350    char *termstat, jstat[2];
351
352    switch (JobStatus) {
353       case JS_Terminated:
354          termstat = _("OK");
355          break;
356      case JS_FatalError:
357      case JS_ErrorTerminated:
358          termstat = _("Error");
359          break;
360      case JS_Error:
361          termstat = _("Non-fatal error");
362          break;
363      case JS_Cancelled:
364          termstat = _("Cancelled");
365          break;
366      case JS_Differences:
367          termstat = _("Verify differences");
368          break;
369      default:
370          jstat[0] = last_job.JobStatus;
371          jstat[1] = 0;
372          termstat = jstat;
373          break;
374    }
375    strncpy(msg, termstat, maxlen);
376    msg[maxlen-1] = 0;
377 }
378
379 /*
380  * Convert Job Termination Status into a string
381  */
382 char *job_status_to_str(int stat) 
383 {
384    char *str;
385
386    switch (stat) {
387    case JS_Terminated:
388       str = "OK";
389       break;
390    case JS_ErrorTerminated:
391    case JS_Error:
392       str = "Error";
393       break;
394    case JS_FatalError:
395       str = "Fatal Error";
396       break;
397    case JS_Cancelled:
398       str = "Cancelled";
399       break;
400    case JS_Differences:
401       str = "Differences";
402       break;
403    default:
404       str = "Unknown term code";
405       break;
406    }
407    return str;
408 }
409
410
411 /*
412  * Convert Job Type into a string
413  */
414 char *job_type_to_str(int type) 
415 {
416    char *str;
417
418    switch (type) {
419    case JT_BACKUP:
420       str = "Backup";
421       break;
422    case JT_VERIFY:
423       str = "Verify";
424       break;
425    case JT_RESTORE:
426       str = "Restore";
427       break;
428    case JT_ADMIN:
429       str = "Admin";
430    default:
431       str = "Unknown Job Type";
432       break;
433    }
434    return str;
435 }
436
437 /*
438  * Convert Job Level into a string
439  */
440 char *job_level_to_str(int level) 
441 {
442    char *str;
443
444    switch (level) {
445    case L_FULL:
446       str = "full";
447       break;
448    case L_INCREMENTAL:
449       str = "incremental";
450       break;
451    case L_DIFFERENTIAL:
452       str = "differential";
453       break;
454    case L_LEVEL:
455       str = "level";
456       break;
457    case L_SINCE:
458       str = "since";
459       break;
460    case L_VERIFY_CATALOG:
461       str = "verify catalog";
462       break;
463    case L_VERIFY_INIT:
464       str = "verify init";
465       break;
466    case L_VERIFY_VOLUME_TO_CATALOG:
467       str = "verify volume to catalog";
468       break;
469    case L_VERIFY_DATA:
470       str = "verify data";
471       break;
472    default:
473       str = "Unknown Job level";
474       break;
475    }
476    return str;
477 }
478
479
480 /***********************************************************************
481  * Encode the mode bits into a 10 character string like LS does
482  ***********************************************************************/
483
484 char *encode_mode(mode_t mode, char *buf)
485 {
486   char *cp = buf;  
487
488   *cp++ = S_ISDIR(mode) ? 'd' : S_ISBLK(mode) ? 'b' : S_ISCHR(mode) ? 'c' :
489           S_ISLNK(mode) ? 'l' : '-';
490   *cp++ = mode & S_IRUSR ? 'r' : '-';
491   *cp++ = mode & S_IWUSR ? 'w' : '-';
492   *cp++ = (mode & S_ISUID
493                ? (mode & S_IXUSR ? 's' : 'S')
494                : (mode & S_IXUSR ? 'x' : '-'));
495   *cp++ = mode & S_IRGRP ? 'r' : '-';
496   *cp++ = mode & S_IWGRP ? 'w' : '-';
497   *cp++ = (mode & S_ISGID
498                ? (mode & S_IXGRP ? 's' : 'S')
499                : (mode & S_IXGRP ? 'x' : '-'));
500   *cp++ = mode & S_IROTH ? 'r' : '-';
501   *cp++ = mode & S_IWOTH ? 'w' : '-';
502   *cp++ = (mode & S_ISVTX
503                ? (mode & S_IXOTH ? 't' : 'T')
504                : (mode & S_IXOTH ? 'x' : '-'));
505   *cp = '\0';
506   return cp;
507 }
508
509 #ifdef WORKING
510 extern char *getuser(uid_t uid);
511 extern char *getgroup(gid_t gid);
512
513 void print_ls_output(char *fname, char *lname, int type, struct stat *statp)
514 {
515    char buf[1000]; 
516    char *p, *f;
517    int n;
518
519    p = encode_mode(statp->st_mode, buf);
520    n = sprintf(p, "  %2d ", (uint32_t)statp->st_nlink);
521    p += n;
522    n = sprintf(p, "%-8.8s %-8.8s", getuser(statp->st_uid), getgroup(statp->st_gid));
523    p += n;
524    n = sprintf(p, "%8ld  ", statp->st_size);
525    p += n;
526    p = encode_time(statp->st_ctime, p);
527    *p++ = ' ';
528    *p++ = ' ';
529    for (f=fname; *f; )
530       *p++ = *f++;
531    if (type == FT_LNK) {
532       *p++ = ' ';
533       *p++ = '-';
534       *p++ = '>';
535       *p++ = ' ';
536       /* Copy link name */
537       for (f=lname; *f; )
538          *p++ = *f++;
539    }
540    *p++ = '\n';
541    *p = 0;
542    fputs(buf, stdout);
543 }
544 #endif
545
546 int do_shell_expansion(char *name)
547 {
548 /*  ****FIXME***** this should work for Win32 too */
549 #define UNIX
550 #ifdef UNIX
551 #ifndef PATH_MAX
552 #define PATH_MAX 512
553 #endif
554
555    int pid, wpid, stat;
556    int waitstatus;
557    char *shellcmd;
558    void (*istat)(int), (*qstat)(int);
559    int i;
560    char echout[PATH_MAX + 256];
561    int pfd[2];
562    static char meta[] = "~\\$[]*?`'<>\"";
563    int found = FALSE;
564    int len;
565
566    /* Check if any meta characters are present */
567    len = strlen(meta);
568    for (i = 0; i < len; i++) {
569       if (strchr(name, meta[i])) {
570          found = TRUE;
571          break;
572       }
573    }
574    stat = 0;
575    if (found) {
576 #ifdef nt
577        /* If the filename appears to be a DOS filename,
578           convert all backward slashes \ to Unix path
579           separators / and insert a \ infront of spaces. */
580        len = strlen(name);
581        if (len >= 3 && name[1] == ':' && name[2] == '\\') {
582           for (i=2; i<len; i++)
583              if (name[i] == '\\')
584                 name[i] = '/';
585        }
586 #else
587        /* Pass string off to the shell for interpretation */
588        if (pipe(pfd) == -1)
589           return 0;
590        switch(pid = fork()) {
591        case -1:
592           break;
593
594        case 0:                            /* child */
595           /* look for shell */
596           if ((shellcmd = getenv("SHELL")) == NULL)
597              shellcmd = "/bin/sh";
598           close(1); dup(pfd[1]);          /* attach pipes to stdin and stdout */
599           close(2); dup(pfd[1]);
600           for (i = 3; i < 32; i++)        /* close everything else */
601              close(i);
602           strcpy(echout, "echo ");        /* form echo command */
603           strcat(echout, name);
604           execl(shellcmd, shellcmd, "-c", echout, NULL); /* give to shell */
605           exit(127);                      /* shouldn't get here */
606
607        default:                           /* parent */
608           /* read output from child */
609           i = read(pfd[0], echout, sizeof echout);
610           echout[--i] = 0;                /* set end of string */
611           /* look for first word or first line. */
612           while (--i >= 0) {
613              if (echout[i] == ' ' || echout[i] == '\n')
614                 echout[i] = 0;            /* keep only first one */
615           }
616           istat = signal(SIGINT, SIG_IGN);
617           qstat = signal(SIGQUIT, SIG_IGN);
618           /* wait for child to exit */
619           while ((wpid = wait(&waitstatus)) != pid && wpid != -1)
620              { ; }
621           signal(SIGINT, istat);
622           signal(SIGQUIT, qstat);
623           strcpy(name, echout);
624           stat = 1;
625           break;
626        }
627        close(pfd[0]);                     /* close pipe */
628        close(pfd[1]);
629 #endif /* nt */
630    }
631    return stat;
632
633 #endif /* UNIX */
634
635 #if  MSC | MSDOS | __WATCOMC__
636
637    char prefix[100], *env, *getenv();
638
639    /* Home directory reference? */
640    if (*name == '~' && (env=getenv("HOME"))) {
641       strcpy(prefix, env);            /* copy HOME directory name */
642       name++;                         /* skip over ~ in name */
643       strcat(prefix, name);
644       name--;                         /* get back to beginning */
645       strcpy(name, prefix);           /* move back into name */
646    }
647    return 1;
648 #endif
649
650 }
651
652 #define MAX_ARGV 100
653 static void build_argc_argv(char *cmd, int *bargc, char *bargv[], int max_arg);
654
655 /*
656  * Run an external program. Optionally wait a specified number
657  *   of seconds. Program killed if wait exceeded. Optionally
658  *   return the output from the program (normally a single line).
659  */
660 int run_program(char *prog, int wait, POOLMEM *results)
661 {
662    int stat = ETIME;
663    int chldstatus = 0;
664    pid_t pid1, pid2;
665    int pfd[2];
666    char *bargv[MAX_ARGV];
667    int bargc;
668
669    
670    build_argc_argv(prog, &bargc, bargv, MAX_ARGV);
671 #ifdef xxxxxxxxxx
672    printf("argc=%d\n", bargc);
673    int i;
674    for (i=0; i<bargc; i++) {
675       printf("argc=%d argv=%s\n", i, bargv[i]);
676    }
677 #endif
678
679    if (results && pipe(pfd) == -1) {
680       return errno;
681    }
682    /* Start worker process */
683    switch (pid1 = fork()) {
684    case -1:
685       break;
686
687    case 0:                            /* child */
688 //    printf("execl of %s\n", prog);
689       if (results) {
690          close(1); dup(pfd[1]);       /* attach pipes to stdin and stdout */
691          close(2); dup(pfd[1]);
692       }
693       execvp(bargv[0], bargv);
694       exit(errno);                   /* shouldn't get here */
695
696    default:                           /* parent */
697       /* start timer process */
698       if (wait > 0) {
699          switch (pid2=fork()) {
700          case -1:
701             break;
702          case 0:                         /* child 2 */
703             /* Time the worker process */  
704             sleep(wait);
705             if (kill(pid1, SIGTERM) == 0) { /* time expired kill it */
706                exit(0);
707             }
708             sleep(3);
709             kill(pid1, SIGKILL);
710             exit(0);
711          default:                        /* parent */
712             break;
713          }
714       }
715
716       /* Parent continues here */
717       int i;
718       if (results) {
719          i = read(pfd[0], results, sizeof_pool_memory(results) - 1);
720          if (--i < 0) {
721             i = 0;
722          }
723          results[i] = 0;                /* set end of string */
724       }
725       /* wait for worker child to exit */
726       for ( ;; ) {
727          pid_t wpid;
728          wpid = waitpid(pid1, &chldstatus, 0);         
729          if (wpid == pid1 || (errno != EINTR)) {
730             break;
731          }
732       }
733       if (WIFEXITED(chldstatus))
734          stat = WEXITSTATUS(chldstatus);
735
736       if (wait > 0) {
737          kill(pid2, SIGKILL);           /* kill off timer process */
738          waitpid(pid2, &chldstatus, 0); /* reap timer process */
739       }
740       if (results) { 
741          close(pfd[0]);              /* close pipe */
742          close(pfd[1]);
743       }
744       break;
745    }
746    return stat;
747 }
748
749 /*
750  * Build argc and argv from a string
751  */
752 static void build_argc_argv(char *cmd, int *bargc, char *bargv[], int max_argv)
753 {
754    int i, quote;
755    char *p, *q;
756    int argc = 0;
757
758    argc = 0;
759    for (i=0; i<max_argv; i++)
760       bargv[i] = NULL;
761
762    p = cmd;
763    quote = 0;
764    while  (*p && (*p == ' ' || *p == '\t'))
765       p++;
766    if (*p == '\"') {
767       quote = 1;
768       p++;
769    }
770    if (*p) {
771       while (*p && argc < MAX_ARGV) {
772          q = p;
773          if (quote) {
774             while (*q && *q != '\"')
775             q++;
776             quote = 0;
777          } else {
778             while (*q && *q != ' ')
779             q++;
780          }
781          if (*q)
782             *(q++) = '\0';
783          bargv[argc++] = p;
784          p = q;
785          while (*p && (*p == ' ' || *p == '\t'))
786             p++;
787          if (*p == '\"') {
788             quote = 1;
789             p++;
790          }
791       }
792    }
793    *bargc = argc;
794 }