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 strncpy(msg, termstat, maxlen);
470 * Convert Job Termination Status into a string
472 char *job_status_to_str(int stat)
480 case JS_ErrorTerminated:
485 str = _("Fatal Error");
488 str = _("Cancelled");
491 str = _("Differences");
494 str = _("Unknown term code");
502 * Convert Job Type into a string
504 char *job_type_to_str(int type)
522 str = _("Unknown Type");
529 * Convert Job Level into a string
531 char *job_level_to_str(int level)
540 str = _("Incremental");
543 str = _("Differential");
551 case L_VERIFY_CATALOG:
552 str = _("Verify Catalog");
555 str = _("Verify Init Catalog");
557 case L_VERIFY_VOLUME_TO_CATALOG:
558 str = _("Verify Volume to Catalog");
561 str = _("Verify Data");
564 str = _("Unknown Job Level");
571 /***********************************************************************
572 * Encode the mode bits into a 10 character string like LS does
573 ***********************************************************************/
575 char *encode_mode(mode_t mode, char *buf)
579 *cp++ = S_ISDIR(mode) ? 'd' : S_ISBLK(mode) ? 'b' : S_ISCHR(mode) ? 'c' :
580 S_ISLNK(mode) ? 'l' : '-';
581 *cp++ = mode & S_IRUSR ? 'r' : '-';
582 *cp++ = mode & S_IWUSR ? 'w' : '-';
583 *cp++ = (mode & S_ISUID
584 ? (mode & S_IXUSR ? 's' : 'S')
585 : (mode & S_IXUSR ? 'x' : '-'));
586 *cp++ = mode & S_IRGRP ? 'r' : '-';
587 *cp++ = mode & S_IWGRP ? 'w' : '-';
588 *cp++ = (mode & S_ISGID
589 ? (mode & S_IXGRP ? 's' : 'S')
590 : (mode & S_IXGRP ? 'x' : '-'));
591 *cp++ = mode & S_IROTH ? 'r' : '-';
592 *cp++ = mode & S_IWOTH ? 'w' : '-';
593 *cp++ = (mode & S_ISVTX
594 ? (mode & S_IXOTH ? 't' : 'T')
595 : (mode & S_IXOTH ? 'x' : '-'));
601 int do_shell_expansion(char *name)
603 /* ****FIXME***** this should work for Win32 too */
613 void (*istat)(int), (*qstat)(int);
615 char echout[PATH_MAX + 256];
617 static char meta[] = "~\\$[]*?`'<>\"";
621 /* Check if any meta characters are present */
623 for (i = 0; i < len; i++) {
624 if (strchr(name, meta[i])) {
632 /* If the filename appears to be a DOS filename,
633 convert all backward slashes \ to Unix path
634 separators / and insert a \ infront of spaces. */
636 if (len >= 3 && name[1] == ':' && name[2] == '\\') {
637 for (i=2; i<len; i++)
642 /* Pass string off to the shell for interpretation */
645 switch(pid = fork()) {
651 if ((shellcmd = getenv("SHELL")) == NULL)
652 shellcmd = "/bin/sh";
653 close(1); dup(pfd[1]); /* attach pipes to stdin and stdout */
654 close(2); dup(pfd[1]);
655 for (i = 3; i < 32; i++) /* close everything else */
657 strcpy(echout, "echo "); /* form echo command */
658 strcat(echout, name);
659 execl(shellcmd, shellcmd, "-c", echout, NULL); /* give to shell */
660 exit(127); /* shouldn't get here */
662 default: /* parent */
663 /* read output from child */
664 i = read(pfd[0], echout, sizeof echout);
665 echout[--i] = 0; /* set end of string */
666 /* look for first word or first line. */
668 if (echout[i] == ' ' || echout[i] == '\n')
669 echout[i] = 0; /* keep only first one */
671 istat = signal(SIGINT, SIG_IGN);
672 qstat = signal(SIGQUIT, SIG_IGN);
673 /* wait for child to exit */
674 while ((wpid = wait(&waitstatus)) != pid && wpid != -1)
676 signal(SIGINT, istat);
677 signal(SIGQUIT, qstat);
678 strcpy(name, echout);
682 close(pfd[0]); /* close pipe */
690 #if MSC | MSDOS | __WATCOMC__
692 char prefix[100], *env, *getenv();
694 /* Home directory reference? */
695 if (*name == '~' && (env=getenv("HOME"))) {
696 strcpy(prefix, env); /* copy HOME directory name */
697 name++; /* skip over ~ in name */
698 strcat(prefix, name);
699 name--; /* get back to beginning */
700 strcpy(name, prefix); /* move back into name */
708 static void build_argc_argv(char *cmd, int *bargc, char *bargv[], int max_arg);
711 * Run an external program. Optionally wait a specified number
712 * of seconds. Program killed if wait exceeded. Optionally
713 * return the output from the program (normally a single line).
715 int run_program(char *prog, int wait, POOLMEM *results)
719 pid_t pid1, pid2 = 0;
721 char *bargv[MAX_ARGV];
725 build_argc_argv(prog, &bargc, bargv, MAX_ARGV);
727 printf("argc=%d\n", bargc);
729 for (i=0; i<bargc; i++) {
730 printf("argc=%d argv=%s\n", i, bargv[i]);
734 if (results && pipe(pfd) == -1) {
737 /* Start worker process */
738 switch (pid1 = fork()) {
743 // printf("execl of %s\n", prog);
745 close(1); dup(pfd[1]); /* attach pipes to stdin and stdout */
746 close(2); dup(pfd[1]);
748 execvp(bargv[0], bargv);
749 exit(errno); /* shouldn't get here */
751 default: /* parent */
752 /* start timer process */
754 switch (pid2=fork()) {
757 case 0: /* child 2 */
758 /* Time the worker process */
760 if (kill(pid1, SIGTERM) == 0) { /* time expired kill it */
766 default: /* parent */
771 /* Parent continues here */
774 i = read(pfd[0], results, sizeof_pool_memory(results) - 1);
778 results[i] = 0; /* set end of string */
780 /* wait for worker child to exit */
783 wpid = waitpid(pid1, &chldstatus, 0);
784 if (wpid == pid1 || (errno != EINTR)) {
788 if (WIFEXITED(chldstatus))
789 stat = WEXITSTATUS(chldstatus);
792 kill(pid2, SIGKILL); /* kill off timer process */
793 waitpid(pid2, &chldstatus, 0); /* reap timer process */
796 close(pfd[0]); /* close pipe */
805 * Build argc and argv from a string
807 static void build_argc_argv(char *cmd, int *bargc, char *bargv[], int max_argv)
814 for (i=0; i<max_argv; i++)
819 while (*p && (*p == ' ' || *p == '\t'))
826 while (*p && argc < MAX_ARGV) {
829 while (*q && *q != '\"')
833 while (*q && *q != ' ')
840 while (*p && (*p == ' ' || *p == '\t'))
851 /* MAKESESSIONKEY -- Generate session key with optional start
852 key. If mode is TRUE, the key will be
853 translated to a string, otherwise it is
854 returned as 16 binary bytes.
856 from SpeakFreely by John Walker */
858 void makeSessionKey(char *key, char *seed, int mode)
861 struct MD5Context md5c;
862 unsigned char md5key[16], md5key1[16];
870 /* The following creates a seed for the session key generator
871 based on a collection of volatile and environment-specific
872 information unlikely to be vulnerable (as a whole) to an
873 exhaustive search attack. If one of these items isn't
874 available on your machine, replace it with something
875 equivalent or, if you like, just delete it. */
877 sprintf(s + strlen(s), "%lu", (unsigned long) getpid());
878 sprintf(s + strlen(s), "%lu", (unsigned long) getppid());
879 getcwd(s + strlen(s), 256);
880 sprintf(s + strlen(s), "%lu", (unsigned long) clock());
881 sprintf(s + strlen(s), "%lu", (unsigned long) time(NULL));
883 sysinfo(SI_HW_SERIAL,s + strlen(s), 12);
885 #ifdef HAVE_GETHOSTID
886 sprintf(s + strlen(s), "%lu", (unsigned long) gethostid());
888 #ifdef HAVE_GETDOMAINNAME
889 getdomainname(s + strlen(s), 256);
891 gethostname(s + strlen(s), 256);
892 sprintf(s + strlen(s), "%u", (unsigned)getuid());
893 sprintf(s + strlen(s), "%u", (unsigned)getgid());
895 MD5Update(&md5c, (unsigned char *)s, strlen(s));
896 MD5Final(md5key, &md5c);
897 sprintf(s + strlen(s), "%lu", (unsigned long) ((time(NULL) + 65121) ^ 0x375F));
899 MD5Update(&md5c, (unsigned char *)s, strlen(s));
900 MD5Final(md5key1, &md5c);
901 #define nextrand (md5key[j] ^ md5key1[j])
903 for (j = k = 0; j < 16; j++) {
904 unsigned char rb = nextrand;
906 #define Rad16(x) ((x) + 'A')
907 key[k++] = Rad16((rb >> 4) & 0xF);
908 key[k++] = Rad16(rb & 0xF);
916 for (j = 0; j < 16; j++) {