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 poolmem message (msg)
327 * return new message pointer. The base of the pool memory
330 void add_str_to_pool_mem(POOLMEM **base, char **msg, char *str)
332 int len = strlen(str) + 1;
336 *base = check_pool_memory_size(*base, len);
337 m = *base - b + *msg;
346 * Convert a JobStatus code into a human readable form
348 void jobstatus_to_ascii(int JobStatus, char *msg, int maxlen)
350 char *termstat, jstat[2];
357 case JS_ErrorTerminated:
358 termstat = _("Error");
361 termstat = _("Non-fatal error");
364 termstat = _("Cancelled");
367 termstat = _("Verify differences");
370 jstat[0] = last_job.JobStatus;
375 strncpy(msg, termstat, maxlen);
380 * Convert Job Termination Status into a string
382 char *job_status_to_str(int stat)
390 case JS_ErrorTerminated:
395 str = _("Fatal Error");
398 str = _("Cancelled");
401 str = _("Differences");
404 str = _("Unknown term code");
412 * Convert Job Type into a string
414 char *job_type_to_str(int type)
431 str = _("Unknown Type");
438 * Convert Job Level into a string
440 char *job_level_to_str(int level)
449 str = _("Incremental");
452 str = _("Differential");
460 case L_VERIFY_CATALOG:
461 str = _("Verify Catalog");
464 str = _("Verify Init Catalog");
466 case L_VERIFY_VOLUME_TO_CATALOG:
467 str = _("Verify Volume to Catalog");
470 str = _("Verify Data");
473 str = _("Unknown Job Level");
480 /***********************************************************************
481 * Encode the mode bits into a 10 character string like LS does
482 ***********************************************************************/
484 char *encode_mode(mode_t mode, char *buf)
488 *cp++ = S_ISDIR(mode) ? 'd' : S_ISBLK(mode) ? 'b' : S_ISCHR(mode) ? 'c' :
489 S_ISLNK(mode) ? 'l' : '-';
490 *cp++ = mode & S_IRUSR ? 'r' : '-';
491 *cp++ = mode & S_IWUSR ? 'w' : '-';
492 *cp++ = (mode & S_ISUID
493 ? (mode & S_IXUSR ? 's' : 'S')
494 : (mode & S_IXUSR ? 'x' : '-'));
495 *cp++ = mode & S_IRGRP ? 'r' : '-';
496 *cp++ = mode & S_IWGRP ? 'w' : '-';
497 *cp++ = (mode & S_ISGID
498 ? (mode & S_IXGRP ? 's' : 'S')
499 : (mode & S_IXGRP ? 'x' : '-'));
500 *cp++ = mode & S_IROTH ? 'r' : '-';
501 *cp++ = mode & S_IWOTH ? 'w' : '-';
502 *cp++ = (mode & S_ISVTX
503 ? (mode & S_IXOTH ? 't' : 'T')
504 : (mode & S_IXOTH ? 'x' : '-'));
510 extern char *getuser(uid_t uid);
511 extern char *getgroup(gid_t gid);
513 void print_ls_output(char *fname, char *lname, int type, struct stat *statp)
519 p = encode_mode(statp->st_mode, buf);
520 n = sprintf(p, " %2d ", (uint32_t)statp->st_nlink);
522 n = sprintf(p, "%-8.8s %-8.8s", getuser(statp->st_uid), getgroup(statp->st_gid));
524 n = sprintf(p, "%8ld ", statp->st_size);
526 p = encode_time(statp->st_ctime, p);
531 if (type == FT_LNK) {
546 int do_shell_expansion(char *name)
548 /* ****FIXME***** this should work for Win32 too */
558 void (*istat)(int), (*qstat)(int);
560 char echout[PATH_MAX + 256];
562 static char meta[] = "~\\$[]*?`'<>\"";
566 /* Check if any meta characters are present */
568 for (i = 0; i < len; i++) {
569 if (strchr(name, meta[i])) {
577 /* If the filename appears to be a DOS filename,
578 convert all backward slashes \ to Unix path
579 separators / and insert a \ infront of spaces. */
581 if (len >= 3 && name[1] == ':' && name[2] == '\\') {
582 for (i=2; i<len; i++)
587 /* Pass string off to the shell for interpretation */
590 switch(pid = fork()) {
596 if ((shellcmd = getenv("SHELL")) == NULL)
597 shellcmd = "/bin/sh";
598 close(1); dup(pfd[1]); /* attach pipes to stdin and stdout */
599 close(2); dup(pfd[1]);
600 for (i = 3; i < 32; i++) /* close everything else */
602 strcpy(echout, "echo "); /* form echo command */
603 strcat(echout, name);
604 execl(shellcmd, shellcmd, "-c", echout, NULL); /* give to shell */
605 exit(127); /* shouldn't get here */
607 default: /* parent */
608 /* read output from child */
609 i = read(pfd[0], echout, sizeof echout);
610 echout[--i] = 0; /* set end of string */
611 /* look for first word or first line. */
613 if (echout[i] == ' ' || echout[i] == '\n')
614 echout[i] = 0; /* keep only first one */
616 istat = signal(SIGINT, SIG_IGN);
617 qstat = signal(SIGQUIT, SIG_IGN);
618 /* wait for child to exit */
619 while ((wpid = wait(&waitstatus)) != pid && wpid != -1)
621 signal(SIGINT, istat);
622 signal(SIGQUIT, qstat);
623 strcpy(name, echout);
627 close(pfd[0]); /* close pipe */
635 #if MSC | MSDOS | __WATCOMC__
637 char prefix[100], *env, *getenv();
639 /* Home directory reference? */
640 if (*name == '~' && (env=getenv("HOME"))) {
641 strcpy(prefix, env); /* copy HOME directory name */
642 name++; /* skip over ~ in name */
643 strcat(prefix, name);
644 name--; /* get back to beginning */
645 strcpy(name, prefix); /* move back into name */
653 static void build_argc_argv(char *cmd, int *bargc, char *bargv[], int max_arg);
656 * Run an external program. Optionally wait a specified number
657 * of seconds. Program killed if wait exceeded. Optionally
658 * return the output from the program (normally a single line).
660 int run_program(char *prog, int wait, POOLMEM *results)
666 char *bargv[MAX_ARGV];
670 build_argc_argv(prog, &bargc, bargv, MAX_ARGV);
672 printf("argc=%d\n", bargc);
674 for (i=0; i<bargc; i++) {
675 printf("argc=%d argv=%s\n", i, bargv[i]);
679 if (results && pipe(pfd) == -1) {
682 /* Start worker process */
683 switch (pid1 = fork()) {
688 // printf("execl of %s\n", prog);
690 close(1); dup(pfd[1]); /* attach pipes to stdin and stdout */
691 close(2); dup(pfd[1]);
693 execvp(bargv[0], bargv);
694 exit(errno); /* shouldn't get here */
696 default: /* parent */
697 /* start timer process */
699 switch (pid2=fork()) {
702 case 0: /* child 2 */
703 /* Time the worker process */
705 if (kill(pid1, SIGTERM) == 0) { /* time expired kill it */
711 default: /* parent */
716 /* Parent continues here */
719 i = read(pfd[0], results, sizeof_pool_memory(results) - 1);
723 results[i] = 0; /* set end of string */
725 /* wait for worker child to exit */
728 wpid = waitpid(pid1, &chldstatus, 0);
729 if (wpid == pid1 || (errno != EINTR)) {
733 if (WIFEXITED(chldstatus))
734 stat = WEXITSTATUS(chldstatus);
737 kill(pid2, SIGKILL); /* kill off timer process */
738 waitpid(pid2, &chldstatus, 0); /* reap timer process */
741 close(pfd[0]); /* close pipe */
750 * Build argc and argv from a string
752 static void build_argc_argv(char *cmd, int *bargc, char *bargv[], int max_argv)
759 for (i=0; i<max_argv; i++)
764 while (*p && (*p == ' ' || *p == '\t'))
771 while (*p && argc < MAX_ARGV) {
774 while (*q && *q != '\"')
778 while (*q && *q != ' ')
785 while (*p && (*p == ' ' || *p == '\t'))