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 * Check if specified string is a number or not.
135 * Taken from SQLite, cool, thanks.
137 int is_a_number(const char *n)
141 if( *n == '-' || *n == '+' ) {
144 while (B_ISDIGIT(*n)) {
148 if (digit_seen && *n == '.') {
150 while (B_ISDIGIT(*n)) { n++; }
152 if (digit_seen && (*n == 'e' || *n == 'E')
153 && (B_ISDIGIT(n[1]) || ((n[1]=='-' || n[1] == '+') && B_ISDIGIT(n[2])))) {
154 n += 2; /* skip e- or e+ or e digit */
155 while (B_ISDIGIT(*n)) { n++; }
157 return digit_seen && *n==0;
162 * Edit an integer number with commas, the supplied buffer
163 * must be at least 27 bytes long. The incoming number
164 * is always widened to 64 bits.
166 char *edit_uint64_with_commas(uint64_t val, char *buf)
168 sprintf(buf, "%" lld, val);
169 return add_commas(buf, buf);
173 * Edit an integer number, the supplied buffer
174 * must be at least 27 bytes long. The incoming number
175 * is always widened to 64 bits.
177 char *edit_uint64(uint64_t val, char *buf)
179 sprintf(buf, "%" lld, val);
185 * Add commas to a string, which is presumably
188 char *add_commas(char *val, char *buf)
206 for (i=0; i < 3; i++) {
215 /* Convert a string in place to lower case */
216 void lcase(char *str)
220 *str = tolower((int)(*str));
225 /* Convert spaces to non-space character.
226 * This makes scanf of fields containing spaces easier.
229 bash_spaces(char *str)
238 /* Convert non-space characters (0x1) back into spaces */
240 unbash_spaces(char *str)
249 /* Strip any trailing junk from the command */
250 void strip_trailing_junk(char *cmd)
253 p = cmd + strlen(cmd) - 1;
255 /* strip trailing junk from command */
256 while ((p >= cmd) && (*p == '\n' || *p == '\r' || *p == ' '))
260 /* Strip any trailing slashes from a directory path */
261 void strip_trailing_slashes(char *dir)
264 p = dir + strlen(dir) - 1;
266 /* strip trailing slashes */
267 while ((p >= dir) && (*p == '/'))
273 * Returns: 0 on failure (EOF)
275 * new address in passed parameter
277 int skip_spaces(char **msg)
283 while (*p && *p == ' ') {
292 * Returns: 0 on failure (EOF)
294 * new address in passed parameter
296 int skip_nonspaces(char **msg)
303 while (*p && *p != ' ') {
310 /* folded search for string - case insensitive */
312 fstrsch(char *a, char *b) /* folded case search */
314 register char *s1,*s2;
315 register char c1, c2;
319 while (*s1) { /* do it the fast way */
320 if ((*s1++ | 0x20) != (*s2++ | 0x20))
321 return 0; /* failed */
323 while (*a) { /* do it over the correct slow way */
324 if (B_ISUPPER(c1 = *a)) {
325 c1 = tolower((int)c1);
327 if (B_ISUPPER(c2 = *b)) {
328 c2 = tolower((int)c2);
340 char *encode_time(time_t time, char *buf)
345 if (localtime_r(&time, &tm)) {
346 n = sprintf(buf, "%04d-%02d-%02d %02d:%02d:%02d",
347 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
348 tm.tm_hour, tm.tm_min, tm.tm_sec);
354 * Concatenate a string (str) onto a pool memory buffer pm
356 void pm_strcat(POOLMEM **pm, char *str)
358 int pmlen = strlen(*pm);
359 int len = strlen(str) + 1;
361 *pm = check_pool_memory_size(*pm, pmlen + len);
362 memcpy(*pm+pmlen, str, len);
367 * Copy a string (str) into a pool memory buffer pm
369 void pm_strcpy(POOLMEM **pm, char *str)
371 int len = strlen(str) + 1;
373 *pm = check_pool_memory_size(*pm, len);
374 memcpy(*pm, str, len);
379 * Convert a JobStatus code into a human readable form
381 void jobstatus_to_ascii(int JobStatus, char *msg, int maxlen)
383 char *termstat, jstat[2];
390 case JS_ErrorTerminated:
391 termstat = _("Error");
394 termstat = _("Non-fatal error");
397 termstat = _("Cancelled");
400 termstat = _("Verify differences");
403 jstat[0] = last_job.JobStatus;
408 strncpy(msg, termstat, maxlen);
413 * Convert Job Termination Status into a string
415 char *job_status_to_str(int stat)
423 case JS_ErrorTerminated:
428 str = _("Fatal Error");
431 str = _("Cancelled");
434 str = _("Differences");
437 str = _("Unknown term code");
445 * Convert Job Type into a string
447 char *job_type_to_str(int type)
465 str = _("Unknown Type");
472 * Convert Job Level into a string
474 char *job_level_to_str(int level)
483 str = _("Incremental");
486 str = _("Differential");
494 case L_VERIFY_CATALOG:
495 str = _("Verify Catalog");
498 str = _("Verify Init Catalog");
500 case L_VERIFY_VOLUME_TO_CATALOG:
501 str = _("Verify Volume to Catalog");
504 str = _("Verify Data");
507 str = _("Unknown Job Level");
514 /***********************************************************************
515 * Encode the mode bits into a 10 character string like LS does
516 ***********************************************************************/
518 char *encode_mode(mode_t mode, char *buf)
522 *cp++ = S_ISDIR(mode) ? 'd' : S_ISBLK(mode) ? 'b' : S_ISCHR(mode) ? 'c' :
523 S_ISLNK(mode) ? 'l' : '-';
524 *cp++ = mode & S_IRUSR ? 'r' : '-';
525 *cp++ = mode & S_IWUSR ? 'w' : '-';
526 *cp++ = (mode & S_ISUID
527 ? (mode & S_IXUSR ? 's' : 'S')
528 : (mode & S_IXUSR ? 'x' : '-'));
529 *cp++ = mode & S_IRGRP ? 'r' : '-';
530 *cp++ = mode & S_IWGRP ? 'w' : '-';
531 *cp++ = (mode & S_ISGID
532 ? (mode & S_IXGRP ? 's' : 'S')
533 : (mode & S_IXGRP ? 'x' : '-'));
534 *cp++ = mode & S_IROTH ? 'r' : '-';
535 *cp++ = mode & S_IWOTH ? 'w' : '-';
536 *cp++ = (mode & S_ISVTX
537 ? (mode & S_IXOTH ? 't' : 'T')
538 : (mode & S_IXOTH ? 'x' : '-'));
544 int do_shell_expansion(char *name)
546 /* ****FIXME***** this should work for Win32 too */
556 void (*istat)(int), (*qstat)(int);
558 char echout[PATH_MAX + 256];
560 static char meta[] = "~\\$[]*?`'<>\"";
564 /* Check if any meta characters are present */
566 for (i = 0; i < len; i++) {
567 if (strchr(name, meta[i])) {
575 /* If the filename appears to be a DOS filename,
576 convert all backward slashes \ to Unix path
577 separators / and insert a \ infront of spaces. */
579 if (len >= 3 && name[1] == ':' && name[2] == '\\') {
580 for (i=2; i<len; i++)
585 /* Pass string off to the shell for interpretation */
588 switch(pid = fork()) {
594 if ((shellcmd = getenv("SHELL")) == NULL)
595 shellcmd = "/bin/sh";
596 close(1); dup(pfd[1]); /* attach pipes to stdin and stdout */
597 close(2); dup(pfd[1]);
598 for (i = 3; i < 32; i++) /* close everything else */
600 strcpy(echout, "echo "); /* form echo command */
601 strcat(echout, name);
602 execl(shellcmd, shellcmd, "-c", echout, NULL); /* give to shell */
603 exit(127); /* shouldn't get here */
605 default: /* parent */
606 /* read output from child */
607 i = read(pfd[0], echout, sizeof echout);
608 echout[--i] = 0; /* set end of string */
609 /* look for first word or first line. */
611 if (echout[i] == ' ' || echout[i] == '\n')
612 echout[i] = 0; /* keep only first one */
614 istat = signal(SIGINT, SIG_IGN);
615 qstat = signal(SIGQUIT, SIG_IGN);
616 /* wait for child to exit */
617 while ((wpid = wait(&waitstatus)) != pid && wpid != -1)
619 signal(SIGINT, istat);
620 signal(SIGQUIT, qstat);
621 strcpy(name, echout);
625 close(pfd[0]); /* close pipe */
633 #if MSC | MSDOS | __WATCOMC__
635 char prefix[100], *env, *getenv();
637 /* Home directory reference? */
638 if (*name == '~' && (env=getenv("HOME"))) {
639 strcpy(prefix, env); /* copy HOME directory name */
640 name++; /* skip over ~ in name */
641 strcat(prefix, name);
642 name--; /* get back to beginning */
643 strcpy(name, prefix); /* move back into name */
651 static void build_argc_argv(char *cmd, int *bargc, char *bargv[], int max_arg);
654 * Run an external program. Optionally wait a specified number
655 * of seconds. Program killed if wait exceeded. Optionally
656 * return the output from the program (normally a single line).
658 int run_program(char *prog, int wait, POOLMEM *results)
662 pid_t pid1, pid2 = 0;
664 char *bargv[MAX_ARGV];
668 build_argc_argv(prog, &bargc, bargv, MAX_ARGV);
670 printf("argc=%d\n", bargc);
672 for (i=0; i<bargc; i++) {
673 printf("argc=%d argv=%s\n", i, bargv[i]);
677 if (results && pipe(pfd) == -1) {
680 /* Start worker process */
681 switch (pid1 = fork()) {
686 // printf("execl of %s\n", prog);
688 close(1); dup(pfd[1]); /* attach pipes to stdin and stdout */
689 close(2); dup(pfd[1]);
691 execvp(bargv[0], bargv);
692 exit(errno); /* shouldn't get here */
694 default: /* parent */
695 /* start timer process */
697 switch (pid2=fork()) {
700 case 0: /* child 2 */
701 /* Time the worker process */
703 if (kill(pid1, SIGTERM) == 0) { /* time expired kill it */
709 default: /* parent */
714 /* Parent continues here */
717 i = read(pfd[0], results, sizeof_pool_memory(results) - 1);
721 results[i] = 0; /* set end of string */
723 /* wait for worker child to exit */
726 wpid = waitpid(pid1, &chldstatus, 0);
727 if (wpid == pid1 || (errno != EINTR)) {
731 if (WIFEXITED(chldstatus))
732 stat = WEXITSTATUS(chldstatus);
735 kill(pid2, SIGKILL); /* kill off timer process */
736 waitpid(pid2, &chldstatus, 0); /* reap timer process */
739 close(pfd[0]); /* close pipe */
748 * Build argc and argv from a string
750 static void build_argc_argv(char *cmd, int *bargc, char *bargv[], int max_argv)
757 for (i=0; i<max_argv; i++)
762 while (*p && (*p == ' ' || *p == '\t'))
769 while (*p && argc < MAX_ARGV) {
772 while (*q && *q != '\"')
776 while (*q && *q != ' ')
783 while (*p && (*p == ' ' || *p == '\t'))
794 /* MAKESESSIONKEY -- Generate session key with optional start
795 key. If mode is TRUE, the key will be
796 translated to a string, otherwise it is
797 returned as 16 binary bytes.
799 from SpeakFreely by John Walker */
801 void makeSessionKey(char *key, char *seed, int mode)
804 struct MD5Context md5c;
805 unsigned char md5key[16], md5key1[16];
813 /* The following creates a seed for the session key generator
814 based on a collection of volatile and environment-specific
815 information unlikely to be vulnerable (as a whole) to an
816 exhaustive search attack. If one of these items isn't
817 available on your machine, replace it with something
818 equivalent or, if you like, just delete it. */
820 sprintf(s + strlen(s), "%lu", (unsigned long) getpid());
821 sprintf(s + strlen(s), "%lu", (unsigned long) getppid());
822 getcwd(s + strlen(s), 256);
823 sprintf(s + strlen(s), "%lu", (unsigned long) clock());
824 sprintf(s + strlen(s), "%lu", (unsigned long) time(NULL));
826 sysinfo(SI_HW_SERIAL,s + strlen(s), 12);
828 #ifdef HAVE_GETHOSTID
829 sprintf(s + strlen(s), "%lu", (unsigned long) gethostid());
831 #ifdef HAVE_GETDOMAINNAME
832 getdomainname(s + strlen(s), 256);
834 gethostname(s + strlen(s), 256);
835 sprintf(s + strlen(s), "%u", (unsigned)getuid());
836 sprintf(s + strlen(s), "%u", (unsigned)getgid());
838 MD5Update(&md5c, (unsigned char *)s, strlen(s));
839 MD5Final(md5key, &md5c);
840 sprintf(s + strlen(s), "%lu", (unsigned long) ((time(NULL) + 65121) ^ 0x375F));
842 MD5Update(&md5c, (unsigned char *)s, strlen(s));
843 MD5Final(md5key1, &md5c);
844 #define nextrand (md5key[j] ^ md5key1[j])
846 for (j = k = 0; j < 16; j++) {
847 unsigned char rb = nextrand;
849 #define Rad16(x) ((x) + 'A')
850 key[k++] = Rad16((rb >> 4) & 0xF);
851 key[k++] = Rad16(rb & 0xF);
859 for (j = 0; j < 16; j++) {