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 = (btime_t)strtod(str, NULL);
71 if (errno != 0 || val < 0) {
74 *value = 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);
379 /***********************************************************************
380 * Encode the mode bits into a 10 character string like LS does
381 ***********************************************************************/
383 char *encode_mode(mode_t mode, char *buf)
387 *cp++ = S_ISDIR(mode) ? 'd' : S_ISBLK(mode) ? 'b' : S_ISCHR(mode) ? 'c' :
388 S_ISLNK(mode) ? 'l' : '-';
389 *cp++ = mode & S_IRUSR ? 'r' : '-';
390 *cp++ = mode & S_IWUSR ? 'w' : '-';
391 *cp++ = (mode & S_ISUID
392 ? (mode & S_IXUSR ? 's' : 'S')
393 : (mode & S_IXUSR ? 'x' : '-'));
394 *cp++ = mode & S_IRGRP ? 'r' : '-';
395 *cp++ = mode & S_IWGRP ? 'w' : '-';
396 *cp++ = (mode & S_ISGID
397 ? (mode & S_IXGRP ? 's' : 'S')
398 : (mode & S_IXGRP ? 'x' : '-'));
399 *cp++ = mode & S_IROTH ? 'r' : '-';
400 *cp++ = mode & S_IWOTH ? 'w' : '-';
401 *cp++ = (mode & S_ISVTX
402 ? (mode & S_IXOTH ? 't' : 'T')
403 : (mode & S_IXOTH ? 'x' : '-'));
409 extern char *getuser(uid_t uid);
410 extern char *getgroup(gid_t gid);
412 void print_ls_output(char *fname, char *lname, int type, struct stat *statp)
418 p = encode_mode(statp->st_mode, buf);
419 n = sprintf(p, " %2d ", (uint32_t)statp->st_nlink);
421 n = sprintf(p, "%-8.8s %-8.8s", getuser(statp->st_uid), getgroup(statp->st_gid));
423 n = sprintf(p, "%8ld ", statp->st_size);
425 p = encode_time(statp->st_ctime, p);
430 if (type == FT_LNK) {
445 int do_shell_expansion(char *name)
447 /* ****FIXME***** this should work for Win32 too */
457 void (*istat)(int), (*qstat)(int);
459 char echout[PATH_MAX + 256];
461 static char meta[] = "~\\$[]*?`'<>\"";
465 /* Check if any meta characters are present */
467 for (i = 0; i < len; i++) {
468 if (strchr(name, meta[i])) {
476 /* If the filename appears to be a DOS filename,
477 convert all backward slashes \ to Unix path
478 separators / and insert a \ infront of spaces. */
480 if (len >= 3 && name[1] == ':' && name[2] == '\\') {
481 for (i=2; i<len; i++)
486 /* Pass string off to the shell for interpretation */
489 switch(pid = fork()) {
495 if ((shellcmd = getenv("SHELL")) == NULL)
496 shellcmd = "/bin/sh";
497 close(1); dup(pfd[1]); /* attach pipes to stdin and stdout */
498 close(2); dup(pfd[1]);
499 for (i = 3; i < 32; i++) /* close everything else */
501 strcpy(echout, "echo "); /* form echo command */
502 strcat(echout, name);
503 execl(shellcmd, shellcmd, "-c", echout, NULL); /* give to shell */
504 exit(127); /* shouldn't get here */
506 default: /* parent */
507 /* read output from child */
508 i = read(pfd[0], echout, sizeof echout);
509 echout[--i] = 0; /* set end of string */
510 /* look for first word or first line. */
512 if (echout[i] == ' ' || echout[i] == '\n')
513 echout[i] = 0; /* keep only first one */
515 istat = signal(SIGINT, SIG_IGN);
516 qstat = signal(SIGQUIT, SIG_IGN);
517 /* wait for child to exit */
518 while ((wpid = wait(&waitstatus)) != pid && wpid != -1)
520 signal(SIGINT, istat);
521 signal(SIGQUIT, qstat);
522 strcpy(name, echout);
526 close(pfd[0]); /* close pipe */
534 #if MSC | MSDOS | __WATCOMC__
536 char prefix[100], *env, *getenv();
538 /* Home directory reference? */
539 if (*name == '~' && (env=getenv("HOME"))) {
540 strcpy(prefix, env); /* copy HOME directory name */
541 name++; /* skip over ~ in name */
542 strcat(prefix, name);
543 name--; /* get back to beginning */
544 strcpy(name, prefix); /* move back into name */
552 static char *bargv[MAX_ARGV];
554 static void build_argc_argv(char *cmd);
556 int run_program(char *prog, int wait, POOLMEM *results)
564 build_argc_argv(prog);
566 printf("argc=%d\n", bargc);
568 for (i=0; i<bargc; i++) {
569 printf("argc=%d argv=%s\n", i, bargv[i]);
573 if (results && pipe(pfd) == -1) {
576 /* Start worker process */
577 switch (pid1 = fork()) {
582 // printf("execl of %s\n", prog);
584 close(1); dup(pfd[1]); /* attach pipes to stdin and stdout */
585 close(2); dup(pfd[1]);
587 execvp(bargv[0], bargv);
588 exit(errno); /* shouldn't get here */
590 default: /* parent */
591 /* start timer process */
592 switch (pid2=fork()) {
595 case 0: /* child 2 */
596 /* Time the worker process */
598 if (kill(pid1, SIGTERM) == 0) { /* time expired kill it */
604 default: /* parent */
607 i = read(pfd[0], results, sizeof_pool_memory(results) - 1);
611 results[i] = 0; /* set end of string */
613 /* wait for worker child to exit */
616 wpid = waitpid(pid1, &chldstatus, 0);
617 if (wpid == pid1 || (errno != EINTR)) {
621 if (WIFEXITED(chldstatus))
622 stat = WEXITSTATUS(chldstatus);
624 kill(pid2, SIGKILL); /* kill off timer process */
625 waitpid(pid2, &chldstatus, 0); /* reap timer process */
627 close(pfd[0]); /* close pipe */
638 * Build argc and argv from a string
640 static void build_argc_argv(char *cmd)
646 for (i=0; i<MAX_ARGV; i++)
651 while (*p && (*p == ' ' || *p == '\t'))
658 while (*p && bargc < MAX_ARGV) {
661 while (*q && *q != '\"')
665 while (*q && *q != ' ')
672 while (*p && (*p == ' ' || *p == '\t'))