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)
436 str = _("Unknown Type");
443 * Convert Job Level into a string
445 char *job_level_to_str(int level)
454 str = _("Incremental");
457 str = _("Differential");
465 case L_VERIFY_CATALOG:
466 str = _("Verify Catalog");
469 str = _("Verify Init Catalog");
471 case L_VERIFY_VOLUME_TO_CATALOG:
472 str = _("Verify Volume to Catalog");
475 str = _("Verify Data");
478 str = _("Unknown Job Level");
485 /***********************************************************************
486 * Encode the mode bits into a 10 character string like LS does
487 ***********************************************************************/
489 char *encode_mode(mode_t mode, char *buf)
493 *cp++ = S_ISDIR(mode) ? 'd' : S_ISBLK(mode) ? 'b' : S_ISCHR(mode) ? 'c' :
494 S_ISLNK(mode) ? 'l' : '-';
495 *cp++ = mode & S_IRUSR ? 'r' : '-';
496 *cp++ = mode & S_IWUSR ? 'w' : '-';
497 *cp++ = (mode & S_ISUID
498 ? (mode & S_IXUSR ? 's' : 'S')
499 : (mode & S_IXUSR ? 'x' : '-'));
500 *cp++ = mode & S_IRGRP ? 'r' : '-';
501 *cp++ = mode & S_IWGRP ? 'w' : '-';
502 *cp++ = (mode & S_ISGID
503 ? (mode & S_IXGRP ? 's' : 'S')
504 : (mode & S_IXGRP ? 'x' : '-'));
505 *cp++ = mode & S_IROTH ? 'r' : '-';
506 *cp++ = mode & S_IWOTH ? 'w' : '-';
507 *cp++ = (mode & S_ISVTX
508 ? (mode & S_IXOTH ? 't' : 'T')
509 : (mode & S_IXOTH ? 'x' : '-'));
515 extern char *getuser(uid_t uid);
516 extern char *getgroup(gid_t gid);
518 void print_ls_output(char *fname, char *lname, int type, struct stat *statp)
524 p = encode_mode(statp->st_mode, buf);
525 n = sprintf(p, " %2d ", (uint32_t)statp->st_nlink);
527 n = sprintf(p, "%-8.8s %-8.8s", getuser(statp->st_uid), getgroup(statp->st_gid));
529 n = sprintf(p, "%8ld ", statp->st_size);
531 p = encode_time(statp->st_ctime, p);
536 if (type == FT_LNK) {
551 int do_shell_expansion(char *name)
553 /* ****FIXME***** this should work for Win32 too */
563 void (*istat)(int), (*qstat)(int);
565 char echout[PATH_MAX + 256];
567 static char meta[] = "~\\$[]*?`'<>\"";
571 /* Check if any meta characters are present */
573 for (i = 0; i < len; i++) {
574 if (strchr(name, meta[i])) {
582 /* If the filename appears to be a DOS filename,
583 convert all backward slashes \ to Unix path
584 separators / and insert a \ infront of spaces. */
586 if (len >= 3 && name[1] == ':' && name[2] == '\\') {
587 for (i=2; i<len; i++)
592 /* Pass string off to the shell for interpretation */
595 switch(pid = fork()) {
601 if ((shellcmd = getenv("SHELL")) == NULL)
602 shellcmd = "/bin/sh";
603 close(1); dup(pfd[1]); /* attach pipes to stdin and stdout */
604 close(2); dup(pfd[1]);
605 for (i = 3; i < 32; i++) /* close everything else */
607 strcpy(echout, "echo "); /* form echo command */
608 strcat(echout, name);
609 execl(shellcmd, shellcmd, "-c", echout, NULL); /* give to shell */
610 exit(127); /* shouldn't get here */
612 default: /* parent */
613 /* read output from child */
614 i = read(pfd[0], echout, sizeof echout);
615 echout[--i] = 0; /* set end of string */
616 /* look for first word or first line. */
618 if (echout[i] == ' ' || echout[i] == '\n')
619 echout[i] = 0; /* keep only first one */
621 istat = signal(SIGINT, SIG_IGN);
622 qstat = signal(SIGQUIT, SIG_IGN);
623 /* wait for child to exit */
624 while ((wpid = wait(&waitstatus)) != pid && wpid != -1)
626 signal(SIGINT, istat);
627 signal(SIGQUIT, qstat);
628 strcpy(name, echout);
632 close(pfd[0]); /* close pipe */
640 #if MSC | MSDOS | __WATCOMC__
642 char prefix[100], *env, *getenv();
644 /* Home directory reference? */
645 if (*name == '~' && (env=getenv("HOME"))) {
646 strcpy(prefix, env); /* copy HOME directory name */
647 name++; /* skip over ~ in name */
648 strcat(prefix, name);
649 name--; /* get back to beginning */
650 strcpy(name, prefix); /* move back into name */
658 static void build_argc_argv(char *cmd, int *bargc, char *bargv[], int max_arg);
661 * Run an external program. Optionally wait a specified number
662 * of seconds. Program killed if wait exceeded. Optionally
663 * return the output from the program (normally a single line).
665 int run_program(char *prog, int wait, POOLMEM *results)
669 pid_t pid1, pid2 = 0;
671 char *bargv[MAX_ARGV];
675 build_argc_argv(prog, &bargc, bargv, MAX_ARGV);
677 printf("argc=%d\n", bargc);
679 for (i=0; i<bargc; i++) {
680 printf("argc=%d argv=%s\n", i, bargv[i]);
684 if (results && pipe(pfd) == -1) {
687 /* Start worker process */
688 switch (pid1 = fork()) {
693 // printf("execl of %s\n", prog);
695 close(1); dup(pfd[1]); /* attach pipes to stdin and stdout */
696 close(2); dup(pfd[1]);
698 execvp(bargv[0], bargv);
699 exit(errno); /* shouldn't get here */
701 default: /* parent */
702 /* start timer process */
704 switch (pid2=fork()) {
707 case 0: /* child 2 */
708 /* Time the worker process */
710 if (kill(pid1, SIGTERM) == 0) { /* time expired kill it */
716 default: /* parent */
721 /* Parent continues here */
724 i = read(pfd[0], results, sizeof_pool_memory(results) - 1);
728 results[i] = 0; /* set end of string */
730 /* wait for worker child to exit */
733 wpid = waitpid(pid1, &chldstatus, 0);
734 if (wpid == pid1 || (errno != EINTR)) {
738 if (WIFEXITED(chldstatus))
739 stat = WEXITSTATUS(chldstatus);
742 kill(pid2, SIGKILL); /* kill off timer process */
743 waitpid(pid2, &chldstatus, 0); /* reap timer process */
746 close(pfd[0]); /* close pipe */
755 * Build argc and argv from a string
757 static void build_argc_argv(char *cmd, int *bargc, char *bargv[], int max_argv)
764 for (i=0; i<max_argv; i++)
769 while (*p && (*p == ' ' || *p == '\t'))
776 while (*p && argc < MAX_ARGV) {
779 while (*q && *q != '\"')
783 while (*q && *q != ' ')
790 while (*p && (*p == ' ' || *p == '\t'))