]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/util.c
Autochanger cleanups
[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  * Encode the mode bits into a 10 character string like LS does
381  ***********************************************************************/
382
383 char *encode_mode(mode_t mode, char *buf)
384 {
385   char *cp = buf;  
386
387   *cp++ = S_ISDIR(mode) ? 'd' : S_ISBLK(mode) ? 'b' : S_ISCHR(mode) ? 'c' :
388           S_ISLNK(mode) ? 'l' : '-';
389   *cp++ = mode & S_IRUSR ? 'r' : '-';
390   *cp++ = mode & S_IWUSR ? 'w' : '-';
391   *cp++ = (mode & S_ISUID
392                ? (mode & S_IXUSR ? 's' : 'S')
393                : (mode & S_IXUSR ? 'x' : '-'));
394   *cp++ = mode & S_IRGRP ? 'r' : '-';
395   *cp++ = mode & S_IWGRP ? 'w' : '-';
396   *cp++ = (mode & S_ISGID
397                ? (mode & S_IXGRP ? 's' : 'S')
398                : (mode & S_IXGRP ? 'x' : '-'));
399   *cp++ = mode & S_IROTH ? 'r' : '-';
400   *cp++ = mode & S_IWOTH ? 'w' : '-';
401   *cp++ = (mode & S_ISVTX
402                ? (mode & S_IXOTH ? 't' : 'T')
403                : (mode & S_IXOTH ? 'x' : '-'));
404   *cp = '\0';
405   return cp;
406 }
407
408 #ifdef WORKING
409 extern char *getuser(uid_t uid);
410 extern char *getgroup(gid_t gid);
411
412 void print_ls_output(char *fname, char *lname, int type, struct stat *statp)
413 {
414    char buf[1000]; 
415    char *p, *f;
416    int n;
417
418    p = encode_mode(statp->st_mode, buf);
419    n = sprintf(p, "  %2d ", (uint32_t)statp->st_nlink);
420    p += n;
421    n = sprintf(p, "%-8.8s %-8.8s", getuser(statp->st_uid), getgroup(statp->st_gid));
422    p += n;
423    n = sprintf(p, "%8ld  ", statp->st_size);
424    p += n;
425    p = encode_time(statp->st_ctime, p);
426    *p++ = ' ';
427    *p++ = ' ';
428    for (f=fname; *f; )
429       *p++ = *f++;
430    if (type == FT_LNK) {
431       *p++ = ' ';
432       *p++ = '-';
433       *p++ = '>';
434       *p++ = ' ';
435       /* Copy link name */
436       for (f=lname; *f; )
437          *p++ = *f++;
438    }
439    *p++ = '\n';
440    *p = 0;
441    fputs(buf, stdout);
442 }
443 #endif
444
445 int do_shell_expansion(char *name)
446 {
447 /*  ****FIXME***** this should work for Win32 too */
448 #define UNIX
449 #ifdef UNIX
450 #ifndef PATH_MAX
451 #define PATH_MAX 512
452 #endif
453
454    int pid, wpid, stat;
455    int waitstatus;
456    char *shellcmd;
457    void (*istat)(int), (*qstat)(int);
458    int i;
459    char echout[PATH_MAX + 256];
460    int pfd[2];
461    static char meta[] = "~\\$[]*?`'<>\"";
462    int found = FALSE;
463    int len;
464
465    /* Check if any meta characters are present */
466    len = strlen(meta);
467    for (i = 0; i < len; i++) {
468       if (strchr(name, meta[i])) {
469          found = TRUE;
470          break;
471       }
472    }
473    stat = 0;
474    if (found) {
475 #ifdef nt
476        /* If the filename appears to be a DOS filename,
477           convert all backward slashes \ to Unix path
478           separators / and insert a \ infront of spaces. */
479        len = strlen(name);
480        if (len >= 3 && name[1] == ':' && name[2] == '\\') {
481           for (i=2; i<len; i++)
482              if (name[i] == '\\')
483                 name[i] = '/';
484        }
485 #else
486        /* Pass string off to the shell for interpretation */
487        if (pipe(pfd) == -1)
488           return 0;
489        switch(pid = fork()) {
490        case -1:
491           break;
492
493        case 0:                            /* child */
494           /* look for shell */
495           if ((shellcmd = getenv("SHELL")) == NULL)
496              shellcmd = "/bin/sh";
497           close(1); dup(pfd[1]);          /* attach pipes to stdin and stdout */
498           close(2); dup(pfd[1]);
499           for (i = 3; i < 32; i++)        /* close everything else */
500              close(i);
501           strcpy(echout, "echo ");        /* form echo command */
502           strcat(echout, name);
503           execl(shellcmd, shellcmd, "-c", echout, NULL); /* give to shell */
504           exit(127);                      /* shouldn't get here */
505
506        default:                           /* parent */
507           /* read output from child */
508           i = read(pfd[0], echout, sizeof echout);
509           echout[--i] = 0;                /* set end of string */
510           /* look for first word or first line. */
511           while (--i >= 0) {
512              if (echout[i] == ' ' || echout[i] == '\n')
513                 echout[i] = 0;            /* keep only first one */
514           }
515           istat = signal(SIGINT, SIG_IGN);
516           qstat = signal(SIGQUIT, SIG_IGN);
517           /* wait for child to exit */
518           while ((wpid = wait(&waitstatus)) != pid && wpid != -1)
519              { ; }
520           signal(SIGINT, istat);
521           signal(SIGQUIT, qstat);
522           strcpy(name, echout);
523           stat = 1;
524           break;
525        }
526        close(pfd[0]);                     /* close pipe */
527        close(pfd[1]);
528 #endif /* nt */
529    }
530    return stat;
531
532 #endif /* UNIX */
533
534 #if  MSC | MSDOS | __WATCOMC__
535
536    char prefix[100], *env, *getenv();
537
538    /* Home directory reference? */
539    if (*name == '~' && (env=getenv("HOME"))) {
540       strcpy(prefix, env);            /* copy HOME directory name */
541       name++;                         /* skip over ~ in name */
542       strcat(prefix, name);
543       name--;                         /* get back to beginning */
544       strcpy(name, prefix);           /* move back into name */
545    }
546    return 1;
547 #endif
548
549 }
550
551 #define MAX_ARGV 100
552 static char *bargv[MAX_ARGV];
553 static int bargc;
554 static void build_argc_argv(char *cmd);
555
556 int run_program(char *prog, int wait, POOLMEM *results)
557 {
558    int stat = ETIME;
559    int chldstatus = 0;
560    pid_t pid1, pid2;
561    int pfd[2];
562
563    
564    build_argc_argv(prog);
565 #ifdef xxxxxxxxxxx
566    printf("argc=%d\n", bargc);
567    int i;
568    for (i=0; i<bargc; i++) {
569       printf("argc=%d argv=%s\n", i, bargv[i]);
570    }
571 #endif
572
573    if (results && pipe(pfd) == -1) {
574       return errno;
575    }
576    /* Start worker process */
577    switch (pid1 = fork()) {
578    case -1:
579       break;
580
581    case 0:                            /* child */
582 //    printf("execl of %s\n", prog);
583       if (results) {
584          close(1); dup(pfd[1]);       /* attach pipes to stdin and stdout */
585          close(2); dup(pfd[1]);
586       }
587       execvp(bargv[0], bargv);
588       exit(errno);                   /* shouldn't get here */
589
590    default:                           /* parent */
591       /* start timer process */
592       switch (pid2=fork()) {
593       case -1:
594          break;
595       case 0:                         /* child 2 */
596          /* Time the worker process */  
597          sleep(wait);
598          if (kill(pid1, SIGTERM) == 0) { /* time expired kill it */
599             exit(0);
600          }
601          sleep(3);
602          kill(pid1, SIGKILL);
603          exit(0);
604       default:                        /* parent */
605          int i;
606          if (results) {
607             i = read(pfd[0], results, sizeof_pool_memory(results) - 1);
608             if (--i < 0) {
609                i = 0;
610             }
611             results[i] = 0;                /* set end of string */
612          }
613          /* wait for worker child to exit */
614          for ( ;; ) {
615             pid_t wpid;
616             wpid = waitpid(pid1, &chldstatus, 0);         
617             if (wpid == pid1 || (errno != EINTR)) {
618                break;
619             }
620          }
621          if (WIFEXITED(chldstatus))
622             stat = WEXITSTATUS(chldstatus);
623
624          kill(pid2, SIGKILL);           /* kill off timer process */
625          waitpid(pid2, &chldstatus, 0); /* reap timer process */
626          if (results) { 
627             close(pfd[0]);              /* close pipe */
628             close(pfd[1]);
629          }
630          break;
631       }
632       break;
633    }
634    return stat;
635 }
636
637 /*
638  * Build argc and argv from a string
639  */
640 static void build_argc_argv(char *cmd)
641 {
642    int i, quote;
643    char *p, *q;
644
645    bargc = 0;
646    for (i=0; i<MAX_ARGV; i++)
647       bargv[i] = NULL;
648
649    p = cmd;
650    quote = 0;
651    while  (*p && (*p == ' ' || *p == '\t'))
652       p++;
653    if (*p == '\"') {
654       quote = 1;
655       p++;
656    }
657    if (*p) {
658       while (*p && bargc < MAX_ARGV) {
659          q = p;
660          if (quote) {
661             while (*q && *q != '\"')
662             q++;
663             quote = 0;
664          } else {
665             while (*q && *q != ' ')
666             q++;
667          }
668          if (*q)
669             *(q++) = '\0';
670          bargv[bargc++] = p;
671          p = q;
672          while (*p && (*p == ' ' || *p == '\t'))
673             p++;
674          if (*p == '\"') {
675             quote = 1;
676             p++;
677          }
678       }
679    }
680 }