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