2 * util.c miscellaneous utility subroutines for Bacula
10 Copyright (C) 2000, 2001, 2002 Kern Sibbald and John Walker
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.
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.
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,
31 #include "findlib/find.h"
34 * Various Bacula Utility subroutines
38 /* Return true of buffer has all zero bytes */
39 int is_buf_zero(char *buf, int len)
41 uint64_t *ip = (uint64_t *)buf;
43 int i, len64, done, rem;
45 /* Optimize by checking uint64_t for zero */
46 len64 = len >> sizeof(uint64_t);
47 for (i=0; i < len64; i++) {
52 done = len64 << sizeof(uint64_t); /* bytes already checked */
55 for (i = 0; i < rem; i++) {
64 * Convert a string duration to utime_t (64 bit seconds)
66 1: if OK, and value stored in value
68 int duration_to_utime(char *str, utime_t *value)
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};
76 /* Look for modifier */
84 while (mod[++i] != 0) {
87 str[len] = 0; /* strip modifier */
92 if (mod[i] == 0 || !is_a_number(str)) {
95 val = strtod(str, NULL);
96 if (errno != 0 || val < 0) {
99 *value = (utime_t)(val * mult[i]);
105 * Edit a utime "duration" into ASCII
107 char *edit_utime(utime_t val, char *buf)
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"};
116 for (i=0; i<5; i++) {
117 times = val / mult[i];
119 val = val - (utime_t)times * mult[i];
120 sprintf(mybuf, "%d %s%s ", times, mod[i], times>1?"s":"");
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":"");
134 * Convert a size size in bytes to uint64_t
135 * Returns 0: if error
136 1: if OK, and value stored in value
138 int size_to_uint64(char *str, int str_len, uint64_t *rtn_value)
142 int mod[] = {'*', 'k', 'm', 'g', 0}; /* first item * not used */
143 uint64_t mult[] = {1, /* byte */
145 1048576, /* megabyte */
146 1073741824}; /* gigabyte */
148 #ifdef we_have_a_compiler_that_works
149 int mod[] = {'*', 'k', 'm', 'g', 't', 0};
150 uint64_t mult[] = {1, /* byte */
152 1048576, /* megabyte */
153 1073741824, /* gigabyte */
154 1099511627776};/* terabyte */
157 Dmsg0(400, "Enter sized to uint64\n");
159 /* Look for modifier */
160 ch = str[str_len - 1];
166 while (mod[++i] != 0) {
169 str[str_len] = 0; /* strip modifier */
174 if (mod[i] == 0 || !is_a_number(str)) {
177 Dmsg3(400, "size str=:%s: %f i=%d\n", str, strtod(str, NULL), i);
179 value = (uint64_t)strtod(str, NULL);
180 Dmsg1(400, "Int value = %d\n", (int)value);
181 if (errno != 0 || value < 0) {
184 *rtn_value = (uint64_t)(value * mult[i]);
185 Dmsg2(400, "Full value = %f %" lld "\n", strtod(str, NULL) * mult[i],
191 * Check if specified string is a number or not.
192 * Taken from SQLite, cool, thanks.
194 int is_a_number(const char *n)
198 if( *n == '-' || *n == '+' ) {
201 while (B_ISDIGIT(*n)) {
205 if (digit_seen && *n == '.') {
207 while (B_ISDIGIT(*n)) { n++; }
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++; }
214 return digit_seen && *n==0;
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.
223 char *edit_uint64_with_commas(uint64_t val, char *buf)
225 sprintf(buf, "%" lld, val);
226 return add_commas(buf, buf);
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.
234 char *edit_uint64(uint64_t val, char *buf)
236 sprintf(buf, "%" lld, val);
242 * Add commas to a string, which is presumably
245 char *add_commas(char *val, char *buf)
263 for (i=0; i < 3; i++) {
272 /* Convert a string in place to lower case */
273 void lcase(char *str)
277 *str = tolower((int)(*str));
282 /* Convert spaces to non-space character.
283 * This makes scanf of fields containing spaces easier.
286 bash_spaces(char *str)
295 /* Convert non-space characters (0x1) back into spaces */
297 unbash_spaces(char *str)
306 /* Strip any trailing junk from the command */
307 void strip_trailing_junk(char *cmd)
310 p = cmd + strlen(cmd) - 1;
312 /* strip trailing junk from command */
313 while ((p >= cmd) && (*p == '\n' || *p == '\r' || *p == ' '))
317 /* Strip any trailing slashes from a directory path */
318 void strip_trailing_slashes(char *dir)
321 p = dir + strlen(dir) - 1;
323 /* strip trailing slashes */
324 while ((p >= dir) && (*p == '/'))
330 * Returns: 0 on failure (EOF)
332 * new address in passed parameter
334 int skip_spaces(char **msg)
340 while (*p && *p == ' ') {
349 * Returns: 0 on failure (EOF)
351 * new address in passed parameter
353 int skip_nonspaces(char **msg)
360 while (*p && *p != ' ') {
367 /* folded search for string - case insensitive */
369 fstrsch(char *a, char *b) /* folded case search */
371 register char *s1,*s2;
372 register char c1, c2;
376 while (*s1) { /* do it the fast way */
377 if ((*s1++ | 0x20) != (*s2++ | 0x20))
378 return 0; /* failed */
380 while (*a) { /* do it over the correct slow way */
381 if (B_ISUPPER(c1 = *a)) {
382 c1 = tolower((int)c1);
384 if (B_ISUPPER(c2 = *b)) {
385 c2 = tolower((int)c2);
397 char *encode_time(time_t time, char *buf)
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);
411 * Concatenate a string (str) onto a pool memory buffer pm
413 void pm_strcat(POOLMEM **pm, char *str)
415 int pmlen = strlen(*pm);
416 int len = strlen(str) + 1;
418 *pm = check_pool_memory_size(*pm, pmlen + len);
419 memcpy(*pm+pmlen, str, len);
424 * Copy a string (str) into a pool memory buffer pm
426 void pm_strcpy(POOLMEM **pm, char *str)
428 int len = strlen(str) + 1;
430 *pm = check_pool_memory_size(*pm, len);
431 memcpy(*pm, str, len);
436 * Convert a JobStatus code into a human readable form
438 void jobstatus_to_ascii(int JobStatus, char *msg, int maxlen)
440 char *termstat, jstat[2];
447 case JS_ErrorTerminated:
448 termstat = _("Error");
451 termstat = _("Non-fatal error");
454 termstat = _("Cancelled");
457 termstat = _("Verify differences");
460 jstat[0] = last_job.JobStatus;
465 bstrncpy(msg, termstat, maxlen);
469 * Convert Job Termination Status into a string
471 char *job_status_to_str(int stat)
479 case JS_ErrorTerminated:
484 str = _("Fatal Error");
487 str = _("Cancelled");
490 str = _("Differences");
493 str = _("Unknown term code");
501 * Convert Job Type into a string
503 char *job_type_to_str(int type)
521 str = _("Unknown Type");
528 * Convert Job Level into a string
530 char *job_level_to_str(int level)
539 str = _("Incremental");
542 str = _("Differential");
550 case L_VERIFY_CATALOG:
551 str = _("Verify Catalog");
554 str = _("Verify Init Catalog");
556 case L_VERIFY_VOLUME_TO_CATALOG:
557 str = _("Verify Volume to Catalog");
560 str = _("Verify Data");
563 str = _("Unknown Job Level");
570 /***********************************************************************
571 * Encode the mode bits into a 10 character string like LS does
572 ***********************************************************************/
574 char *encode_mode(mode_t mode, char *buf)
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' : '-'));
600 int do_shell_expansion(char *name)
602 /* ****FIXME***** this should work for Win32 too */
612 void (*istat)(int), (*qstat)(int);
614 char echout[PATH_MAX + 256];
616 static char meta[] = "~\\$[]*?`'<>\"";
620 /* Check if any meta characters are present */
622 for (i = 0; i < len; i++) {
623 if (strchr(name, meta[i])) {
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. */
635 if (len >= 3 && name[1] == ':' && name[2] == '\\') {
636 for (i=2; i<len; i++)
641 /* Pass string off to the shell for interpretation */
644 switch(pid = fork()) {
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 */
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 */
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. */
667 if (echout[i] == ' ' || echout[i] == '\n')
668 echout[i] = 0; /* keep only first one */
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)
675 signal(SIGINT, istat);
676 signal(SIGQUIT, qstat);
677 strcpy(name, echout);
681 close(pfd[0]); /* close pipe */
689 #if MSC | MSDOS | __WATCOMC__
691 char prefix[100], *env, *getenv();
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 */
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.
712 from SpeakFreely by John Walker */
714 void makeSessionKey(char *key, char *seed, int mode)
717 struct MD5Context md5c;
718 unsigned char md5key[16], md5key1[16];
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. */
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));
739 sysinfo(SI_HW_SERIAL,s + strlen(s), 12);
741 #ifdef HAVE_GETHOSTID
742 sprintf(s + strlen(s), "%lu", (unsigned long) gethostid());
744 #ifdef HAVE_GETDOMAINNAME
745 getdomainname(s + strlen(s), 256);
747 gethostname(s + strlen(s), 256);
748 sprintf(s + strlen(s), "%u", (unsigned)getuid());
749 sprintf(s + strlen(s), "%u", (unsigned)getgid());
751 MD5Update(&md5c, (unsigned char *)s, strlen(s));
752 MD5Final(md5key, &md5c);
753 sprintf(s + strlen(s), "%lu", (unsigned long) ((time(NULL) + 65121) ^ 0x375F));
755 MD5Update(&md5c, (unsigned char *)s, strlen(s));
756 MD5Final(md5key1, &md5c);
757 #define nextrand (md5key[j] ^ md5key1[j])
759 for (j = k = 0; j < 16; j++) {
760 unsigned char rb = nextrand;
762 #define Rad16(x) ((x) + 'A')
763 key[k++] = Rad16((rb >> 4) & 0xF);
764 key[k++] = Rad16(rb & 0xF);
772 for (j = 0; j < 16; j++) {