]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/util.c
30c5a39cd1ca7a76344658029f0644c228df7971
[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;
42    char *p;
43    int i, len64, done, rem;
44
45    if (buf[0] != 0) {
46       return 0;
47    }
48    ip = (uint64_t *)buf;
49    /* Optimize by checking uint64_t for zero */
50    len64 = len / sizeof(uint64_t);
51    for (i=0; i < len64; i++) {
52       if (ip[i] != 0) {
53          return 0;
54       }
55    }
56    done = len64 * sizeof(uint64_t);  /* bytes already checked */
57    p = buf + done;
58    rem = len - done;
59    for (i = 0; i < rem; i++) {
60       if (p[i] != 0) {
61          return 0;
62       }
63    }
64    return 1;
65 }
66
67
68 /* Convert a string in place to lower case */
69 void lcase(char *str)
70 {
71    while (*str) {
72       if (B_ISUPPER(*str))
73          *str = tolower((int)(*str));
74        str++;
75    }
76 }
77
78 /* Convert spaces to non-space character. 
79  * This makes scanf of fields containing spaces easier.
80  */
81 void
82 bash_spaces(char *str)
83 {
84    while (*str) {
85       if (*str == ' ')
86          *str = 0x1;
87       str++;
88    }
89 }
90
91 /* Convert non-space characters (0x1) back into spaces */
92 void
93 unbash_spaces(char *str)
94 {
95    while (*str) {
96      if (*str == 0x1)
97         *str = ' ';
98      str++;
99    }
100 }
101
102
103 char *encode_time(time_t time, char *buf)
104 {
105    struct tm tm;
106    int n = 0;
107
108    if (localtime_r(&time, &tm)) {
109       n = sprintf(buf, "%04d-%02d-%02d %02d:%02d:%02d",
110                    tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
111                    tm.tm_hour, tm.tm_min, tm.tm_sec);
112    }
113    return buf+n;
114 }
115
116 /*
117  * Concatenate a string (str) onto a pool memory buffer pm
118  */
119 int pm_strcat(POOLMEM **pm, char *str)
120 {
121    int pmlen = strlen(*pm);
122    int len = strlen(str) + 1;
123
124    *pm = check_pool_memory_size(*pm, pmlen + len);
125    memcpy(*pm+pmlen, str, len);
126    return pmlen + len - 1;
127 }
128
129
130 /*
131  * Copy a string (str) into a pool memory buffer pm
132  */
133 int pm_strcpy(POOLMEM **pm, char *str)
134 {
135    int len = strlen(str) + 1;
136
137    *pm = check_pool_memory_size(*pm, len);
138    memcpy(*pm, str, len);
139    return len - 1;
140 }
141
142
143 /*
144  * Convert a JobStatus code into a human readable form
145  */
146 void jobstatus_to_ascii(int JobStatus, char *msg, int maxlen)
147 {
148    char *termstat;
149    char buf[100];
150
151    switch (JobStatus) {
152       case JS_Terminated:
153          termstat = _("OK");
154          break;
155      case JS_FatalError:
156      case JS_ErrorTerminated:
157          termstat = _("Error");
158          break;
159      case JS_Error:
160          termstat = _("Non-fatal error");
161          break;
162      case JS_Canceled:
163          termstat = _("Canceled");
164          break;
165      case JS_Differences:
166          termstat = _("Verify differences");
167          break;
168      default:
169          if (JobStatus == 0) {
170             buf[0] = 0;
171          } else {
172             bsnprintf(buf, sizeof(buf), _("Unknown Job termination status=%d"), JobStatus);
173          }
174          termstat = buf;
175          break;
176    }
177    bstrncpy(msg, termstat, maxlen);
178 }
179
180 /*
181  * Convert Job Termination Status into a string
182  */
183 char *job_status_to_str(int stat) 
184 {
185    char *str;
186
187    switch (stat) {
188    case JS_Terminated:
189       str = _("OK");
190       break;
191    case JS_ErrorTerminated:
192    case JS_Error:
193       str = _("Error");
194       break;
195    case JS_FatalError:
196       str = _("Fatal Error");
197       break;
198    case JS_Canceled:
199       str = _("Canceled");
200       break;
201    case JS_Differences:
202       str = _("Differences");
203       break;
204    default:
205       str = _("Unknown term code");
206       break;
207    }
208    return str;
209 }
210
211
212 /*
213  * Convert Job Type into a string
214  */
215 char *job_type_to_str(int type) 
216 {
217    char *str;
218
219    switch (type) {
220    case JT_BACKUP:
221       str = _("Backup");
222       break;
223    case JT_VERIFY:
224       str = _("Verify");
225       break;
226    case JT_RESTORE:
227       str = _("Restore");
228       break;
229    case JT_ADMIN:
230       str = _("Admin");
231       break;
232    default:
233       str = _("Unknown Type");
234       break;
235    }
236    return str;
237 }
238
239 /*
240  * Convert Job Level into a string
241  */
242 char *job_level_to_str(int level) 
243 {
244    char *str;
245
246    switch (level) {
247    case L_BASE:
248       str = _("Base");
249    case L_FULL:
250       str = _("Full");
251       break;
252    case L_INCREMENTAL:
253       str = _("Incremental");
254       break;
255    case L_DIFFERENTIAL:
256       str = _("Differential");
257       break;
258    case L_SINCE:
259       str = _("Since");
260       break;
261    case L_VERIFY_CATALOG:
262       str = _("Verify Catalog");
263       break;
264    case L_VERIFY_INIT:
265       str = _("Verify Init Catalog");
266       break;
267    case L_VERIFY_VOLUME_TO_CATALOG:
268       str = _("Verify Volume to Catalog");
269       break;
270    case L_VERIFY_DISK_TO_CATALOG:
271       str = _("Verify Disk to Catalog");
272       break;
273    case L_VERIFY_DATA:
274       str = _("Verify Data");
275       break;
276    default:
277       str = _("Unknown Job Level");
278       break;
279    }
280    return str;
281 }
282
283
284 /***********************************************************************
285  * Encode the mode bits into a 10 character string like LS does
286  ***********************************************************************/
287
288 char *encode_mode(mode_t mode, char *buf)
289 {
290   char *cp = buf;  
291
292   *cp++ = S_ISDIR(mode) ? 'd' : S_ISBLK(mode)  ? 'b' : S_ISCHR(mode)  ? 'c' :
293           S_ISLNK(mode) ? 'l' : S_ISFIFO(mode) ? 'f' : S_ISSOCK(mode) ? 's' : '-';
294   *cp++ = mode & S_IRUSR ? 'r' : '-';
295   *cp++ = mode & S_IWUSR ? 'w' : '-';
296   *cp++ = (mode & S_ISUID
297                ? (mode & S_IXUSR ? 's' : 'S')
298                : (mode & S_IXUSR ? 'x' : '-'));
299   *cp++ = mode & S_IRGRP ? 'r' : '-';
300   *cp++ = mode & S_IWGRP ? 'w' : '-';
301   *cp++ = (mode & S_ISGID
302                ? (mode & S_IXGRP ? 's' : 'S')
303                : (mode & S_IXGRP ? 'x' : '-'));
304   *cp++ = mode & S_IROTH ? 'r' : '-';
305   *cp++ = mode & S_IWOTH ? 'w' : '-';
306   *cp++ = (mode & S_ISVTX
307                ? (mode & S_IXOTH ? 't' : 'T')
308                : (mode & S_IXOTH ? 'x' : '-'));
309   *cp = '\0';
310   return cp;
311 }
312
313
314 int do_shell_expansion(char *name, int name_len)
315 {
316    static char meta[] = "~\\$[]*?`'<>\"";
317    bool found = false;
318    int len, i, stat;
319    POOLMEM *cmd;
320    BPIPE *bpipe;
321    char line[MAXSTRING];
322    char *shellcmd;
323
324    /* Check if any meta characters are present */
325    len = strlen(meta);
326    for (i = 0; i < len; i++) {
327       if (strchr(name, meta[i])) {
328          found = true;
329          break;
330       }
331    }
332    if (found) {
333       cmd =  get_pool_memory(PM_FNAME);
334       /* look for shell */
335       if ((shellcmd = getenv("SHELL")) == NULL) {
336          shellcmd = "/bin/sh";
337       }
338       pm_strcpy(&cmd, shellcmd);
339       pm_strcat(&cmd, " -c \"echo ");
340       pm_strcat(&cmd, name);
341       pm_strcat(&cmd, "\"");
342       Dmsg1(400, "Send: %s\n", cmd);
343       bpipe = open_bpipe(cmd, 0, "r");
344       *line = 0;
345       fgets(line, sizeof(line), bpipe->rfd);
346       strip_trailing_junk(line);
347       stat = close_bpipe(bpipe);
348       Dmsg2(400, "stat=%d got: %s\n", stat, line);
349       free_pool_memory(cmd);
350       if (stat == 0) {
351          bstrncpy(name, line, name_len);
352       }
353    }
354    return 1;
355 }
356
357
358 /*  MAKESESSIONKEY  --  Generate session key with optional start
359                         key.  If mode is TRUE, the key will be
360                         translated to a string, otherwise it is
361                         returned as 16 binary bytes.
362
363     from SpeakFreely by John Walker */
364
365 void make_session_key(char *key, char *seed, int mode)
366 {
367      int j, k;
368      struct MD5Context md5c;
369      unsigned char md5key[16], md5key1[16];
370      char s[1024];
371
372      s[0] = 0;
373      if (seed != NULL) {
374         strcat(s, seed);
375      }
376
377      /* The following creates a seed for the session key generator
378         based on a collection of volatile and environment-specific
379         information unlikely to be vulnerable (as a whole) to an
380         exhaustive search attack.  If one of these items isn't
381         available on your machine, replace it with something
382         equivalent or, if you like, just delete it. */
383
384      sprintf(s + strlen(s), "%lu", (unsigned long) getpid());
385      sprintf(s + strlen(s), "%lu", (unsigned long) getppid());
386      getcwd(s + strlen(s), 256);
387      sprintf(s + strlen(s), "%lu", (unsigned long) clock());
388      sprintf(s + strlen(s), "%lu", (unsigned long) time(NULL));
389 #ifdef Solaris
390      sysinfo(SI_HW_SERIAL,s + strlen(s), 12);
391 #endif
392 #ifdef HAVE_GETHOSTID
393      sprintf(s + strlen(s), "%lu", (unsigned long) gethostid());
394 #endif
395 #ifdef HAVE_GETDOMAINNAME
396      getdomainname(s + strlen(s), 256);
397 #endif
398      gethostname(s + strlen(s), 256);
399      sprintf(s + strlen(s), "%u", (unsigned)getuid());
400      sprintf(s + strlen(s), "%u", (unsigned)getgid());
401      MD5Init(&md5c);
402      MD5Update(&md5c, (unsigned char *)s, strlen(s));
403      MD5Final(md5key, &md5c);
404      sprintf(s + strlen(s), "%lu", (unsigned long) ((time(NULL) + 65121) ^ 0x375F));
405      MD5Init(&md5c);
406      MD5Update(&md5c, (unsigned char *)s, strlen(s));
407      MD5Final(md5key1, &md5c);
408 #define nextrand    (md5key[j] ^ md5key1[j])
409      if (mode) {
410         for (j = k = 0; j < 16; j++) {
411             unsigned char rb = nextrand;
412
413 #define Rad16(x) ((x) + 'A')
414             key[k++] = Rad16((rb >> 4) & 0xF);
415             key[k++] = Rad16(rb & 0xF);
416 #undef Rad16
417             if (j & 1) {
418                  key[k++] = '-';
419             }
420         }
421         key[--k] = 0;
422      } else {
423         for (j = 0; j < 16; j++) {
424             key[j] = nextrand;
425         }
426      }
427 }
428 #undef nextrand
429
430
431
432 /*
433  * Edit job codes into main command line
434  *  %% = %
435  *  %c = Client's name
436  *  %d = Director's name
437  *  %e = Job Exit code
438  *  %i = JobId
439  *  %j = Unique Job name
440  *  %l = job level
441  *  %n = Unadorned Job name
442  *  %t = Job type (Backup, ...)
443  *  %r = Recipients
444  *
445  *  omsg = edited output message
446  *  imsg = input string containing edit codes (%x)
447  *  to = recepients list 
448  *
449  */
450 POOLMEM *edit_job_codes(JCR *jcr, char *omsg, char *imsg, char *to)   
451 {
452    char *p, *str;
453    char add[20];
454    char name[MAX_NAME_LENGTH];
455
456    *omsg = 0;
457    Dmsg1(200, "edit_job_codes: %s\n", imsg);
458    for (p=imsg; *p; p++) {
459       if (*p == '%') {
460          switch (*++p) {
461          case '%':
462             str = "%";
463             break;
464          case 'c':
465             str = jcr->client_name;
466             if (!str) {
467                str = "";
468             }
469             break;
470          case 'd':
471             str = my_name;            /* Director's name */
472             break;
473          case 'e':
474             str = job_status_to_str(jcr->JobStatus); 
475             break;
476          case 'i':
477             bsnprintf(add, sizeof(add), "%d", jcr->JobId);
478             str = add;
479             break;
480          case 'j':                    /* Job name */
481             str = jcr->Job;
482             break;
483          case 'l':
484             str = job_level_to_str(jcr->JobLevel);
485             break;
486          case 'n':
487              bstrncpy(name, jcr->Job, sizeof(name));
488              /* There are three periods after the Job name */
489              for (int i=0; i<3; i++) {
490                 if ((str=strrchr(name, '.')) != NULL) {
491                     *str = 0;
492                 }
493              }
494              str = name;
495              break;
496          case 'r':
497             str = to;
498             break;
499          case 't':
500             str = job_type_to_str(jcr->JobType);
501             break;
502          default:
503             add[0] = '%';
504             add[1] = *p;
505             add[2] = 0;
506             str = add;
507             break;
508          }
509       } else {
510          add[0] = *p;
511          add[1] = 0;
512          str = add;
513       }
514       Dmsg1(1200, "add_str %s\n", str);
515       pm_strcat(&omsg, str);
516       Dmsg1(1200, "omsg=%s\n", omsg);
517    }
518    return omsg;
519 }
520
521 void set_working_directory(char *wd)
522 {
523    struct stat stat_buf; 
524
525    if (wd == NULL) {
526       Emsg0(M_ERROR_TERM, 0, _("Working directory not defined. Cannot continue.\n"));
527    }
528    if (stat(wd, &stat_buf) != 0) {
529       Emsg1(M_ERROR_TERM, 0, _("Working Directory: \"%s\" not found. Cannot continue.\n"),
530          wd);
531    }
532    if (!S_ISDIR(stat_buf.st_mode)) {
533       Emsg1(M_ERROR_TERM, 0, _("Working Directory: \"%s\" is not a directory. Cannot continue.\n"),
534          wd);
535    }
536    working_directory = wd;            /* set global */
537 }