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