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
39 * Convert a string to btime_t (64 bit seconds)
41 1: if OK, and value stored in value
43 int string_to_btime(char *str, btime_t *value)
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};
51 /* Look for modifier */
59 while (mod[++i] != 0) {
62 str[len] = 0; /* strip modifier */
67 if (mod[i] == 0 || !is_a_number(str)) {
70 val = strtod(str, NULL);
71 if (errno != 0 || val < 0) {
74 *value = (btime_t)(val * mult[i]);
79 char *edit_btime(btime_t val, char *buf)
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"};
89 times = val / mult[i];
91 val = val - (btime_t)times * mult[i];
92 sprintf(mybuf, "%d %s%s ", times, mod[i], times>1?"s":"");
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":"");
106 * Check if specified string is a number or not.
107 * Taken from SQLite, cool, thanks.
109 int is_a_number(const char *n)
113 if( *n == '-' || *n == '+' ) {
116 while (ISDIGIT(*n)) {
120 if (digit_seen && *n == '.') {
122 while (ISDIGIT(*n)) { n++; }
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++; }
129 return digit_seen && *n==0;
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.
138 char *edit_uint64_with_commas(uint64_t val, char *buf)
140 sprintf(buf, "%" lld, val);
141 return add_commas(buf, buf);
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.
149 char *edit_uint64(uint64_t val, char *buf)
151 sprintf(buf, "%" lld, val);
157 * Add commas to a string, which is presumably
160 char *add_commas(char *val, char *buf)
178 for (i=0; i < 3; i++) {
187 /* Convert a string in place to lower case */
188 void lcase(char *str)
192 *str = tolower((int)(*str));
197 /* Convert spaces to non-space character.
198 * This makes scanf of fields containing spaces easier.
201 bash_spaces(char *str)
210 /* Convert non-space characters (0x1) back into spaces */
212 unbash_spaces(char *str)
221 /* Strip any trailing junk from the command */
222 void strip_trailing_junk(char *cmd)
225 p = cmd + strlen(cmd) - 1;
227 /* strip trailing junk from command */
228 while ((p >= cmd) && (*p == '\n' || *p == '\r' || *p == ' '))
232 /* Strip any trailing slashes from a directory path */
233 void strip_trailing_slashes(char *dir)
236 p = dir + strlen(dir) - 1;
238 /* strip trailing slashes */
239 while ((p >= dir) && (*p == '/'))
245 * Returns: 0 on failure (EOF)
247 * new address in passed parameter
249 int skip_spaces(char **msg)
255 while (*p && *p == ' ') {
264 * Returns: 0 on failure (EOF)
266 * new address in passed parameter
268 int skip_nonspaces(char **msg)
275 while (*p && *p != ' ') {
282 /* folded search for string - case insensitive */
284 fstrsch(char *a, char *b) /* folded case search */
286 register char *s1,*s2;
287 register char c1, c2;
291 while (*s1) { /* do it the fast way */
292 if ((*s1++ | 0x20) != (*s2++ | 0x20))
293 return 0; /* failed */
295 while (*a) { /* do it over the correct slow way */
296 if (ISUPPER(c1 = *a)) {
297 c1 = tolower((int)c1);
299 if (ISUPPER(c2 = *b)) {
300 c2 = tolower((int)c2);
312 char *encode_time(time_t time, char *buf)
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);
326 * Concatenate a string (str) onto a pool memory buffer pm
328 void pm_strcat(POOLMEM **pm, char *str)
330 int pmlen = strlen(*pm);
331 int len = strlen(str) + 1;
333 *pm = check_pool_memory_size(*pm, pmlen + len);
334 memcpy(*pm+pmlen, str, len);
339 * Copy a string (str) into a pool memory buffer pm
341 void pm_strcpy(POOLMEM **pm, char *str)
343 int len = strlen(str) + 1;
345 *pm = check_pool_memory_size(*pm, len);
346 memcpy(*pm, str, len);
351 * Convert a JobStatus code into a human readable form
353 void jobstatus_to_ascii(int JobStatus, char *msg, int maxlen)
355 char *termstat, jstat[2];
362 case JS_ErrorTerminated:
363 termstat = _("Error");
366 termstat = _("Non-fatal error");
369 termstat = _("Cancelled");
372 termstat = _("Verify differences");
375 jstat[0] = last_job.JobStatus;
380 strncpy(msg, termstat, maxlen);
385 * Convert Job Termination Status into a string
387 char *job_status_to_str(int stat)
395 case JS_ErrorTerminated:
400 str = _("Fatal Error");
403 str = _("Cancelled");
406 str = _("Differences");
409 str = _("Unknown term code");
417 * Convert Job Type into a string
419 char *job_type_to_str(int type)
437 str = _("Unknown Type");
444 * Convert Job Level into a string
446 char *job_level_to_str(int level)
455 str = _("Incremental");
458 str = _("Differential");
466 case L_VERIFY_CATALOG:
467 str = _("Verify Catalog");
470 str = _("Verify Init Catalog");
472 case L_VERIFY_VOLUME_TO_CATALOG:
473 str = _("Verify Volume to Catalog");
476 str = _("Verify Data");
479 str = _("Unknown Job Level");
486 /***********************************************************************
487 * Encode the mode bits into a 10 character string like LS does
488 ***********************************************************************/
490 char *encode_mode(mode_t mode, char *buf)
494 *cp++ = S_ISDIR(mode) ? 'd' : S_ISBLK(mode) ? 'b' : S_ISCHR(mode) ? 'c' :
495 S_ISLNK(mode) ? 'l' : '-';
496 *cp++ = mode & S_IRUSR ? 'r' : '-';
497 *cp++ = mode & S_IWUSR ? 'w' : '-';
498 *cp++ = (mode & S_ISUID
499 ? (mode & S_IXUSR ? 's' : 'S')
500 : (mode & S_IXUSR ? 'x' : '-'));
501 *cp++ = mode & S_IRGRP ? 'r' : '-';
502 *cp++ = mode & S_IWGRP ? 'w' : '-';
503 *cp++ = (mode & S_ISGID
504 ? (mode & S_IXGRP ? 's' : 'S')
505 : (mode & S_IXGRP ? 'x' : '-'));
506 *cp++ = mode & S_IROTH ? 'r' : '-';
507 *cp++ = mode & S_IWOTH ? 'w' : '-';
508 *cp++ = (mode & S_ISVTX
509 ? (mode & S_IXOTH ? 't' : 'T')
510 : (mode & S_IXOTH ? 'x' : '-'));
516 int do_shell_expansion(char *name)
518 /* ****FIXME***** this should work for Win32 too */
528 void (*istat)(int), (*qstat)(int);
530 char echout[PATH_MAX + 256];
532 static char meta[] = "~\\$[]*?`'<>\"";
536 /* Check if any meta characters are present */
538 for (i = 0; i < len; i++) {
539 if (strchr(name, meta[i])) {
547 /* If the filename appears to be a DOS filename,
548 convert all backward slashes \ to Unix path
549 separators / and insert a \ infront of spaces. */
551 if (len >= 3 && name[1] == ':' && name[2] == '\\') {
552 for (i=2; i<len; i++)
557 /* Pass string off to the shell for interpretation */
560 switch(pid = fork()) {
566 if ((shellcmd = getenv("SHELL")) == NULL)
567 shellcmd = "/bin/sh";
568 close(1); dup(pfd[1]); /* attach pipes to stdin and stdout */
569 close(2); dup(pfd[1]);
570 for (i = 3; i < 32; i++) /* close everything else */
572 strcpy(echout, "echo "); /* form echo command */
573 strcat(echout, name);
574 execl(shellcmd, shellcmd, "-c", echout, NULL); /* give to shell */
575 exit(127); /* shouldn't get here */
577 default: /* parent */
578 /* read output from child */
579 i = read(pfd[0], echout, sizeof echout);
580 echout[--i] = 0; /* set end of string */
581 /* look for first word or first line. */
583 if (echout[i] == ' ' || echout[i] == '\n')
584 echout[i] = 0; /* keep only first one */
586 istat = signal(SIGINT, SIG_IGN);
587 qstat = signal(SIGQUIT, SIG_IGN);
588 /* wait for child to exit */
589 while ((wpid = wait(&waitstatus)) != pid && wpid != -1)
591 signal(SIGINT, istat);
592 signal(SIGQUIT, qstat);
593 strcpy(name, echout);
597 close(pfd[0]); /* close pipe */
605 #if MSC | MSDOS | __WATCOMC__
607 char prefix[100], *env, *getenv();
609 /* Home directory reference? */
610 if (*name == '~' && (env=getenv("HOME"))) {
611 strcpy(prefix, env); /* copy HOME directory name */
612 name++; /* skip over ~ in name */
613 strcat(prefix, name);
614 name--; /* get back to beginning */
615 strcpy(name, prefix); /* move back into name */
623 static void build_argc_argv(char *cmd, int *bargc, char *bargv[], int max_arg);
626 * Run an external program. Optionally wait a specified number
627 * of seconds. Program killed if wait exceeded. Optionally
628 * return the output from the program (normally a single line).
630 int run_program(char *prog, int wait, POOLMEM *results)
634 pid_t pid1, pid2 = 0;
636 char *bargv[MAX_ARGV];
640 build_argc_argv(prog, &bargc, bargv, MAX_ARGV);
642 printf("argc=%d\n", bargc);
644 for (i=0; i<bargc; i++) {
645 printf("argc=%d argv=%s\n", i, bargv[i]);
649 if (results && pipe(pfd) == -1) {
652 /* Start worker process */
653 switch (pid1 = fork()) {
658 // printf("execl of %s\n", prog);
660 close(1); dup(pfd[1]); /* attach pipes to stdin and stdout */
661 close(2); dup(pfd[1]);
663 execvp(bargv[0], bargv);
664 exit(errno); /* shouldn't get here */
666 default: /* parent */
667 /* start timer process */
669 switch (pid2=fork()) {
672 case 0: /* child 2 */
673 /* Time the worker process */
675 if (kill(pid1, SIGTERM) == 0) { /* time expired kill it */
681 default: /* parent */
686 /* Parent continues here */
689 i = read(pfd[0], results, sizeof_pool_memory(results) - 1);
693 results[i] = 0; /* set end of string */
695 /* wait for worker child to exit */
698 wpid = waitpid(pid1, &chldstatus, 0);
699 if (wpid == pid1 || (errno != EINTR)) {
703 if (WIFEXITED(chldstatus))
704 stat = WEXITSTATUS(chldstatus);
707 kill(pid2, SIGKILL); /* kill off timer process */
708 waitpid(pid2, &chldstatus, 0); /* reap timer process */
711 close(pfd[0]); /* close pipe */
720 * Build argc and argv from a string
722 static void build_argc_argv(char *cmd, int *bargc, char *bargv[], int max_argv)
729 for (i=0; i<max_argv; i++)
734 while (*p && (*p == ' ' || *p == '\t'))
741 while (*p && argc < MAX_ARGV) {
744 while (*q && *q != '\"')
748 while (*q && *q != ' ')
755 while (*p && (*p == ' ' || *p == '\t'))
766 /* MAKESESSIONKEY -- Generate session key with optional start
767 key. If mode is TRUE, the key will be
768 translated to a string, otherwise it is
769 returned as 16 binary bytes.
771 from SpeakFreely by John Walker */
773 void makeSessionKey(char *key, char *seed, int mode)
776 struct MD5Context md5c;
777 unsigned char md5key[16], md5key1[16];
785 /* The following creates a seed for the session key generator
786 based on a collection of volatile and environment-specific
787 information unlikely to be vulnerable (as a whole) to an
788 exhaustive search attack. If one of these items isn't
789 available on your machine, replace it with something
790 equivalent or, if you like, just delete it. */
792 sprintf(s + strlen(s), "%lu", (unsigned long) getpid());
793 sprintf(s + strlen(s), "%lu", (unsigned long) getppid());
794 getcwd(s + strlen(s), 256);
795 sprintf(s + strlen(s), "%lu", (unsigned long) clock());
796 sprintf(s + strlen(s), "%lu", (unsigned long) time(NULL));
798 sysinfo(SI_HW_SERIAL,s + strlen(s), 12);
800 #ifdef HAVE_GETHOSTID
801 sprintf(s + strlen(s), "%lu", (unsigned long) gethostid());
803 #ifdef HAVE_GETDOMAINNAME
804 getdomainname(s + strlen(s), 256);
806 gethostname(s + strlen(s), 256);
807 sprintf(s + strlen(s), "%u", (unsigned)getuid());
808 sprintf(s + strlen(s), "%u", (unsigned)getgid());
810 MD5Update(&md5c, (unsigned char *)s, strlen(s));
811 MD5Final(md5key, &md5c);
812 sprintf(s + strlen(s), "%lu", (unsigned long) ((time(NULL) + 65121) ^ 0x375F));
814 MD5Update(&md5c, (unsigned char *)s, strlen(s));
815 MD5Final(md5key1, &md5c);
816 #define nextrand (md5key[j] ^ md5key1[j])
818 for (j = k = 0; j < 16; j++) {
819 unsigned char rb = nextrand;
821 #define Rad16(x) ((x) + 'A')
822 key[k++] = Rad16((rb >> 4) & 0xF);
823 key[k++] = Rad16(rb & 0xF);
831 for (j = 0; j < 16; j++) {