]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/util.c
cc0da0539ca861ab415d6df97cf66d665d3fbc3e
[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 /* Return true of buffer has all zero bytes */
39 int is_buf_zero(char *buf, int len)
40 {
41    uint64_t *ip = (uint64_t *)buf;
42    char *p;
43    int i, len64, done, rem;
44
45    /* Optimize by checking uint64_t for zero */
46    len64 = len >> sizeof(uint64_t);
47    for (i=0; i < len64; i++) {
48       if (ip[i] != 0) {
49          return 0;
50       }
51    }
52    done = len64 << sizeof(uint64_t);  /* bytes already checked */
53    p = buf + done;
54    rem = len - done;
55    for (i = 0; i < rem; i++) {
56       if (p[i] != 0) {
57          return 0;
58       }
59    }
60    return 1;
61 }
62
63 /*
64  * Convert a string duration to utime_t (64 bit seconds)
65  * Returns 0: if error
66            1: if OK, and value stored in value
67  */
68 int duration_to_utime(char *str, utime_t *value)
69 {
70    int i, ch, len;
71    double val;
72    static int  mod[] = {'*', 's', 'n', 'h', 'd', 'w', 'm', 'q', 'y', 0};
73    static int mult[] = {1,    1,  60, 60*60, 60*60*24, 60*60*24*7, 60*60*24*30, 
74                   60*60*24*91, 60*60*24*365};
75
76    /* Look for modifier */
77    len = strlen(str);
78    ch = str[len - 1];
79    i = 0;
80    if (B_ISALPHA(ch)) {
81       if (B_ISUPPER(ch)) {
82          ch = tolower(ch);
83       }
84       while (mod[++i] != 0) {
85          if (ch == mod[i]) {
86             len--;
87             str[len] = 0; /* strip modifier */
88             break;
89          }
90       }
91    }
92    if (mod[i] == 0 || !is_a_number(str)) {
93       return 0;
94    }
95    val = strtod(str, NULL);
96    if (errno != 0 || val < 0) {
97       return 0;
98    }
99    *value = (utime_t)(val * mult[i]);
100    return 1;
101
102 }
103
104 /*
105  * Edit a utime "duration" into ASCII
106  */
107 char *edit_utime(utime_t val, char *buf)
108 {
109    char mybuf[30];
110    static int mult[] = {60*60*24*365, 60*60*24*30, 60*60*24, 60*60, 60};
111    static char *mod[]  = {"year",  "month",  "day", "hour", "min"};
112    int i;
113    uint32_t times;
114
115    *buf = 0;
116    for (i=0; i<5; i++) {
117       times = val / mult[i];
118       if (times > 0) {
119          val = val - (utime_t)times * mult[i];
120          sprintf(mybuf, "%d %s%s ", times, mod[i], times>1?"s":"");
121          strcat(buf, mybuf);
122       }
123    }
124    if (val == 0 && strlen(buf) == 0) {     
125       strcat(buf, "0 secs");
126    } else if (val != 0) {
127       sprintf(mybuf, "%d sec%s", (uint32_t)val, val>1?"s":"");
128       strcat(buf, mybuf);
129    }
130    return buf;
131 }
132
133 /*
134  * Convert a size size in bytes to uint64_t
135  * Returns 0: if error
136            1: if OK, and value stored in value
137  */
138 int size_to_uint64(char *str, int str_len, uint64_t *rtn_value)
139 {
140    int i, ch;
141    double value;
142    int mod[]  = {'*', 'k', 'm', 'g', 0}; /* first item * not used */
143    uint64_t mult[] = {1,             /* byte */
144                       1024,          /* kilobyte */
145                       1048576,       /* megabyte */
146                       1073741824};   /* gigabyte */
147
148 #ifdef we_have_a_compiler_that_works
149    int mod[]  = {'*', 'k', 'm', 'g', 't', 0};
150    uint64_t mult[] = {1,             /* byte */
151                       1024,          /* kilobyte */
152                       1048576,       /* megabyte */
153                       1073741824,    /* gigabyte */
154                       1099511627776};/* terabyte */
155 #endif
156
157    Dmsg0(400, "Enter sized to uint64\n");
158
159    /* Look for modifier */
160    ch = str[str_len - 1];
161    i = 0;
162    if (B_ISALPHA(ch)) {
163       if (B_ISUPPER(ch)) {
164          ch = tolower(ch);
165       }
166       while (mod[++i] != 0) {
167          if (ch == mod[i]) {
168             str_len--;
169             str[str_len] = 0; /* strip modifier */
170             break;
171          }
172       }
173    }
174    if (mod[i] == 0 || !is_a_number(str)) {
175       return 0;
176    }
177    Dmsg3(400, "size str=:%s: %f i=%d\n", str, strtod(str, NULL), i);
178
179    value = (uint64_t)strtod(str, NULL);
180    Dmsg1(400, "Int value = %d\n", (int)value);
181    if (errno != 0 || value < 0) {
182       return 0;
183    }
184    *rtn_value = (uint64_t)(value * mult[i]);
185    Dmsg2(400, "Full value = %f %" lld "\n", strtod(str, NULL) * mult[i],
186        value *mult[i]);
187    return 1;
188 }
189
190 /*
191  * Check if specified string is a number or not.
192  *  Taken from SQLite, cool, thanks.
193  */
194 int is_a_number(const char *n)
195 {
196    int digit_seen = 0;
197
198    if( *n == '-' || *n == '+' ) {
199       n++;
200    }
201    while (B_ISDIGIT(*n)) {
202       digit_seen = 1;
203       n++;
204    }
205    if (digit_seen && *n == '.') {
206       n++;
207       while (B_ISDIGIT(*n)) { n++; }
208    }
209    if (digit_seen && (*n == 'e' || *n == 'E')
210        && (B_ISDIGIT(n[1]) || ((n[1]=='-' || n[1] == '+') && B_ISDIGIT(n[2])))) {
211       n += 2;                         /* skip e- or e+ or e digit */
212       while (B_ISDIGIT(*n)) { n++; }
213    }
214    return digit_seen && *n==0;
215 }
216
217
218 /*
219  * Edit an integer number with commas, the supplied buffer
220  * must be at least 27 bytes long.  The incoming number
221  * is always widened to 64 bits.
222  */
223 char *edit_uint64_with_commas(uint64_t val, char *buf)
224 {
225    sprintf(buf, "%" lld, val);
226    return add_commas(buf, buf);
227 }
228
229 /*
230  * Edit an integer number, the supplied buffer
231  * must be at least 27 bytes long.  The incoming number
232  * is always widened to 64 bits.
233  */
234 char *edit_uint64(uint64_t val, char *buf)
235 {
236    sprintf(buf, "%" lld, val);
237    return buf;
238 }
239
240
241 /*
242  * Add commas to a string, which is presumably
243  * a number.  
244  */
245 char *add_commas(char *val, char *buf)
246 {
247    int len, nc;
248    char *p, *q;
249    int i;
250
251    if (val != buf) {
252       strcpy(buf, val);
253    }
254    len = strlen(buf);
255    if (len < 1) {
256       len = 1;
257    }
258    nc = (len - 1) / 3;
259    p = buf+len;
260    q = p + nc;
261    *q-- = *p--;
262    for ( ; nc; nc--) {
263       for (i=0; i < 3; i++) {
264           *q-- = *p--;
265       }
266       *q-- = ',';
267    }   
268    return buf;
269 }
270
271
272 /* Convert a string in place to lower case */
273 void lcase(char *str)
274 {
275    while (*str) {
276       if (B_ISUPPER(*str))
277          *str = tolower((int)(*str));
278        str++;
279    }
280 }
281
282 /* Convert spaces to non-space character. 
283  * This makes scanf of fields containing spaces easier.
284  */
285 void
286 bash_spaces(char *str)
287 {
288    while (*str) {
289       if (*str == ' ')
290          *str = 0x1;
291       str++;
292    }
293 }
294
295 /* Convert non-space characters (0x1) back into spaces */
296 void
297 unbash_spaces(char *str)
298 {
299    while (*str) {
300      if (*str == 0x1)
301         *str = ' ';
302      str++;
303    }
304 }
305
306 /* Strip any trailing junk from the command */
307 void strip_trailing_junk(char *cmd)
308 {
309    char *p;
310    p = cmd + strlen(cmd) - 1;
311
312    /* strip trailing junk from command */
313    while ((p >= cmd) && (*p == '\n' || *p == '\r' || *p == ' '))
314       *p-- = 0;
315 }
316
317 /* Strip any trailing slashes from a directory path */
318 void strip_trailing_slashes(char *dir)
319 {
320    char *p;
321    p = dir + strlen(dir) - 1;
322
323    /* strip trailing slashes */
324    while ((p >= dir) && (*p == '/'))
325       *p-- = 0;
326 }
327
328 /*
329  * Skip spaces
330  *  Returns: 0 on failure (EOF)             
331  *           1 on success
332  *           new address in passed parameter 
333  */
334 int skip_spaces(char **msg)
335 {
336    char *p = *msg;
337    if (!p) {
338       return 0;
339    }
340    while (*p && *p == ' ') {
341       p++;
342    }
343    *msg = p;
344    return *p ? 1 : 0;
345 }
346
347 /*
348  * Skip nonspaces
349  *  Returns: 0 on failure (EOF)             
350  *           1 on success
351  *           new address in passed parameter 
352  */
353 int skip_nonspaces(char **msg)
354 {
355    char *p = *msg;
356
357    if (!p) {
358       return 0;
359    }
360    while (*p && *p != ' ') {
361       p++;
362    }
363    *msg = p;
364    return *p ? 1 : 0;
365 }
366
367 /* folded search for string - case insensitive */
368 int
369 fstrsch(char *a, char *b)   /* folded case search */
370 {
371    register char *s1,*s2;
372    register char c1, c2;
373
374    s1=a;
375    s2=b;
376    while (*s1) {                      /* do it the fast way */
377       if ((*s1++ | 0x20) != (*s2++ | 0x20))
378          return 0;                    /* failed */
379    }
380    while (*a) {                       /* do it over the correct slow way */
381       if (B_ISUPPER(c1 = *a)) {
382          c1 = tolower((int)c1);
383       }
384       if (B_ISUPPER(c2 = *b)) {
385          c2 = tolower((int)c2);
386       }
387       if (c1 != c2) {
388          return 0;
389       }
390       a++;
391       b++;
392    }
393    return 1;
394 }
395
396
397 char *encode_time(time_t time, char *buf)
398 {
399    struct tm tm;
400    int n = 0;
401
402    if (localtime_r(&time, &tm)) {
403       n = sprintf(buf, "%04d-%02d-%02d %02d:%02d:%02d",
404                    tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
405                    tm.tm_hour, tm.tm_min, tm.tm_sec);
406    }
407    return buf+n;
408 }
409
410 /*
411  * Concatenate a string (str) onto a pool memory buffer pm
412  */
413 void pm_strcat(POOLMEM **pm, char *str)
414 {
415    int pmlen = strlen(*pm);
416    int len = strlen(str) + 1;
417
418    *pm = check_pool_memory_size(*pm, pmlen + len);
419    memcpy(*pm+pmlen, str, len);
420 }
421
422
423 /*
424  * Copy a string (str) into a pool memory buffer pm
425  */
426 void pm_strcpy(POOLMEM **pm, char *str)
427 {
428    int len = strlen(str) + 1;
429
430    *pm = check_pool_memory_size(*pm, len);
431    memcpy(*pm, str, len);
432 }
433
434
435 /*
436  * Convert a JobStatus code into a human readable form
437  */
438 void jobstatus_to_ascii(int JobStatus, char *msg, int maxlen)
439 {
440    char *termstat, jstat[2];
441
442    switch (JobStatus) {
443       case JS_Terminated:
444          termstat = _("OK");
445          break;
446      case JS_FatalError:
447      case JS_ErrorTerminated:
448          termstat = _("Error");
449          break;
450      case JS_Error:
451          termstat = _("Non-fatal error");
452          break;
453      case JS_Cancelled:
454          termstat = _("Cancelled");
455          break;
456      case JS_Differences:
457          termstat = _("Verify differences");
458          break;
459      default:
460          jstat[0] = last_job.JobStatus;
461          jstat[1] = 0;
462          termstat = jstat;
463          break;
464    }
465    bstrncpy(msg, termstat, maxlen);
466 }
467
468 /*
469  * Convert Job Termination Status into a string
470  */
471 char *job_status_to_str(int stat) 
472 {
473    char *str;
474
475    switch (stat) {
476    case JS_Terminated:
477       str = _("OK");
478       break;
479    case JS_ErrorTerminated:
480    case JS_Error:
481       str = _("Error");
482       break;
483    case JS_FatalError:
484       str = _("Fatal Error");
485       break;
486    case JS_Cancelled:
487       str = _("Cancelled");
488       break;
489    case JS_Differences:
490       str = _("Differences");
491       break;
492    default:
493       str = _("Unknown term code");
494       break;
495    }
496    return str;
497 }
498
499
500 /*
501  * Convert Job Type into a string
502  */
503 char *job_type_to_str(int type) 
504 {
505    char *str;
506
507    switch (type) {
508    case JT_BACKUP:
509       str = _("Backup");
510       break;
511    case JT_VERIFY:
512       str = _("Verify");
513       break;
514    case JT_RESTORE:
515       str = _("Restore");
516       break;
517    case JT_ADMIN:
518       str = _("Admin");
519       break;
520    default:
521       str = _("Unknown Type");
522       break;
523    }
524    return str;
525 }
526
527 /*
528  * Convert Job Level into a string
529  */
530 char *job_level_to_str(int level) 
531 {
532    char *str;
533
534    switch (level) {
535    case L_FULL:
536       str = _("Full");
537       break;
538    case L_INCREMENTAL:
539       str = _("Incremental");
540       break;
541    case L_DIFFERENTIAL:
542       str = _("Differential");
543       break;
544    case L_LEVEL:
545       str = _("Level");
546       break;
547    case L_SINCE:
548       str = _("Since");
549       break;
550    case L_VERIFY_CATALOG:
551       str = _("Verify Catalog");
552       break;
553    case L_VERIFY_INIT:
554       str = _("Verify Init Catalog");
555       break;
556    case L_VERIFY_VOLUME_TO_CATALOG:
557       str = _("Verify Volume to Catalog");
558       break;
559    case L_VERIFY_DATA:
560       str = _("Verify Data");
561       break;
562    default:
563       str = _("Unknown Job Level");
564       break;
565    }
566    return str;
567 }
568
569
570 /***********************************************************************
571  * Encode the mode bits into a 10 character string like LS does
572  ***********************************************************************/
573
574 char *encode_mode(mode_t mode, char *buf)
575 {
576   char *cp = buf;  
577
578   *cp++ = S_ISDIR(mode) ? 'd' : S_ISBLK(mode) ? 'b' : S_ISCHR(mode) ? 'c' :
579           S_ISLNK(mode) ? 'l' : '-';
580   *cp++ = mode & S_IRUSR ? 'r' : '-';
581   *cp++ = mode & S_IWUSR ? 'w' : '-';
582   *cp++ = (mode & S_ISUID
583                ? (mode & S_IXUSR ? 's' : 'S')
584                : (mode & S_IXUSR ? 'x' : '-'));
585   *cp++ = mode & S_IRGRP ? 'r' : '-';
586   *cp++ = mode & S_IWGRP ? 'w' : '-';
587   *cp++ = (mode & S_ISGID
588                ? (mode & S_IXGRP ? 's' : 'S')
589                : (mode & S_IXGRP ? 'x' : '-'));
590   *cp++ = mode & S_IROTH ? 'r' : '-';
591   *cp++ = mode & S_IWOTH ? 'w' : '-';
592   *cp++ = (mode & S_ISVTX
593                ? (mode & S_IXOTH ? 't' : 'T')
594                : (mode & S_IXOTH ? 'x' : '-'));
595   *cp = '\0';
596   return cp;
597 }
598
599
600 int do_shell_expansion(char *name)
601 {
602 /*  ****FIXME***** this should work for Win32 too */
603 #define UNIX
604 #ifdef UNIX
605 #ifndef PATH_MAX
606 #define PATH_MAX 512
607 #endif
608
609    int pid, wpid, stat;
610    int waitstatus;
611    char *shellcmd;
612    void (*istat)(int), (*qstat)(int);
613    int i;
614    char echout[PATH_MAX + 256];
615    int pfd[2];
616    static char meta[] = "~\\$[]*?`'<>\"";
617    int found = FALSE;
618    int len;
619
620    /* Check if any meta characters are present */
621    len = strlen(meta);
622    for (i = 0; i < len; i++) {
623       if (strchr(name, meta[i])) {
624          found = TRUE;
625          break;
626       }
627    }
628    stat = 0;
629    if (found) {
630 #ifdef nt
631        /* If the filename appears to be a DOS filename,
632           convert all backward slashes \ to Unix path
633           separators / and insert a \ infront of spaces. */
634        len = strlen(name);
635        if (len >= 3 && name[1] == ':' && name[2] == '\\') {
636           for (i=2; i<len; i++)
637              if (name[i] == '\\')
638                 name[i] = '/';
639        }
640 #else
641        /* Pass string off to the shell for interpretation */
642        if (pipe(pfd) == -1)
643           return 0;
644        switch(pid = fork()) {
645        case -1:
646           break;
647
648        case 0:                            /* child */
649           /* look for shell */
650           if ((shellcmd = getenv("SHELL")) == NULL)
651              shellcmd = "/bin/sh";
652           close(1); dup(pfd[1]);          /* attach pipes to stdin and stdout */
653           close(2); dup(pfd[1]);
654           for (i = 3; i < 32; i++)        /* close everything else */
655              close(i);
656           strcpy(echout, "echo ");        /* form echo command */
657           strcat(echout, name);
658           execl(shellcmd, shellcmd, "-c", echout, NULL); /* give to shell */
659           exit(127);                      /* shouldn't get here */
660
661        default:                           /* parent */
662           /* read output from child */
663           i = read(pfd[0], echout, sizeof echout);
664           echout[--i] = 0;                /* set end of string */
665           /* look for first word or first line. */
666           while (--i >= 0) {
667              if (echout[i] == ' ' || echout[i] == '\n')
668                 echout[i] = 0;            /* keep only first one */
669           }
670           istat = signal(SIGINT, SIG_IGN);
671           qstat = signal(SIGQUIT, SIG_IGN);
672           /* wait for child to exit */
673           while ((wpid = wait(&waitstatus)) != pid && wpid != -1)
674              { ; }
675           signal(SIGINT, istat);
676           signal(SIGQUIT, qstat);
677           strcpy(name, echout);
678           stat = 1;
679           break;
680        }
681        close(pfd[0]);                     /* close pipe */
682        close(pfd[1]);
683 #endif /* nt */
684    }
685    return stat;
686
687 #endif /* UNIX */
688
689 #if  MSC | MSDOS | __WATCOMC__
690
691    char prefix[100], *env, *getenv();
692
693    /* Home directory reference? */
694    if (*name == '~' && (env=getenv("HOME"))) {
695       strcpy(prefix, env);            /* copy HOME directory name */
696       name++;                         /* skip over ~ in name */
697       strcat(prefix, name);
698       name--;                         /* get back to beginning */
699       strcpy(name, prefix);           /* move back into name */
700    }
701    return 1;
702 #endif
703
704 }
705
706
707 /*  MAKESESSIONKEY  --  Generate session key with optional start
708                         key.  If mode is TRUE, the key will be
709                         translated to a string, otherwise it is
710                         returned as 16 binary bytes.
711
712     from SpeakFreely by John Walker */
713
714 void makeSessionKey(char *key, char *seed, int mode)
715 {
716      int j, k;
717      struct MD5Context md5c;
718      unsigned char md5key[16], md5key1[16];
719      char s[1024];
720
721      s[0] = 0;
722      if (seed != NULL) {
723         strcat(s, seed);
724      }
725
726      /* The following creates a seed for the session key generator
727         based on a collection of volatile and environment-specific
728         information unlikely to be vulnerable (as a whole) to an
729         exhaustive search attack.  If one of these items isn't
730         available on your machine, replace it with something
731         equivalent or, if you like, just delete it. */
732
733      sprintf(s + strlen(s), "%lu", (unsigned long) getpid());
734      sprintf(s + strlen(s), "%lu", (unsigned long) getppid());
735      getcwd(s + strlen(s), 256);
736      sprintf(s + strlen(s), "%lu", (unsigned long) clock());
737      sprintf(s + strlen(s), "%lu", (unsigned long) time(NULL));
738 #ifdef Solaris
739      sysinfo(SI_HW_SERIAL,s + strlen(s), 12);
740 #endif
741 #ifdef HAVE_GETHOSTID
742      sprintf(s + strlen(s), "%lu", (unsigned long) gethostid());
743 #endif
744 #ifdef HAVE_GETDOMAINNAME
745      getdomainname(s + strlen(s), 256);
746 #endif
747      gethostname(s + strlen(s), 256);
748      sprintf(s + strlen(s), "%u", (unsigned)getuid());
749      sprintf(s + strlen(s), "%u", (unsigned)getgid());
750      MD5Init(&md5c);
751      MD5Update(&md5c, (unsigned char *)s, strlen(s));
752      MD5Final(md5key, &md5c);
753      sprintf(s + strlen(s), "%lu", (unsigned long) ((time(NULL) + 65121) ^ 0x375F));
754      MD5Init(&md5c);
755      MD5Update(&md5c, (unsigned char *)s, strlen(s));
756      MD5Final(md5key1, &md5c);
757 #define nextrand    (md5key[j] ^ md5key1[j])
758      if (mode) {
759         for (j = k = 0; j < 16; j++) {
760             unsigned char rb = nextrand;
761
762 #define Rad16(x) ((x) + 'A')
763             key[k++] = Rad16((rb >> 4) & 0xF);
764             key[k++] = Rad16(rb & 0xF);
765 #undef Rad16
766             if (j & 1) {
767                  key[k++] = '-';
768             }
769         }
770         key[--k] = 0;
771      } else {
772         for (j = 0; j < 16; j++) {
773             key[j] = nextrand;
774         }
775      }
776 }
777 #undef nextrand