]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/util.c
Fix DiskToCatalog seg fault
[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_DATA:
271       str = _("Verify Data");
272       break;
273    default:
274       str = _("Unknown Job Level");
275       break;
276    }
277    return str;
278 }
279
280
281 /***********************************************************************
282  * Encode the mode bits into a 10 character string like LS does
283  ***********************************************************************/
284
285 char *encode_mode(mode_t mode, char *buf)
286 {
287   char *cp = buf;  
288
289   *cp++ = S_ISDIR(mode) ? 'd' : S_ISBLK(mode)  ? 'b' : S_ISCHR(mode)  ? 'c' :
290           S_ISLNK(mode) ? 'l' : S_ISFIFO(mode) ? 'f' : S_ISSOCK(mode) ? 's' : '-';
291   *cp++ = mode & S_IRUSR ? 'r' : '-';
292   *cp++ = mode & S_IWUSR ? 'w' : '-';
293   *cp++ = (mode & S_ISUID
294                ? (mode & S_IXUSR ? 's' : 'S')
295                : (mode & S_IXUSR ? 'x' : '-'));
296   *cp++ = mode & S_IRGRP ? 'r' : '-';
297   *cp++ = mode & S_IWGRP ? 'w' : '-';
298   *cp++ = (mode & S_ISGID
299                ? (mode & S_IXGRP ? 's' : 'S')
300                : (mode & S_IXGRP ? 'x' : '-'));
301   *cp++ = mode & S_IROTH ? 'r' : '-';
302   *cp++ = mode & S_IWOTH ? 'w' : '-';
303   *cp++ = (mode & S_ISVTX
304                ? (mode & S_IXOTH ? 't' : 'T')
305                : (mode & S_IXOTH ? 'x' : '-'));
306   *cp = '\0';
307   return cp;
308 }
309
310
311 int do_shell_expansion(char *name, int name_len)
312 {
313    static char meta[] = "~\\$[]*?`'<>\"";
314    bool found = false;
315    int len, i, stat;
316    POOLMEM *cmd;
317    BPIPE *bpipe;
318    char line[MAXSTRING];
319    char *shellcmd;
320
321    /* Check if any meta characters are present */
322    len = strlen(meta);
323    for (i = 0; i < len; i++) {
324       if (strchr(name, meta[i])) {
325          found = true;
326          break;
327       }
328    }
329    if (found) {
330       cmd =  get_pool_memory(PM_FNAME);
331       /* look for shell */
332       if ((shellcmd = getenv("SHELL")) == NULL) {
333          shellcmd = "/bin/sh";
334       }
335       pm_strcpy(&cmd, shellcmd);
336       pm_strcat(&cmd, " -c \"echo ");
337       pm_strcat(&cmd, name);
338       pm_strcat(&cmd, "\"");
339       Dmsg1(400, "Send: %s\n", cmd);
340       bpipe = open_bpipe(cmd, 0, "r");
341       *line = 0;
342       fgets(line, sizeof(line), bpipe->rfd);
343       strip_trailing_junk(line);
344       stat = close_bpipe(bpipe);
345       Dmsg2(400, "stat=%d got: %s\n", stat, line);
346       free_pool_memory(cmd);
347       if (stat == 0) {
348          bstrncpy(name, line, name_len);
349       }
350    }
351    return 1;
352 }
353
354
355 /*  MAKESESSIONKEY  --  Generate session key with optional start
356                         key.  If mode is TRUE, the key will be
357                         translated to a string, otherwise it is
358                         returned as 16 binary bytes.
359
360     from SpeakFreely by John Walker */
361
362 void make_session_key(char *key, char *seed, int mode)
363 {
364      int j, k;
365      struct MD5Context md5c;
366      unsigned char md5key[16], md5key1[16];
367      char s[1024];
368
369      s[0] = 0;
370      if (seed != NULL) {
371         strcat(s, seed);
372      }
373
374      /* The following creates a seed for the session key generator
375         based on a collection of volatile and environment-specific
376         information unlikely to be vulnerable (as a whole) to an
377         exhaustive search attack.  If one of these items isn't
378         available on your machine, replace it with something
379         equivalent or, if you like, just delete it. */
380
381      sprintf(s + strlen(s), "%lu", (unsigned long) getpid());
382      sprintf(s + strlen(s), "%lu", (unsigned long) getppid());
383      getcwd(s + strlen(s), 256);
384      sprintf(s + strlen(s), "%lu", (unsigned long) clock());
385      sprintf(s + strlen(s), "%lu", (unsigned long) time(NULL));
386 #ifdef Solaris
387      sysinfo(SI_HW_SERIAL,s + strlen(s), 12);
388 #endif
389 #ifdef HAVE_GETHOSTID
390      sprintf(s + strlen(s), "%lu", (unsigned long) gethostid());
391 #endif
392 #ifdef HAVE_GETDOMAINNAME
393      getdomainname(s + strlen(s), 256);
394 #endif
395      gethostname(s + strlen(s), 256);
396      sprintf(s + strlen(s), "%u", (unsigned)getuid());
397      sprintf(s + strlen(s), "%u", (unsigned)getgid());
398      MD5Init(&md5c);
399      MD5Update(&md5c, (unsigned char *)s, strlen(s));
400      MD5Final(md5key, &md5c);
401      sprintf(s + strlen(s), "%lu", (unsigned long) ((time(NULL) + 65121) ^ 0x375F));
402      MD5Init(&md5c);
403      MD5Update(&md5c, (unsigned char *)s, strlen(s));
404      MD5Final(md5key1, &md5c);
405 #define nextrand    (md5key[j] ^ md5key1[j])
406      if (mode) {
407         for (j = k = 0; j < 16; j++) {
408             unsigned char rb = nextrand;
409
410 #define Rad16(x) ((x) + 'A')
411             key[k++] = Rad16((rb >> 4) & 0xF);
412             key[k++] = Rad16(rb & 0xF);
413 #undef Rad16
414             if (j & 1) {
415                  key[k++] = '-';
416             }
417         }
418         key[--k] = 0;
419      } else {
420         for (j = 0; j < 16; j++) {
421             key[j] = nextrand;
422         }
423      }
424 }
425 #undef nextrand
426
427
428
429 /*
430  * Edit job codes into main command line
431  *  %% = %
432  *  %c = Client's name
433  *  %d = Director's name
434  *  %e = Job Exit code
435  *  %i = JobId
436  *  %j = Unique Job name
437  *  %l = job level
438  *  %n = Unadorned Job name
439  *  %t = Job type (Backup, ...)
440  *  %r = Recipients
441  *
442  *  omsg = edited output message
443  *  imsg = input string containing edit codes (%x)
444  *  to = recepients list 
445  *
446  */
447 POOLMEM *edit_job_codes(JCR *jcr, char *omsg, char *imsg, char *to)   
448 {
449    char *p, *str;
450    char add[20];
451    char name[MAX_NAME_LENGTH];
452
453    *omsg = 0;
454    Dmsg1(200, "edit_job_codes: %s\n", imsg);
455    for (p=imsg; *p; p++) {
456       if (*p == '%') {
457          switch (*++p) {
458          case '%':
459             str = "%";
460             break;
461          case 'c':
462             str = jcr->client_name;
463             if (!str) {
464                str = "";
465             }
466             break;
467          case 'd':
468             str = my_name;            /* Director's name */
469             break;
470          case 'e':
471             str = job_status_to_str(jcr->JobStatus); 
472             break;
473          case 'i':
474             bsnprintf(add, sizeof(add), "%d", jcr->JobId);
475             str = add;
476             break;
477          case 'j':                    /* Job name */
478             str = jcr->Job;
479             break;
480          case 'l':
481             str = job_level_to_str(jcr->JobLevel);
482             break;
483          case 'n':
484              bstrncpy(name, jcr->Job, sizeof(name));
485              /* There are three periods after the Job name */
486              for (int i=0; i<3; i++) {
487                 if ((str=strrchr(name, '.')) != NULL) {
488                     *str = 0;
489                 }
490              }
491              str = name;
492              break;
493          case 'r':
494             str = to;
495             break;
496          case 't':
497             str = job_type_to_str(jcr->JobType);
498             break;
499          default:
500             add[0] = '%';
501             add[1] = *p;
502             add[2] = 0;
503             str = add;
504             break;
505          }
506       } else {
507          add[0] = *p;
508          add[1] = 0;
509          str = add;
510       }
511       Dmsg1(1200, "add_str %s\n", str);
512       pm_strcat(&omsg, str);
513       Dmsg1(1200, "omsg=%s\n", omsg);
514    }
515    return omsg;
516 }
517
518 void set_working_directory(char *wd)
519 {
520    struct stat stat_buf; 
521
522    if (wd == NULL) {
523       Emsg0(M_ERROR_TERM, 0, _("Working directory not defined. Cannot continue.\n"));
524    }
525    if (stat(wd, &stat_buf) != 0) {
526       Emsg1(M_ERROR_TERM, 0, _("Working Directory: \"%s\" not found. Cannot continue.\n"),
527          wd);
528    }
529    if (!S_ISDIR(stat_buf.st_mode)) {
530       Emsg1(M_ERROR_TERM, 0, _("Working Directory: \"%s\" is not a directory. Cannot continue.\n"),
531          wd);
532    }
533    working_directory = wd;            /* set global */
534 }