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
38 /* Return true of buffer has all zero bytes */
39 int is_buf_zero(char *buf, int len)
41 uint64_t *ip = (uint64_t *)buf;
43 int i, len64, done, rem;
45 /* Optimize by checking uint64_t for zero */
46 len64 = len >> sizeof(uint64_t);
47 for (i=0; i < len64; i++) {
52 done = len64 << sizeof(uint64_t); /* bytes already checked */
55 for (i = 0; i < rem; i++) {
64 /* Convert a string in place to lower case */
69 *str = tolower((int)(*str));
74 /* Convert spaces to non-space character.
75 * This makes scanf of fields containing spaces easier.
78 bash_spaces(char *str)
87 /* Convert non-space characters (0x1) back into spaces */
89 unbash_spaces(char *str)
98 /* Strip any trailing junk from the command */
99 void strip_trailing_junk(char *cmd)
102 p = cmd + strlen(cmd) - 1;
104 /* strip trailing junk from command */
105 while ((p >= cmd) && (*p == '\n' || *p == '\r' || *p == ' '))
109 /* Strip any trailing slashes from a directory path */
110 void strip_trailing_slashes(char *dir)
113 p = dir + strlen(dir) - 1;
115 /* strip trailing slashes */
116 while ((p >= dir) && (*p == '/'))
122 * Returns: 0 on failure (EOF)
124 * new address in passed parameter
126 int skip_spaces(char **msg)
132 while (*p && *p == ' ') {
141 * Returns: 0 on failure (EOF)
143 * new address in passed parameter
145 int skip_nonspaces(char **msg)
152 while (*p && *p != ' ') {
159 /* folded search for string - case insensitive */
161 fstrsch(char *a, char *b) /* folded case search */
163 register char *s1,*s2;
164 register char c1, c2;
168 while (*s1) { /* do it the fast way */
169 if ((*s1++ | 0x20) != (*s2++ | 0x20))
170 return 0; /* failed */
172 while (*a) { /* do it over the correct slow way */
173 if (B_ISUPPER(c1 = *a)) {
174 c1 = tolower((int)c1);
176 if (B_ISUPPER(c2 = *b)) {
177 c2 = tolower((int)c2);
189 char *encode_time(time_t time, char *buf)
194 if (localtime_r(&time, &tm)) {
195 n = sprintf(buf, "%04d-%02d-%02d %02d:%02d:%02d",
196 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
197 tm.tm_hour, tm.tm_min, tm.tm_sec);
203 * Concatenate a string (str) onto a pool memory buffer pm
205 void pm_strcat(POOLMEM **pm, char *str)
207 int pmlen = strlen(*pm);
208 int len = strlen(str) + 1;
210 *pm = check_pool_memory_size(*pm, pmlen + len);
211 memcpy(*pm+pmlen, str, len);
216 * Copy a string (str) into a pool memory buffer pm
218 void pm_strcpy(POOLMEM **pm, char *str)
220 int len = strlen(str) + 1;
222 *pm = check_pool_memory_size(*pm, len);
223 memcpy(*pm, str, len);
228 * Convert a JobStatus code into a human readable form
230 void jobstatus_to_ascii(int JobStatus, char *msg, int maxlen)
232 char *termstat, jstat[2];
239 case JS_ErrorTerminated:
240 termstat = _("Error");
243 termstat = _("Non-fatal error");
246 termstat = _("Canceled");
249 termstat = _("Verify differences");
252 jstat[0] = last_job.JobStatus;
257 bstrncpy(msg, termstat, maxlen);
261 * Convert Job Termination Status into a string
263 char *job_status_to_str(int stat)
271 case JS_ErrorTerminated:
276 str = _("Fatal Error");
282 str = _("Differences");
285 str = _("Unknown term code");
293 * Convert Job Type into a string
295 char *job_type_to_str(int type)
313 str = _("Unknown Type");
320 * Convert Job Level into a string
322 char *job_level_to_str(int level)
333 str = _("Incremental");
336 str = _("Differential");
341 case L_VERIFY_CATALOG:
342 str = _("Verify Catalog");
345 str = _("Verify Init Catalog");
347 case L_VERIFY_VOLUME_TO_CATALOG:
348 str = _("Verify Volume to Catalog");
351 str = _("Verify Data");
354 str = _("Unknown Job Level");
361 /***********************************************************************
362 * Encode the mode bits into a 10 character string like LS does
363 ***********************************************************************/
365 char *encode_mode(mode_t mode, char *buf)
369 *cp++ = S_ISDIR(mode) ? 'd' : S_ISBLK(mode) ? 'b' : S_ISCHR(mode) ? 'c' :
370 S_ISLNK(mode) ? 'l' : S_ISFIFO(mode) ? 'f' : S_ISSOCK(mode) ? 's' : '-';
371 *cp++ = mode & S_IRUSR ? 'r' : '-';
372 *cp++ = mode & S_IWUSR ? 'w' : '-';
373 *cp++ = (mode & S_ISUID
374 ? (mode & S_IXUSR ? 's' : 'S')
375 : (mode & S_IXUSR ? 'x' : '-'));
376 *cp++ = mode & S_IRGRP ? 'r' : '-';
377 *cp++ = mode & S_IWGRP ? 'w' : '-';
378 *cp++ = (mode & S_ISGID
379 ? (mode & S_IXGRP ? 's' : 'S')
380 : (mode & S_IXGRP ? 'x' : '-'));
381 *cp++ = mode & S_IROTH ? 'r' : '-';
382 *cp++ = mode & S_IWOTH ? 'w' : '-';
383 *cp++ = (mode & S_ISVTX
384 ? (mode & S_IXOTH ? 't' : 'T')
385 : (mode & S_IXOTH ? 'x' : '-'));
391 int do_shell_expansion(char *name, int name_len)
393 /* ****FIXME***** this should work for Win32 too */
404 char echout[PATH_MAX + 256];
406 static char meta[] = "~\\$[]*?`'<>\"";
410 /* Check if any meta characters are present */
412 for (i = 0; i < len; i++) {
413 if (strchr(name, meta[i])) {
421 /* If the filename appears to be a DOS filename,
422 convert all backward slashes \ to Unix path
423 separators / and insert a \ infront of spaces. */
425 if (len >= 3 && name[1] == ':' && name[2] == '\\') {
426 for (i=2; i<len; i++)
431 /* Pass string off to the shell for interpretation */
434 switch(pid = fork()) {
440 if ((shellcmd = getenv("SHELL")) == NULL) {
441 shellcmd = "/bin/sh";
443 close(1); dup(pfd[1]); /* attach pipes to stdin and stdout */
444 close(2); dup(pfd[1]);
445 for (i = 3; i < 32; i++) /* close everything else */
447 strcpy(echout, "echo "); /* form echo command */
448 bstrncat(echout, name, sizeof(echout));
449 execl(shellcmd, shellcmd, "-c", echout, NULL); /* give to shell */
450 exit(127); /* shouldn't get here */
452 default: /* parent */
453 /* read output from child */
455 i = read(pfd[0], echout, sizeof echout);
457 echout[--i] = 0; /* set end of string */
458 /* look for first line. */
460 if (echout[i] == '\n') {
461 echout[i] = 0; /* keep only first one */
465 /* wait for child to exit */
466 while ((wpid = wait(&waitstatus)) != pid && wpid != -1)
468 strip_trailing_junk(echout);
469 if (strlen(echout) > 0) {
470 bstrncpy(name, echout, name_len);
475 close(pfd[0]); /* close pipe */
483 #if MSC | MSDOS | __WATCOMC__
485 char prefix[100], *env, *getenv();
487 /* Home directory reference? */
488 if (*name == '~' && (env=getenv("HOME"))) {
489 strcpy(prefix, env); /* copy HOME directory name */
490 name++; /* skip over ~ in name */
491 strcat(prefix, name);
492 name--; /* get back to beginning */
493 strcpy(name, prefix); /* move back into name */
501 /* MAKESESSIONKEY -- Generate session key with optional start
502 key. If mode is TRUE, the key will be
503 translated to a string, otherwise it is
504 returned as 16 binary bytes.
506 from SpeakFreely by John Walker */
508 void makeSessionKey(char *key, char *seed, int mode)
511 struct MD5Context md5c;
512 unsigned char md5key[16], md5key1[16];
520 /* The following creates a seed for the session key generator
521 based on a collection of volatile and environment-specific
522 information unlikely to be vulnerable (as a whole) to an
523 exhaustive search attack. If one of these items isn't
524 available on your machine, replace it with something
525 equivalent or, if you like, just delete it. */
527 sprintf(s + strlen(s), "%lu", (unsigned long) getpid());
528 sprintf(s + strlen(s), "%lu", (unsigned long) getppid());
529 getcwd(s + strlen(s), 256);
530 sprintf(s + strlen(s), "%lu", (unsigned long) clock());
531 sprintf(s + strlen(s), "%lu", (unsigned long) time(NULL));
533 sysinfo(SI_HW_SERIAL,s + strlen(s), 12);
535 #ifdef HAVE_GETHOSTID
536 sprintf(s + strlen(s), "%lu", (unsigned long) gethostid());
538 #ifdef HAVE_GETDOMAINNAME
539 getdomainname(s + strlen(s), 256);
541 gethostname(s + strlen(s), 256);
542 sprintf(s + strlen(s), "%u", (unsigned)getuid());
543 sprintf(s + strlen(s), "%u", (unsigned)getgid());
545 MD5Update(&md5c, (unsigned char *)s, strlen(s));
546 MD5Final(md5key, &md5c);
547 sprintf(s + strlen(s), "%lu", (unsigned long) ((time(NULL) + 65121) ^ 0x375F));
549 MD5Update(&md5c, (unsigned char *)s, strlen(s));
550 MD5Final(md5key1, &md5c);
551 #define nextrand (md5key[j] ^ md5key1[j])
553 for (j = k = 0; j < 16; j++) {
554 unsigned char rb = nextrand;
556 #define Rad16(x) ((x) + 'A')
557 key[k++] = Rad16((rb >> 4) & 0xF);
558 key[k++] = Rad16(rb & 0xF);
566 for (j = 0; j < 16; j++) {
576 * Edit job codes into main command line
579 * %t = Job type (Backup, ...)
585 * %d = Director's name
587 * omsg = edited output message
588 * imsg = input string containing edit codes (%x)
589 * to = recepients list
592 POOLMEM *edit_job_codes(JCR *jcr, char *omsg, char *imsg, char *to)
598 Dmsg1(200, "edit_job_codes: %s\n", imsg);
599 for (p=imsg; *p; p++) {
606 str = jcr->client_name;
612 str = my_name; /* Director's name */
615 str = job_status_to_str(jcr->JobStatus);
618 sprintf(add, "%d", jcr->JobId);
621 case 'j': /* Job name */
625 str = job_level_to_str(jcr->JobLevel);
631 str = job_type_to_str(jcr->JobType);
645 Dmsg1(1200, "add_str %s\n", str);
646 pm_strcat(&omsg, str);
647 Dmsg1(1200, "omsg=%s\n", omsg);
653 * Return next argument from command line. Note, this
654 * routine is destructive.
656 char *next_arg(char **s)
661 /* skip past spaces to next arg */
662 for (p=*s; *p && *p == ' '; ) {
665 Dmsg1(400, "Next arg=%s\n", p);
666 for (n = q = p; *p ; ) {
676 if (*p == '"') { /* start or end of quote */
678 p++; /* skip quote */
686 if (!in_quote && *p == ' ') { /* end of field */
694 Dmsg2(400, "End arg=%s next=%s\n", n, p);
699 * This routine parses the input command line.
700 * It makes a copy in args, then builds an
701 * argc, argv like list where
703 * argc = count of arguments
704 * argk[i] = argument keyword (part preceding =)
705 * argv[i] = argument value (part after =)
707 * example: arg1 arg2=abc arg3=
718 void parse_command_args(POOLMEM *cmd, POOLMEM *args, int *argc,
719 char **argk, char **argv)
724 len = strlen(cmd) + 1;
725 args = check_pool_memory_size(args, len);
726 bstrncpy(args, cmd, len);
727 strip_trailing_junk(args);
730 /* Pick up all arguments */
731 while (*argc < MAX_CMD_ARGS) {
735 argv[(*argc)++] = NULL;
740 /* Separate keyword and value */
741 for (int i=0; i < *argc; i++) {
742 p = strchr(argk[i], '=');
744 *p++ = 0; /* terminate keyword and point to value */
745 /* Unquote quoted values */
747 for (n = q = ++p; *p && *p != '"'; ) {
753 *q = 0; /* terminate string */
754 p = n; /* point to string */
756 if (strlen(p) > MAX_NAME_LENGTH-1) {
757 p[MAX_NAME_LENGTH-1] = 0; /* truncate to max len */
760 argv[i] = p; /* save ptr to value or NULL */
763 for (i=0; i<argc; i++) {
764 Dmsg3(000, "Arg %d: kw=%s val=%s\n", i, argk[i], argv[i]?argv[i]:"NULL");
769 void set_working_directory(char *wd)
771 struct stat stat_buf;
774 Emsg0(M_ERROR_TERM, 0, _("Working directory not defined. Cannot continue.\n"));
776 if (stat(wd, &stat_buf) != 0) {
777 Emsg1(M_ERROR_TERM, 0, _("Working Directory: \"%s\" not found. Cannot continue.\n"),
780 if (!S_ISDIR(stat_buf.st_mode)) {
781 Emsg1(M_ERROR_TERM, 0, _("Working Directory: \"%s\" is not a directory. Cannot continue.\n"),
784 working_directory = wd; /* set global */