]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/util.c
405d32e57c7d3c2ea8a60c2a063e2c5f1b13cc09
[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    double 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 = strtod(str, NULL);
71    if (errno != 0 || val < 0) {
72       return 0;
73    }
74    *value = (btime_t)(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 pool memory buffer pm
327  */
328 void pm_strcat(POOLMEM **pm, char *str)
329 {
330    int pmlen = strlen(*pm);
331    int len = strlen(str) + 1;
332
333    *pm = check_pool_memory_size(*pm, pmlen + len);
334    memcpy(*pm+pmlen, str, len);
335 }
336
337
338 /*
339  * Copy a string (str) into a pool memory buffer pm
340  */
341 void pm_strcpy(POOLMEM **pm, char *str)
342 {
343    int len = strlen(str) + 1;
344
345    *pm = check_pool_memory_size(*pm, len);
346    memcpy(*pm, str, len);
347 }
348
349
350 /*
351  * Convert a JobStatus code into a human readable form
352  */
353 void jobstatus_to_ascii(int JobStatus, char *msg, int maxlen)
354 {
355    char *termstat, jstat[2];
356
357    switch (JobStatus) {
358       case JS_Terminated:
359          termstat = _("OK");
360          break;
361      case JS_FatalError:
362      case JS_ErrorTerminated:
363          termstat = _("Error");
364          break;
365      case JS_Error:
366          termstat = _("Non-fatal error");
367          break;
368      case JS_Cancelled:
369          termstat = _("Cancelled");
370          break;
371      case JS_Differences:
372          termstat = _("Verify differences");
373          break;
374      default:
375          jstat[0] = last_job.JobStatus;
376          jstat[1] = 0;
377          termstat = jstat;
378          break;
379    }
380    strncpy(msg, termstat, maxlen);
381    msg[maxlen-1] = 0;
382 }
383
384 /*
385  * Convert Job Termination Status into a string
386  */
387 char *job_status_to_str(int stat) 
388 {
389    char *str;
390
391    switch (stat) {
392    case JS_Terminated:
393       str = _("OK");
394       break;
395    case JS_ErrorTerminated:
396    case JS_Error:
397       str = _("Error");
398       break;
399    case JS_FatalError:
400       str = _("Fatal Error");
401       break;
402    case JS_Cancelled:
403       str = _("Cancelled");
404       break;
405    case JS_Differences:
406       str = _("Differences");
407       break;
408    default:
409       str = _("Unknown term code");
410       break;
411    }
412    return str;
413 }
414
415
416 /*
417  * Convert Job Type into a string
418  */
419 char *job_type_to_str(int type) 
420 {
421    char *str;
422
423    switch (type) {
424    case JT_BACKUP:
425       str = _("Backup");
426       break;
427    case JT_VERIFY:
428       str = _("Verify");
429       break;
430    case JT_RESTORE:
431       str = _("Restore");
432       break;
433    case JT_ADMIN:
434       str = _("Admin");
435    default:
436       str = _("Unknown Type");
437       break;
438    }
439    return str;
440 }
441
442 /*
443  * Convert Job Level into a string
444  */
445 char *job_level_to_str(int level) 
446 {
447    char *str;
448
449    switch (level) {
450    case L_FULL:
451       str = _("Full");
452       break;
453    case L_INCREMENTAL:
454       str = _("Incremental");
455       break;
456    case L_DIFFERENTIAL:
457       str = _("Differential");
458       break;
459    case L_LEVEL:
460       str = _("Level");
461       break;
462    case L_SINCE:
463       str = _("Since");
464       break;
465    case L_VERIFY_CATALOG:
466       str = _("Verify Catalog");
467       break;
468    case L_VERIFY_INIT:
469       str = _("Verify Init Catalog");
470       break;
471    case L_VERIFY_VOLUME_TO_CATALOG:
472       str = _("Verify Volume to Catalog");
473       break;
474    case L_VERIFY_DATA:
475       str = _("Verify Data");
476       break;
477    default:
478       str = _("Unknown Job Level");
479       break;
480    }
481    return str;
482 }
483
484
485 /***********************************************************************
486  * Encode the mode bits into a 10 character string like LS does
487  ***********************************************************************/
488
489 char *encode_mode(mode_t mode, char *buf)
490 {
491   char *cp = buf;  
492
493   *cp++ = S_ISDIR(mode) ? 'd' : S_ISBLK(mode) ? 'b' : S_ISCHR(mode) ? 'c' :
494           S_ISLNK(mode) ? 'l' : '-';
495   *cp++ = mode & S_IRUSR ? 'r' : '-';
496   *cp++ = mode & S_IWUSR ? 'w' : '-';
497   *cp++ = (mode & S_ISUID
498                ? (mode & S_IXUSR ? 's' : 'S')
499                : (mode & S_IXUSR ? 'x' : '-'));
500   *cp++ = mode & S_IRGRP ? 'r' : '-';
501   *cp++ = mode & S_IWGRP ? 'w' : '-';
502   *cp++ = (mode & S_ISGID
503                ? (mode & S_IXGRP ? 's' : 'S')
504                : (mode & S_IXGRP ? 'x' : '-'));
505   *cp++ = mode & S_IROTH ? 'r' : '-';
506   *cp++ = mode & S_IWOTH ? 'w' : '-';
507   *cp++ = (mode & S_ISVTX
508                ? (mode & S_IXOTH ? 't' : 'T')
509                : (mode & S_IXOTH ? 'x' : '-'));
510   *cp = '\0';
511   return cp;
512 }
513
514 #ifdef WORKING
515 extern char *getuser(uid_t uid);
516 extern char *getgroup(gid_t gid);
517
518 void print_ls_output(char *fname, char *lname, int type, struct stat *statp)
519 {
520    char buf[1000]; 
521    char *p, *f;
522    int n;
523
524    p = encode_mode(statp->st_mode, buf);
525    n = sprintf(p, "  %2d ", (uint32_t)statp->st_nlink);
526    p += n;
527    n = sprintf(p, "%-8.8s %-8.8s", getuser(statp->st_uid), getgroup(statp->st_gid));
528    p += n;
529    n = sprintf(p, "%8ld  ", statp->st_size);
530    p += n;
531    p = encode_time(statp->st_ctime, p);
532    *p++ = ' ';
533    *p++ = ' ';
534    for (f=fname; *f; )
535       *p++ = *f++;
536    if (type == FT_LNK) {
537       *p++ = ' ';
538       *p++ = '-';
539       *p++ = '>';
540       *p++ = ' ';
541       /* Copy link name */
542       for (f=lname; *f; )
543          *p++ = *f++;
544    }
545    *p++ = '\n';
546    *p = 0;
547    fputs(buf, stdout);
548 }
549 #endif
550
551 int do_shell_expansion(char *name)
552 {
553 /*  ****FIXME***** this should work for Win32 too */
554 #define UNIX
555 #ifdef UNIX
556 #ifndef PATH_MAX
557 #define PATH_MAX 512
558 #endif
559
560    int pid, wpid, stat;
561    int waitstatus;
562    char *shellcmd;
563    void (*istat)(int), (*qstat)(int);
564    int i;
565    char echout[PATH_MAX + 256];
566    int pfd[2];
567    static char meta[] = "~\\$[]*?`'<>\"";
568    int found = FALSE;
569    int len;
570
571    /* Check if any meta characters are present */
572    len = strlen(meta);
573    for (i = 0; i < len; i++) {
574       if (strchr(name, meta[i])) {
575          found = TRUE;
576          break;
577       }
578    }
579    stat = 0;
580    if (found) {
581 #ifdef nt
582        /* If the filename appears to be a DOS filename,
583           convert all backward slashes \ to Unix path
584           separators / and insert a \ infront of spaces. */
585        len = strlen(name);
586        if (len >= 3 && name[1] == ':' && name[2] == '\\') {
587           for (i=2; i<len; i++)
588              if (name[i] == '\\')
589                 name[i] = '/';
590        }
591 #else
592        /* Pass string off to the shell for interpretation */
593        if (pipe(pfd) == -1)
594           return 0;
595        switch(pid = fork()) {
596        case -1:
597           break;
598
599        case 0:                            /* child */
600           /* look for shell */
601           if ((shellcmd = getenv("SHELL")) == NULL)
602              shellcmd = "/bin/sh";
603           close(1); dup(pfd[1]);          /* attach pipes to stdin and stdout */
604           close(2); dup(pfd[1]);
605           for (i = 3; i < 32; i++)        /* close everything else */
606              close(i);
607           strcpy(echout, "echo ");        /* form echo command */
608           strcat(echout, name);
609           execl(shellcmd, shellcmd, "-c", echout, NULL); /* give to shell */
610           exit(127);                      /* shouldn't get here */
611
612        default:                           /* parent */
613           /* read output from child */
614           i = read(pfd[0], echout, sizeof echout);
615           echout[--i] = 0;                /* set end of string */
616           /* look for first word or first line. */
617           while (--i >= 0) {
618              if (echout[i] == ' ' || echout[i] == '\n')
619                 echout[i] = 0;            /* keep only first one */
620           }
621           istat = signal(SIGINT, SIG_IGN);
622           qstat = signal(SIGQUIT, SIG_IGN);
623           /* wait for child to exit */
624           while ((wpid = wait(&waitstatus)) != pid && wpid != -1)
625              { ; }
626           signal(SIGINT, istat);
627           signal(SIGQUIT, qstat);
628           strcpy(name, echout);
629           stat = 1;
630           break;
631        }
632        close(pfd[0]);                     /* close pipe */
633        close(pfd[1]);
634 #endif /* nt */
635    }
636    return stat;
637
638 #endif /* UNIX */
639
640 #if  MSC | MSDOS | __WATCOMC__
641
642    char prefix[100], *env, *getenv();
643
644    /* Home directory reference? */
645    if (*name == '~' && (env=getenv("HOME"))) {
646       strcpy(prefix, env);            /* copy HOME directory name */
647       name++;                         /* skip over ~ in name */
648       strcat(prefix, name);
649       name--;                         /* get back to beginning */
650       strcpy(name, prefix);           /* move back into name */
651    }
652    return 1;
653 #endif
654
655 }
656
657 #define MAX_ARGV 100
658 static void build_argc_argv(char *cmd, int *bargc, char *bargv[], int max_arg);
659
660 /*
661  * Run an external program. Optionally wait a specified number
662  *   of seconds. Program killed if wait exceeded. Optionally
663  *   return the output from the program (normally a single line).
664  */
665 int run_program(char *prog, int wait, POOLMEM *results)
666 {
667    int stat = ETIME;
668    int chldstatus = 0;
669    pid_t pid1, pid2;
670    int pfd[2];
671    char *bargv[MAX_ARGV];
672    int bargc;
673
674    
675    build_argc_argv(prog, &bargc, bargv, MAX_ARGV);
676 #ifdef xxxxxxxxxx
677    printf("argc=%d\n", bargc);
678    int i;
679    for (i=0; i<bargc; i++) {
680       printf("argc=%d argv=%s\n", i, bargv[i]);
681    }
682 #endif
683
684    if (results && pipe(pfd) == -1) {
685       return errno;
686    }
687    /* Start worker process */
688    switch (pid1 = fork()) {
689    case -1:
690       break;
691
692    case 0:                            /* child */
693 //    printf("execl of %s\n", prog);
694       if (results) {
695          close(1); dup(pfd[1]);       /* attach pipes to stdin and stdout */
696          close(2); dup(pfd[1]);
697       }
698       execvp(bargv[0], bargv);
699       exit(errno);                   /* shouldn't get here */
700
701    default:                           /* parent */
702       /* start timer process */
703       if (wait > 0) {
704          switch (pid2=fork()) {
705          case -1:
706             break;
707          case 0:                         /* child 2 */
708             /* Time the worker process */  
709             sleep(wait);
710             if (kill(pid1, SIGTERM) == 0) { /* time expired kill it */
711                exit(0);
712             }
713             sleep(3);
714             kill(pid1, SIGKILL);
715             exit(0);
716          default:                        /* parent */
717             break;
718          }
719       }
720
721       /* Parent continues here */
722       int i;
723       if (results) {
724          i = read(pfd[0], results, sizeof_pool_memory(results) - 1);
725          if (--i < 0) {
726             i = 0;
727          }
728          results[i] = 0;                /* set end of string */
729       }
730       /* wait for worker child to exit */
731       for ( ;; ) {
732          pid_t wpid;
733          wpid = waitpid(pid1, &chldstatus, 0);         
734          if (wpid == pid1 || (errno != EINTR)) {
735             break;
736          }
737       }
738       if (WIFEXITED(chldstatus))
739          stat = WEXITSTATUS(chldstatus);
740
741       if (wait > 0) {
742          kill(pid2, SIGKILL);           /* kill off timer process */
743          waitpid(pid2, &chldstatus, 0); /* reap timer process */
744       }
745       if (results) { 
746          close(pfd[0]);              /* close pipe */
747          close(pfd[1]);
748       }
749       break;
750    }
751    return stat;
752 }
753
754 /*
755  * Build argc and argv from a string
756  */
757 static void build_argc_argv(char *cmd, int *bargc, char *bargv[], int max_argv)
758 {
759    int i, quote;
760    char *p, *q;
761    int argc = 0;
762
763    argc = 0;
764    for (i=0; i<max_argv; i++)
765       bargv[i] = NULL;
766
767    p = cmd;
768    quote = 0;
769    while  (*p && (*p == ' ' || *p == '\t'))
770       p++;
771    if (*p == '\"') {
772       quote = 1;
773       p++;
774    }
775    if (*p) {
776       while (*p && argc < MAX_ARGV) {
777          q = p;
778          if (quote) {
779             while (*q && *q != '\"')
780             q++;
781             quote = 0;
782          } else {
783             while (*q && *q != ' ')
784             q++;
785          }
786          if (*q)
787             *(q++) = '\0';
788          bargv[argc++] = p;
789          p = q;
790          while (*p && (*p == ' ' || *p == '\t'))
791             p++;
792          if (*p == '\"') {
793             quote = 1;
794             p++;
795          }
796       }
797    }
798    *bargc = argc;
799 }