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