]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/util.c
4433febb4f2e559190200a67100d50aeff7c6774
[bacula/bacula] / bacula / src / lib / util.c
1 /*
2  *   util.c  miscellaneous utility subroutines for Bacula
3  * 
4  *    Kern Sibbald, MM
5  *
6  *   Version $Id$
7  */
8
9 /*
10    Copyright (C) 2000, 2001, 2002 Kern Sibbald and John Walker
11
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.
16
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.
21
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,
25    MA 02111-1307, USA.
26
27  */
28
29 #include "bacula.h"
30 #include "jcr.h"
31 #include "findlib/find.h"
32
33 /*
34  * Various Bacula Utility subroutines
35  *
36  */
37
38 /* Return true of buffer has all zero bytes */
39 int is_buf_zero(char *buf, int len)
40 {
41    uint64_t *ip = (uint64_t *)buf;
42    char *p;
43    int i, len64, done, rem;
44
45    /* Optimize by checking uint64_t for zero */
46    len64 = len >> sizeof(uint64_t);
47    for (i=0; i < len64; i++) {
48       if (ip[i] != 0) {
49          return 0;
50       }
51    }
52    done = len64 << sizeof(uint64_t);  /* bytes already checked */
53    p = buf + done;
54    rem = len - done;
55    for (i = 0; i < rem; i++) {
56       if (p[i] != 0) {
57          return 0;
58       }
59    }
60    return 1;
61 }
62
63
64 /* Convert a string in place to lower case */
65 void lcase(char *str)
66 {
67    while (*str) {
68       if (B_ISUPPER(*str))
69          *str = tolower((int)(*str));
70        str++;
71    }
72 }
73
74 /* Convert spaces to non-space character. 
75  * This makes scanf of fields containing spaces easier.
76  */
77 void
78 bash_spaces(char *str)
79 {
80    while (*str) {
81       if (*str == ' ')
82          *str = 0x1;
83       str++;
84    }
85 }
86
87 /* Convert non-space characters (0x1) back into spaces */
88 void
89 unbash_spaces(char *str)
90 {
91    while (*str) {
92      if (*str == 0x1)
93         *str = ' ';
94      str++;
95    }
96 }
97
98 /* Strip any trailing junk from the command */
99 void strip_trailing_junk(char *cmd)
100 {
101    char *p;
102    p = cmd + strlen(cmd) - 1;
103
104    /* strip trailing junk from command */
105    while ((p >= cmd) && (*p == '\n' || *p == '\r' || *p == ' '))
106       *p-- = 0;
107 }
108
109 /* Strip any trailing slashes from a directory path */
110 void strip_trailing_slashes(char *dir)
111 {
112    char *p;
113    p = dir + strlen(dir) - 1;
114
115    /* strip trailing slashes */
116    while ((p >= dir) && (*p == '/'))
117       *p-- = 0;
118 }
119
120 /*
121  * Skip spaces
122  *  Returns: 0 on failure (EOF)             
123  *           1 on success
124  *           new address in passed parameter 
125  */
126 int skip_spaces(char **msg)
127 {
128    char *p = *msg;
129    if (!p) {
130       return 0;
131    }
132    while (*p && *p == ' ') {
133       p++;
134    }
135    *msg = p;
136    return *p ? 1 : 0;
137 }
138
139 /*
140  * Skip nonspaces
141  *  Returns: 0 on failure (EOF)             
142  *           1 on success
143  *           new address in passed parameter 
144  */
145 int skip_nonspaces(char **msg)
146 {
147    char *p = *msg;
148
149    if (!p) {
150       return 0;
151    }
152    while (*p && *p != ' ') {
153       p++;
154    }
155    *msg = p;
156    return *p ? 1 : 0;
157 }
158
159 /* folded search for string - case insensitive */
160 int
161 fstrsch(char *a, char *b)   /* folded case search */
162 {
163    register char *s1,*s2;
164    register char c1, c2;
165
166    s1=a;
167    s2=b;
168    while (*s1) {                      /* do it the fast way */
169       if ((*s1++ | 0x20) != (*s2++ | 0x20))
170          return 0;                    /* failed */
171    }
172    while (*a) {                       /* do it over the correct slow way */
173       if (B_ISUPPER(c1 = *a)) {
174          c1 = tolower((int)c1);
175       }
176       if (B_ISUPPER(c2 = *b)) {
177          c2 = tolower((int)c2);
178       }
179       if (c1 != c2) {
180          return 0;
181       }
182       a++;
183       b++;
184    }
185    return 1;
186 }
187
188
189 char *encode_time(time_t time, char *buf)
190 {
191    struct tm tm;
192    int n = 0;
193
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);
198    }
199    return buf+n;
200 }
201
202 /*
203  * Concatenate a string (str) onto a pool memory buffer pm
204  */
205 void pm_strcat(POOLMEM **pm, char *str)
206 {
207    int pmlen = strlen(*pm);
208    int len = strlen(str) + 1;
209
210    *pm = check_pool_memory_size(*pm, pmlen + len);
211    memcpy(*pm+pmlen, str, len);
212 }
213
214
215 /*
216  * Copy a string (str) into a pool memory buffer pm
217  */
218 void pm_strcpy(POOLMEM **pm, char *str)
219 {
220    int len = strlen(str) + 1;
221
222    *pm = check_pool_memory_size(*pm, len);
223    memcpy(*pm, str, len);
224 }
225
226
227 /*
228  * Convert a JobStatus code into a human readable form
229  */
230 void jobstatus_to_ascii(int JobStatus, char *msg, int maxlen)
231 {
232    char *termstat, jstat[2];
233
234    switch (JobStatus) {
235       case JS_Terminated:
236          termstat = _("OK");
237          break;
238      case JS_FatalError:
239      case JS_ErrorTerminated:
240          termstat = _("Error");
241          break;
242      case JS_Error:
243          termstat = _("Non-fatal error");
244          break;
245      case JS_Canceled:
246          termstat = _("Canceled");
247          break;
248      case JS_Differences:
249          termstat = _("Verify differences");
250          break;
251      default:
252          jstat[0] = last_job.JobStatus;
253          jstat[1] = 0;
254          termstat = jstat;
255          break;
256    }
257    bstrncpy(msg, termstat, maxlen);
258 }
259
260 /*
261  * Convert Job Termination Status into a string
262  */
263 char *job_status_to_str(int stat) 
264 {
265    char *str;
266
267    switch (stat) {
268    case JS_Terminated:
269       str = _("OK");
270       break;
271    case JS_ErrorTerminated:
272    case JS_Error:
273       str = _("Error");
274       break;
275    case JS_FatalError:
276       str = _("Fatal Error");
277       break;
278    case JS_Canceled:
279       str = _("Canceled");
280       break;
281    case JS_Differences:
282       str = _("Differences");
283       break;
284    default:
285       str = _("Unknown term code");
286       break;
287    }
288    return str;
289 }
290
291
292 /*
293  * Convert Job Type into a string
294  */
295 char *job_type_to_str(int type) 
296 {
297    char *str;
298
299    switch (type) {
300    case JT_BACKUP:
301       str = _("Backup");
302       break;
303    case JT_VERIFY:
304       str = _("Verify");
305       break;
306    case JT_RESTORE:
307       str = _("Restore");
308       break;
309    case JT_ADMIN:
310       str = _("Admin");
311       break;
312    default:
313       str = _("Unknown Type");
314       break;
315    }
316    return str;
317 }
318
319 /*
320  * Convert Job Level into a string
321  */
322 char *job_level_to_str(int level) 
323 {
324    char *str;
325
326    switch (level) {
327    case L_BASE:
328       str = _("Base");
329    case L_FULL:
330       str = _("Full");
331       break;
332    case L_INCREMENTAL:
333       str = _("Incremental");
334       break;
335    case L_DIFFERENTIAL:
336       str = _("Differential");
337       break;
338    case L_SINCE:
339       str = _("Since");
340       break;
341    case L_VERIFY_CATALOG:
342       str = _("Verify Catalog");
343       break;
344    case L_VERIFY_INIT:
345       str = _("Verify Init Catalog");
346       break;
347    case L_VERIFY_VOLUME_TO_CATALOG:
348       str = _("Verify Volume to Catalog");
349       break;
350    case L_VERIFY_DATA:
351       str = _("Verify Data");
352       break;
353    default:
354       str = _("Unknown Job Level");
355       break;
356    }
357    return str;
358 }
359
360
361 /***********************************************************************
362  * Encode the mode bits into a 10 character string like LS does
363  ***********************************************************************/
364
365 char *encode_mode(mode_t mode, char *buf)
366 {
367   char *cp = buf;  
368
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' : '-'));
386   *cp = '\0';
387   return cp;
388 }
389
390
391 int do_shell_expansion(char *name, int name_len)
392 {
393 /*  ****FIXME***** this should work for Win32 too */
394 #define UNIX
395 #ifdef UNIX
396 #ifndef PATH_MAX
397 #define PATH_MAX 512
398 #endif
399
400    int pid, wpid, stat;
401    int waitstatus;
402    char *shellcmd;
403    int i;
404    char echout[PATH_MAX + 256];
405    int pfd[2];
406    static char meta[] = "~\\$[]*?`'<>\"";
407    int found = FALSE;
408    int len;
409
410    /* Check if any meta characters are present */
411    len = strlen(meta);
412    for (i = 0; i < len; i++) {
413       if (strchr(name, meta[i])) {
414          found = TRUE;
415          break;
416       }
417    }
418    stat = 0;
419    if (found) {
420 #ifdef nt
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. */
424        len = strlen(name);
425        if (len >= 3 && name[1] == ':' && name[2] == '\\') {
426           for (i=2; i<len; i++)
427              if (name[i] == '\\')
428                 name[i] = '/';
429        }
430 #else
431        /* Pass string off to the shell for interpretation */
432        if (pipe(pfd) == -1)
433           return 0;
434        switch(pid = fork()) {
435        case -1:
436           break;
437
438        case 0:                            /* child */
439           /* look for shell */
440           if ((shellcmd = getenv("SHELL")) == NULL) {
441              shellcmd = "/bin/sh";
442           }
443 #ifdef xxx
444           close(1); dup(pfd[1]);          /* attach pipes to stdout and stderr */
445           close(2); dup(pfd[1]);
446           for (i = 3; i < 32; i++)        /* close everything else */
447              close(i);
448 #endif
449           close(pfd[0]);                  /* close stdin */
450           dup2(pfd[1], 1);                /* attach to stdout */
451           dup2(pfd[1], 2);                /* and stderr */
452           strcpy(echout, "echo ");        /* form echo command */
453           bstrncat(echout, name, sizeof(echout));
454           execl(shellcmd, shellcmd, "-c", echout, NULL); /* give to shell */
455           exit(127);                      /* shouldn't get here */
456
457        default:                           /* parent */
458           /* read output from child */
459           echout[0] = 0;
460           do {
461              i = read(pfd[0], echout, sizeof echout);
462           } while (i == -1 && errno == EINTR); 
463
464           if (i > 0) {
465              echout[--i] = 0;                /* set end of string */
466              /* look for first line. */
467              while (--i >= 0) {
468                 if (echout[i] == '\n') {
469                    echout[i] = 0;            /* keep only first one */
470                 }
471              }
472           }
473           /* wait for child to exit */
474           while ((wpid = wait(&waitstatus)) != pid && wpid != -1)
475              { ; }
476           strip_trailing_junk(echout);
477           if (strlen(echout) > 0) {
478              bstrncpy(name, echout, name_len);
479           }
480           stat = 1;
481           break;
482        }
483        close(pfd[0]);                     /* close pipe */
484        close(pfd[1]);
485 #endif /* nt */
486    }
487    return stat;
488
489 #endif /* UNIX */
490
491 #if  MSC | MSDOS | __WATCOMC__
492
493    char prefix[100], *env, *getenv();
494
495    /* Home directory reference? */
496    if (*name == '~' && (env=getenv("HOME"))) {
497       strcpy(prefix, env);            /* copy HOME directory name */
498       name++;                         /* skip over ~ in name */
499       strcat(prefix, name);
500       name--;                         /* get back to beginning */
501       strcpy(name, prefix);           /* move back into name */
502    }
503    return 1;
504 #endif
505
506 }
507
508
509 /*  MAKESESSIONKEY  --  Generate session key with optional start
510                         key.  If mode is TRUE, the key will be
511                         translated to a string, otherwise it is
512                         returned as 16 binary bytes.
513
514     from SpeakFreely by John Walker */
515
516 void makeSessionKey(char *key, char *seed, int mode)
517 {
518      int j, k;
519      struct MD5Context md5c;
520      unsigned char md5key[16], md5key1[16];
521      char s[1024];
522
523      s[0] = 0;
524      if (seed != NULL) {
525         strcat(s, seed);
526      }
527
528      /* The following creates a seed for the session key generator
529         based on a collection of volatile and environment-specific
530         information unlikely to be vulnerable (as a whole) to an
531         exhaustive search attack.  If one of these items isn't
532         available on your machine, replace it with something
533         equivalent or, if you like, just delete it. */
534
535      sprintf(s + strlen(s), "%lu", (unsigned long) getpid());
536      sprintf(s + strlen(s), "%lu", (unsigned long) getppid());
537      getcwd(s + strlen(s), 256);
538      sprintf(s + strlen(s), "%lu", (unsigned long) clock());
539      sprintf(s + strlen(s), "%lu", (unsigned long) time(NULL));
540 #ifdef Solaris
541      sysinfo(SI_HW_SERIAL,s + strlen(s), 12);
542 #endif
543 #ifdef HAVE_GETHOSTID
544      sprintf(s + strlen(s), "%lu", (unsigned long) gethostid());
545 #endif
546 #ifdef HAVE_GETDOMAINNAME
547      getdomainname(s + strlen(s), 256);
548 #endif
549      gethostname(s + strlen(s), 256);
550      sprintf(s + strlen(s), "%u", (unsigned)getuid());
551      sprintf(s + strlen(s), "%u", (unsigned)getgid());
552      MD5Init(&md5c);
553      MD5Update(&md5c, (unsigned char *)s, strlen(s));
554      MD5Final(md5key, &md5c);
555      sprintf(s + strlen(s), "%lu", (unsigned long) ((time(NULL) + 65121) ^ 0x375F));
556      MD5Init(&md5c);
557      MD5Update(&md5c, (unsigned char *)s, strlen(s));
558      MD5Final(md5key1, &md5c);
559 #define nextrand    (md5key[j] ^ md5key1[j])
560      if (mode) {
561         for (j = k = 0; j < 16; j++) {
562             unsigned char rb = nextrand;
563
564 #define Rad16(x) ((x) + 'A')
565             key[k++] = Rad16((rb >> 4) & 0xF);
566             key[k++] = Rad16(rb & 0xF);
567 #undef Rad16
568             if (j & 1) {
569                  key[k++] = '-';
570             }
571         }
572         key[--k] = 0;
573      } else {
574         for (j = 0; j < 16; j++) {
575             key[j] = nextrand;
576         }
577      }
578 }
579 #undef nextrand
580
581
582
583 /*
584  * Edit job codes into main command line
585  *  %% = %
586  *  %j = Job name
587  *  %t = Job type (Backup, ...)
588  *  %e = Job Exit code
589  *  %i = JobId
590  *  %l = job level
591  *  %c = Client's name
592  *  %r = Recipients
593  *  %d = Director's name
594  *
595  *  omsg = edited output message
596  *  imsg = input string containing edit codes (%x)
597  *  to = recepients list 
598  *
599  */
600 POOLMEM *edit_job_codes(JCR *jcr, char *omsg, char *imsg, char *to)   
601 {
602    char *p, *str;
603    char add[20];
604
605    *omsg = 0;
606    Dmsg1(200, "edit_job_codes: %s\n", imsg);
607    for (p=imsg; *p; p++) {
608       if (*p == '%') {
609          switch (*++p) {
610          case '%':
611             str = "%";
612             break;
613          case 'c':
614             str = jcr->client_name;
615             if (!str) {
616                str = "";
617             }
618             break;
619          case 'd':
620             str = my_name;            /* Director's name */
621             break;
622          case 'e':
623             str = job_status_to_str(jcr->JobStatus); 
624             break;
625          case 'i':
626             sprintf(add, "%d", jcr->JobId);
627             str = add;
628             break;
629          case 'j':                    /* Job name */
630             str = jcr->Job;
631             break;
632          case 'l':
633             str = job_level_to_str(jcr->JobLevel);
634             break;
635          case 'r':
636             str = to;
637             break;
638          case 't':
639             str = job_type_to_str(jcr->JobType);
640             break;
641          default:
642             add[0] = '%';
643             add[1] = *p;
644             add[2] = 0;
645             str = add;
646             break;
647          }
648       } else {
649          add[0] = *p;
650          add[1] = 0;
651          str = add;
652       }
653       Dmsg1(1200, "add_str %s\n", str);
654       pm_strcat(&omsg, str);
655       Dmsg1(1200, "omsg=%s\n", omsg);
656    }
657    return omsg;
658 }
659
660 /* 
661  * Return next argument from command line.  Note, this
662  * routine is destructive.
663  */
664 char *next_arg(char **s)
665 {
666    char *p, *q, *n;
667    int in_quote = 0;
668
669    /* skip past spaces to next arg */
670    for (p=*s; *p && *p == ' '; ) {
671       p++;
672    }    
673    Dmsg1(400, "Next arg=%s\n", p);
674    for (n = q = p; *p ; ) {
675       if (*p == '\\') {
676          p++;
677          if (*p) {
678             *q++ = *p++;
679          } else {
680             *q++ = *p;
681          }
682          continue;
683       }
684       if (*p == '"') {                  /* start or end of quote */
685          if (in_quote) {
686             p++;                        /* skip quote */
687             in_quote = 0;
688             continue;
689          }
690          in_quote = 1;
691          p++;
692          continue;
693       }
694       if (!in_quote && *p == ' ') {     /* end of field */
695          p++;
696          break;
697       }
698       *q++ = *p++;
699    }
700    *q = 0;
701    *s = p;
702    Dmsg2(400, "End arg=%s next=%s\n", n, p);
703    return n;
704 }   
705
706 /*
707  * This routine parses the input command line.
708  * It makes a copy in args, then builds an
709  *  argc, argv like list where
710  *    
711  *  argc = count of arguments
712  *  argk[i] = argument keyword (part preceding =)
713  *  argv[i] = argument value (part after =)
714  *
715  *  example:  arg1 arg2=abc arg3=
716  *
717  *  argc = c
718  *  argk[0] = arg1
719  *  argv[0] = NULL
720  *  argk[1] = arg2
721  *  argv[1] = abc
722  *  argk[2] = arg3
723  *  argv[2] = 
724  */
725
726 void parse_command_args(POOLMEM *cmd, POOLMEM *args, int *argc, 
727                         char **argk, char **argv) 
728 {
729    char *p, *q, *n;
730    int len;
731
732    len = strlen(cmd) + 1;
733    args = check_pool_memory_size(args, len);
734    bstrncpy(args, cmd, len);
735    strip_trailing_junk(args);
736    *argc = 0;
737    p = args;
738    /* Pick up all arguments */
739    while (*argc < MAX_CMD_ARGS) {
740       n = next_arg(&p);   
741       if (*n) {
742          argk[*argc] = n;
743          argv[(*argc)++] = NULL;
744       } else {
745          break;
746       }
747    }
748    /* Separate keyword and value */
749    for (int i=0; i < *argc; i++) {
750       p = strchr(argk[i], '=');
751       if (p) {
752          *p++ = 0;                    /* terminate keyword and point to value */
753          /* Unquote quoted values */
754          if (*p == '"') {
755             for (n = q = ++p; *p && *p != '"'; ) {
756                if (*p == '\\') {
757                   p++;
758                }
759                *q++ = *p++;
760             }
761             *q = 0;                   /* terminate string */
762             p = n;                    /* point to string */
763          }
764          if (strlen(p) > MAX_NAME_LENGTH-1) {
765             p[MAX_NAME_LENGTH-1] = 0; /* truncate to max len */
766          }
767       }
768       argv[i] = p;                    /* save ptr to value or NULL */
769    }
770 #ifdef xxxx
771    for (i=0; i<argc; i++) {
772       Dmsg3(000, "Arg %d: kw=%s val=%s\n", i, argk[i], argv[i]?argv[i]:"NULL");
773    }
774 #endif
775 }
776
777 void set_working_directory(char *wd)
778 {
779    struct stat stat_buf; 
780
781    if (wd == NULL) {
782       Emsg0(M_ERROR_TERM, 0, _("Working directory not defined. Cannot continue.\n"));
783    }
784    if (stat(wd, &stat_buf) != 0) {
785       Emsg1(M_ERROR_TERM, 0, _("Working Directory: \"%s\" not found. Cannot continue.\n"),
786          wd);
787    }
788    if (!S_ISDIR(stat_buf.st_mode)) {
789       Emsg1(M_ERROR_TERM, 0, _("Working Directory: \"%s\" is not a directory. Cannot continue.\n"),
790          wd);
791    }
792    working_directory = wd;            /* set global */
793 }