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 duration 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]);
80 * Edit a btime "duration" into ASCII
82 char *edit_btime(btime_t val, char *buf)
85 static int mult[] = {60*60*24*365, 60*60*24*30, 60*60*24, 60*60, 60};
86 static char *mod[] = {"year", "month", "day", "hour", "min"};
92 times = val / mult[i];
94 val = val - (btime_t)times * mult[i];
95 sprintf(mybuf, "%d %s%s ", times, mod[i], times>1?"s":"");
99 if (val == 0 && strlen(buf) == 0) {
100 strcat(buf, "0 secs");
101 } else if (val != 0) {
102 sprintf(mybuf, "%d sec%s", (uint32_t)val, val>1?"s":"");
109 * Check if specified string is a number or not.
110 * Taken from SQLite, cool, thanks.
112 int is_a_number(const char *n)
116 if( *n == '-' || *n == '+' ) {
119 while (ISDIGIT(*n)) {
123 if (digit_seen && *n == '.') {
125 while (ISDIGIT(*n)) { n++; }
127 if (digit_seen && (*n == 'e' || *n == 'E')
128 && (ISDIGIT(n[1]) || ((n[1]=='-' || n[1] == '+') && ISDIGIT(n[2])))) {
129 n += 2; /* skip e- or e+ or e digit */
130 while (ISDIGIT(*n)) { n++; }
132 return digit_seen && *n==0;
137 * Edit an integer number with commas, the supplied buffer
138 * must be at least 27 bytes long. The incoming number
139 * is always widened to 64 bits.
141 char *edit_uint64_with_commas(uint64_t val, char *buf)
143 sprintf(buf, "%" lld, val);
144 return add_commas(buf, buf);
148 * Edit an integer number, the supplied buffer
149 * must be at least 27 bytes long. The incoming number
150 * is always widened to 64 bits.
152 char *edit_uint64(uint64_t val, char *buf)
154 sprintf(buf, "%" lld, val);
160 * Add commas to a string, which is presumably
163 char *add_commas(char *val, char *buf)
181 for (i=0; i < 3; i++) {
190 /* Convert a string in place to lower case */
191 void lcase(char *str)
195 *str = tolower((int)(*str));
200 /* Convert spaces to non-space character.
201 * This makes scanf of fields containing spaces easier.
204 bash_spaces(char *str)
213 /* Convert non-space characters (0x1) back into spaces */
215 unbash_spaces(char *str)
224 /* Strip any trailing junk from the command */
225 void strip_trailing_junk(char *cmd)
228 p = cmd + strlen(cmd) - 1;
230 /* strip trailing junk from command */
231 while ((p >= cmd) && (*p == '\n' || *p == '\r' || *p == ' '))
235 /* Strip any trailing slashes from a directory path */
236 void strip_trailing_slashes(char *dir)
239 p = dir + strlen(dir) - 1;
241 /* strip trailing slashes */
242 while ((p >= dir) && (*p == '/'))
248 * Returns: 0 on failure (EOF)
250 * new address in passed parameter
252 int skip_spaces(char **msg)
258 while (*p && *p == ' ') {
267 * Returns: 0 on failure (EOF)
269 * new address in passed parameter
271 int skip_nonspaces(char **msg)
278 while (*p && *p != ' ') {
285 /* folded search for string - case insensitive */
287 fstrsch(char *a, char *b) /* folded case search */
289 register char *s1,*s2;
290 register char c1, c2;
294 while (*s1) { /* do it the fast way */
295 if ((*s1++ | 0x20) != (*s2++ | 0x20))
296 return 0; /* failed */
298 while (*a) { /* do it over the correct slow way */
299 if (ISUPPER(c1 = *a)) {
300 c1 = tolower((int)c1);
302 if (ISUPPER(c2 = *b)) {
303 c2 = tolower((int)c2);
315 char *encode_time(time_t time, char *buf)
320 if (localtime_r(&time, &tm)) {
321 n = sprintf(buf, "%04d-%02d-%02d %02d:%02d:%02d",
322 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
323 tm.tm_hour, tm.tm_min, tm.tm_sec);
329 * Concatenate a string (str) onto a pool memory buffer pm
331 void pm_strcat(POOLMEM **pm, char *str)
333 int pmlen = strlen(*pm);
334 int len = strlen(str) + 1;
336 *pm = check_pool_memory_size(*pm, pmlen + len);
337 memcpy(*pm+pmlen, str, len);
342 * Copy a string (str) into a pool memory buffer pm
344 void pm_strcpy(POOLMEM **pm, char *str)
346 int len = strlen(str) + 1;
348 *pm = check_pool_memory_size(*pm, len);
349 memcpy(*pm, str, len);
354 * Convert a JobStatus code into a human readable form
356 void jobstatus_to_ascii(int JobStatus, char *msg, int maxlen)
358 char *termstat, jstat[2];
365 case JS_ErrorTerminated:
366 termstat = _("Error");
369 termstat = _("Non-fatal error");
372 termstat = _("Cancelled");
375 termstat = _("Verify differences");
378 jstat[0] = last_job.JobStatus;
383 strncpy(msg, termstat, maxlen);
388 * Convert Job Termination Status into a string
390 char *job_status_to_str(int stat)
398 case JS_ErrorTerminated:
403 str = _("Fatal Error");
406 str = _("Cancelled");
409 str = _("Differences");
412 str = _("Unknown term code");
420 * Convert Job Type into a string
422 char *job_type_to_str(int type)
440 str = _("Unknown Type");
447 * Convert Job Level into a string
449 char *job_level_to_str(int level)
458 str = _("Incremental");
461 str = _("Differential");
469 case L_VERIFY_CATALOG:
470 str = _("Verify Catalog");
473 str = _("Verify Init Catalog");
475 case L_VERIFY_VOLUME_TO_CATALOG:
476 str = _("Verify Volume to Catalog");
479 str = _("Verify Data");
482 str = _("Unknown Job Level");
489 /***********************************************************************
490 * Encode the mode bits into a 10 character string like LS does
491 ***********************************************************************/
493 char *encode_mode(mode_t mode, char *buf)
497 *cp++ = S_ISDIR(mode) ? 'd' : S_ISBLK(mode) ? 'b' : S_ISCHR(mode) ? 'c' :
498 S_ISLNK(mode) ? 'l' : '-';
499 *cp++ = mode & S_IRUSR ? 'r' : '-';
500 *cp++ = mode & S_IWUSR ? 'w' : '-';
501 *cp++ = (mode & S_ISUID
502 ? (mode & S_IXUSR ? 's' : 'S')
503 : (mode & S_IXUSR ? 'x' : '-'));
504 *cp++ = mode & S_IRGRP ? 'r' : '-';
505 *cp++ = mode & S_IWGRP ? 'w' : '-';
506 *cp++ = (mode & S_ISGID
507 ? (mode & S_IXGRP ? 's' : 'S')
508 : (mode & S_IXGRP ? 'x' : '-'));
509 *cp++ = mode & S_IROTH ? 'r' : '-';
510 *cp++ = mode & S_IWOTH ? 'w' : '-';
511 *cp++ = (mode & S_ISVTX
512 ? (mode & S_IXOTH ? 't' : 'T')
513 : (mode & S_IXOTH ? 'x' : '-'));
519 int do_shell_expansion(char *name)
521 /* ****FIXME***** this should work for Win32 too */
531 void (*istat)(int), (*qstat)(int);
533 char echout[PATH_MAX + 256];
535 static char meta[] = "~\\$[]*?`'<>\"";
539 /* Check if any meta characters are present */
541 for (i = 0; i < len; i++) {
542 if (strchr(name, meta[i])) {
550 /* If the filename appears to be a DOS filename,
551 convert all backward slashes \ to Unix path
552 separators / and insert a \ infront of spaces. */
554 if (len >= 3 && name[1] == ':' && name[2] == '\\') {
555 for (i=2; i<len; i++)
560 /* Pass string off to the shell for interpretation */
563 switch(pid = fork()) {
569 if ((shellcmd = getenv("SHELL")) == NULL)
570 shellcmd = "/bin/sh";
571 close(1); dup(pfd[1]); /* attach pipes to stdin and stdout */
572 close(2); dup(pfd[1]);
573 for (i = 3; i < 32; i++) /* close everything else */
575 strcpy(echout, "echo "); /* form echo command */
576 strcat(echout, name);
577 execl(shellcmd, shellcmd, "-c", echout, NULL); /* give to shell */
578 exit(127); /* shouldn't get here */
580 default: /* parent */
581 /* read output from child */
582 i = read(pfd[0], echout, sizeof echout);
583 echout[--i] = 0; /* set end of string */
584 /* look for first word or first line. */
586 if (echout[i] == ' ' || echout[i] == '\n')
587 echout[i] = 0; /* keep only first one */
589 istat = signal(SIGINT, SIG_IGN);
590 qstat = signal(SIGQUIT, SIG_IGN);
591 /* wait for child to exit */
592 while ((wpid = wait(&waitstatus)) != pid && wpid != -1)
594 signal(SIGINT, istat);
595 signal(SIGQUIT, qstat);
596 strcpy(name, echout);
600 close(pfd[0]); /* close pipe */
608 #if MSC | MSDOS | __WATCOMC__
610 char prefix[100], *env, *getenv();
612 /* Home directory reference? */
613 if (*name == '~' && (env=getenv("HOME"))) {
614 strcpy(prefix, env); /* copy HOME directory name */
615 name++; /* skip over ~ in name */
616 strcat(prefix, name);
617 name--; /* get back to beginning */
618 strcpy(name, prefix); /* move back into name */
626 static void build_argc_argv(char *cmd, int *bargc, char *bargv[], int max_arg);
629 * Run an external program. Optionally wait a specified number
630 * of seconds. Program killed if wait exceeded. Optionally
631 * return the output from the program (normally a single line).
633 int run_program(char *prog, int wait, POOLMEM *results)
637 pid_t pid1, pid2 = 0;
639 char *bargv[MAX_ARGV];
643 build_argc_argv(prog, &bargc, bargv, MAX_ARGV);
645 printf("argc=%d\n", bargc);
647 for (i=0; i<bargc; i++) {
648 printf("argc=%d argv=%s\n", i, bargv[i]);
652 if (results && pipe(pfd) == -1) {
655 /* Start worker process */
656 switch (pid1 = fork()) {
661 // printf("execl of %s\n", prog);
663 close(1); dup(pfd[1]); /* attach pipes to stdin and stdout */
664 close(2); dup(pfd[1]);
666 execvp(bargv[0], bargv);
667 exit(errno); /* shouldn't get here */
669 default: /* parent */
670 /* start timer process */
672 switch (pid2=fork()) {
675 case 0: /* child 2 */
676 /* Time the worker process */
678 if (kill(pid1, SIGTERM) == 0) { /* time expired kill it */
684 default: /* parent */
689 /* Parent continues here */
692 i = read(pfd[0], results, sizeof_pool_memory(results) - 1);
696 results[i] = 0; /* set end of string */
698 /* wait for worker child to exit */
701 wpid = waitpid(pid1, &chldstatus, 0);
702 if (wpid == pid1 || (errno != EINTR)) {
706 if (WIFEXITED(chldstatus))
707 stat = WEXITSTATUS(chldstatus);
710 kill(pid2, SIGKILL); /* kill off timer process */
711 waitpid(pid2, &chldstatus, 0); /* reap timer process */
714 close(pfd[0]); /* close pipe */
723 * Build argc and argv from a string
725 static void build_argc_argv(char *cmd, int *bargc, char *bargv[], int max_argv)
732 for (i=0; i<max_argv; i++)
737 while (*p && (*p == ' ' || *p == '\t'))
744 while (*p && argc < MAX_ARGV) {
747 while (*q && *q != '\"')
751 while (*q && *q != ' ')
758 while (*p && (*p == ' ' || *p == '\t'))
769 /* MAKESESSIONKEY -- Generate session key with optional start
770 key. If mode is TRUE, the key will be
771 translated to a string, otherwise it is
772 returned as 16 binary bytes.
774 from SpeakFreely by John Walker */
776 void makeSessionKey(char *key, char *seed, int mode)
779 struct MD5Context md5c;
780 unsigned char md5key[16], md5key1[16];
788 /* The following creates a seed for the session key generator
789 based on a collection of volatile and environment-specific
790 information unlikely to be vulnerable (as a whole) to an
791 exhaustive search attack. If one of these items isn't
792 available on your machine, replace it with something
793 equivalent or, if you like, just delete it. */
795 sprintf(s + strlen(s), "%lu", (unsigned long) getpid());
796 sprintf(s + strlen(s), "%lu", (unsigned long) getppid());
797 getcwd(s + strlen(s), 256);
798 sprintf(s + strlen(s), "%lu", (unsigned long) clock());
799 sprintf(s + strlen(s), "%lu", (unsigned long) time(NULL));
801 sysinfo(SI_HW_SERIAL,s + strlen(s), 12);
803 #ifdef HAVE_GETHOSTID
804 sprintf(s + strlen(s), "%lu", (unsigned long) gethostid());
806 #ifdef HAVE_GETDOMAINNAME
807 getdomainname(s + strlen(s), 256);
809 gethostname(s + strlen(s), 256);
810 sprintf(s + strlen(s), "%u", (unsigned)getuid());
811 sprintf(s + strlen(s), "%u", (unsigned)getgid());
813 MD5Update(&md5c, (unsigned char *)s, strlen(s));
814 MD5Final(md5key, &md5c);
815 sprintf(s + strlen(s), "%lu", (unsigned long) ((time(NULL) + 65121) ^ 0x375F));
817 MD5Update(&md5c, (unsigned char *)s, strlen(s));
818 MD5Final(md5key1, &md5c);
819 #define nextrand (md5key[j] ^ md5key1[j])
821 for (j = k = 0; j < 16; j++) {
822 unsigned char rb = nextrand;
824 #define Rad16(x) ((x) + 'A')
825 key[k++] = Rad16((rb >> 4) & 0xF);
826 key[k++] = Rad16(rb & 0xF);
834 for (j = 0; j < 16; j++) {