]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/bsys.c
Fix get_basename() -- rewrite
[bacula/bacula] / bacula / src / lib / bsys.c
1 /*
2    Bacula® - The Network Backup Solution
3
4    Copyright (C) 2000-2011 Free Software Foundation Europe e.V.
5
6    The main author of Bacula is Kern Sibbald, with contributions from
7    many others, a complete list can be found in the file AUTHORS.
8    This program is Free Software; you can redistribute it and/or
9    modify it under the terms of version three of the GNU Affero General Public
10    License as published by the Free Software Foundation and included
11    in the file LICENSE.
12
13    This program is distributed in the hope that it will be useful, but
14    WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16    General Public License for more details.
17
18    You should have received a copy of the GNU Affero General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21    02110-1301, USA.
22
23    Bacula® is a registered trademark of Kern Sibbald.
24    The licensor of Bacula is the Free Software Foundation Europe
25    (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
26    Switzerland, email:ftf@fsfeurope.org.
27 */
28 /*
29  * Miscellaneous Bacula memory and thread safe routines
30  *   Generally, these are interfaces to system or standard
31  *   library routines.
32  *
33  *  Bacula utility functions are in util.c
34  *
35  */
36
37 #include "bacula.h"
38
39
40 static pthread_mutex_t timer_mutex = PTHREAD_MUTEX_INITIALIZER;
41 static pthread_cond_t timer = PTHREAD_COND_INITIALIZER;
42
43 /*
44  * This routine will sleep (sec, microsec).  Note, however, that if a
45  *   signal occurs, it will return early.  It is up to the caller
46  *   to recall this routine if he/she REALLY wants to sleep the
47  *   requested time.
48  */
49 int bmicrosleep(int32_t sec, int32_t usec)
50 {
51    struct timespec timeout;
52    struct timeval tv;
53    struct timezone tz;
54    int stat;
55
56    timeout.tv_sec = sec;
57    timeout.tv_nsec = usec * 1000;
58
59 #ifdef HAVE_NANOSLEEP
60    stat = nanosleep(&timeout, NULL);
61    if (!(stat < 0 && errno == ENOSYS)) {
62       return stat;
63    }
64    /* If we reach here it is because nanosleep is not supported by the OS */
65 #endif
66
67    /* Do it the old way */
68    gettimeofday(&tv, &tz);
69    timeout.tv_nsec += tv.tv_usec * 1000;
70    timeout.tv_sec += tv.tv_sec;
71    while (timeout.tv_nsec >= 1000000000) {
72       timeout.tv_nsec -= 1000000000;
73       timeout.tv_sec++;
74    }
75
76    Dmsg2(200, "pthread_cond_timedwait sec=%lld usec=%d\n", sec, usec);
77    /* Note, this unlocks mutex during the sleep */
78    P(timer_mutex);
79    stat = pthread_cond_timedwait(&timer, &timer_mutex, &timeout);
80    if (stat != 0) {
81       berrno be;
82       Dmsg2(200, "pthread_cond_timedwait stat=%d ERR=%s\n", stat,
83          be.bstrerror(stat));
84    }
85    V(timer_mutex);
86    return stat;
87 }
88
89 /*
90  * Guarantee that the string is properly terminated */
91 char *bstrncpy(char *dest, const char *src, int maxlen)
92 {
93    strncpy(dest, src, maxlen-1);
94    dest[maxlen-1] = 0;
95    return dest;
96 }
97
98 /*
99  * Guarantee that the string is properly terminated */
100 char *bstrncpy(char *dest, POOL_MEM &src, int maxlen)
101 {
102    strncpy(dest, src.c_str(), maxlen-1);
103    dest[maxlen-1] = 0;
104    return dest;
105 }
106
107 /*
108  * Note: Here the maxlen is the maximum length permitted
109  *  stored in dest, while on Unix systems, it is the maximum characters
110  *  that may be copied from src.
111  */
112 char *bstrncat(char *dest, const char *src, int maxlen)
113 {
114    int len = strlen(dest);
115    if (len < maxlen-1) {
116       strncpy(dest+len, src, maxlen-len-1);
117    }
118    dest[maxlen-1] = 0;
119    return dest;
120 }
121
122 /*
123  * Note: Here the maxlen is the maximum length permitted
124  *  stored in dest, while on Unix systems, it is the maximum characters
125  *  that may be copied from src.
126  */
127 char *bstrncat(char *dest, POOL_MEM &src, int maxlen)
128 {
129    int len = strlen(dest);
130    if (len < maxlen-1) {
131       strncpy(dest+len, src.c_str(), maxlen-len-1);
132    }
133    dest[maxlen-1] = 0;
134    return dest;
135 }
136
137 /*
138  * Allows one or both pointers to be NULL
139  */
140 bool bstrcmp(const char *s1, const char *s2)
141 {
142    if (s1 == s2) return true;
143    if (s1 == NULL || s2 == NULL) return false;
144    return strcmp(s1, s2) == 0;
145 }
146
147 /*
148  * Get character length of UTF-8 string
149  *
150  * Valid UTF-8 codes
151  * U-00000000 - U-0000007F: 0xxxxxxx 
152  * U-00000080 - U-000007FF: 110xxxxx 10xxxxxx 
153  * U-00000800 - U-0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx 
154  * U-00010000 - U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx 
155  * U-00200000 - U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 
156  * U-04000000 - U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
157  */
158 int cstrlen(const char *str)
159 {
160    uint8_t *p = (uint8_t *)str;
161    int len = 0;
162    if (str == NULL) {
163       return 0;
164    }
165    while (*p) {
166       if ((*p & 0xC0) != 0xC0) {
167          p++;
168          len++;
169          continue;
170       }
171       if ((*p & 0xD0) == 0xC0) {
172          p += 2;
173          len++;
174          continue;
175       }
176       if ((*p & 0xF0) == 0xD0) {
177          p += 3;
178          len++;
179          continue;
180       }
181       if ((*p & 0xF8) == 0xF0) {
182          p += 4;
183          len++;
184          continue;
185       }
186       if ((*p & 0xFC) == 0xF8) {
187          p += 5;
188          len++;
189          continue;
190       }
191       if ((*p & 0xFE) == 0xFC) {
192          p += 6;
193          len++;
194          continue;
195       }
196       p++;                      /* Shouln't get here but must advance */
197    }
198    return len;
199 }
200
201
202
203 #ifndef bmalloc
204 void *bmalloc(size_t size)
205 {
206   void *buf;
207
208 #ifdef SMARTALLOC
209   buf = sm_malloc(file, line, size);
210 #else
211   buf = malloc(size);
212 #endif
213   if (buf == NULL) {
214      berrno be;
215      Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.bstrerror());
216   }
217   return buf;
218 }
219 #endif
220
221 void *b_malloc(const char *file, int line, size_t size)
222 {
223   void *buf;
224
225 #ifdef SMARTALLOC
226   buf = sm_malloc(file, line, size);
227 #else
228   buf = malloc(size);
229 #endif
230   if (buf == NULL) {
231      berrno be;
232      e_msg(file, line, M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.bstrerror());
233   }
234   return buf;
235 }
236
237
238 void bfree(void *buf)
239 {
240 #ifdef SMARTALLOC
241   sm_free(__FILE__, __LINE__, buf);
242 #else
243   free(buf);
244 #endif
245 }
246
247 void *brealloc (void *buf, size_t size)
248 {
249 #ifdef SMARTALOC
250    buf = sm_realloc(__FILE__, __LINE__, buf, size);
251 #else
252    buf = realloc(buf, size);
253 #endif
254    if (buf == NULL) {
255       berrno be;
256       Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.bstrerror());
257    }
258    return buf;
259 }
260
261
262 void *bcalloc(size_t size1, size_t size2)
263 {
264   void *buf;
265
266    buf = calloc(size1, size2);
267    if (buf == NULL) {
268       berrno be;
269       Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.bstrerror());
270    }
271    return buf;
272 }
273
274 /* Code now in src/lib/bsnprintf.c */
275 #ifndef USE_BSNPRINTF
276
277 #define BIG_BUF 5000
278 /*
279  * Implement snprintf
280  */
281 int bsnprintf(char *str, int32_t size, const char *fmt,  ...)
282 {
283    va_list   arg_ptr;
284    int len;
285
286    va_start(arg_ptr, fmt);
287    len = bvsnprintf(str, size, fmt, arg_ptr);
288    va_end(arg_ptr);
289    return len;
290 }
291
292 /*
293  * Implement vsnprintf()
294  */
295 int bvsnprintf(char *str, int32_t size, const char  *format, va_list ap)
296 {
297 #ifdef HAVE_VSNPRINTF
298    int len;
299    len = vsnprintf(str, size, format, ap);
300    str[size-1] = 0;
301    return len;
302
303 #else
304
305    int len, buflen;
306    char *buf;
307    buflen = size > BIG_BUF ? size : BIG_BUF;
308    buf = get_memory(buflen);
309    len = vsprintf(buf, format, ap);
310    if (len >= buflen) {
311       Emsg0(M_ABORT, 0, _("Buffer overflow.\n"));
312    }
313    memcpy(str, buf, len);
314    str[len] = 0;                /* len excludes the null */
315    free_memory(buf);
316    return len;
317 #endif
318 }
319 #endif /* USE_BSNPRINTF */
320
321 #ifndef HAVE_LOCALTIME_R
322
323 struct tm *localtime_r(const time_t *timep, struct tm *tm)
324 {
325     static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
326     struct tm *ltm,
327
328     P(mutex);
329     ltm = localtime(timep);
330     if (ltm) {
331        memcpy(tm, ltm, sizeof(struct tm));
332     }
333     V(mutex);
334     return ltm ? tm : NULL;
335 }
336 #endif /* HAVE_LOCALTIME_R */
337
338 #ifndef HAVE_READDIR_R
339 #ifndef HAVE_WIN32
340 #include <dirent.h>
341
342 int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
343 {
344     static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
345     struct dirent *ndir;
346     int stat;
347
348     P(mutex);
349     errno = 0;
350     ndir = readdir(dirp);
351     stat = errno;
352     if (ndir) {
353        memcpy(entry, ndir, sizeof(struct dirent));
354        strcpy(entry->d_name, ndir->d_name);
355        *result = entry;
356     } else {
357        *result = NULL;
358     }
359     V(mutex);
360     return stat;
361
362 }
363 #endif
364 #endif /* HAVE_READDIR_R */
365
366
367 int b_strerror(int errnum, char *buf, size_t bufsiz)
368 {
369     static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
370     int stat = 0;
371     const char *msg;
372
373     P(mutex);
374
375     msg = strerror(errnum);
376     if (!msg) {
377        msg = _("Bad errno");
378        stat = -1;
379     }
380     bstrncpy(buf, msg, bufsiz);
381     V(mutex);
382     return stat;
383 }
384
385 #ifdef DEBUG_MEMSET
386 /* These routines are not normally turned on */
387 #undef memset
388 void b_memset(const char *file, int line, void *mem, int val, size_t num)
389 {
390    /* Testing for 2000 byte zero at beginning of Volume block */
391    if (num > 1900 && num < 3000) {
392       Pmsg3(000, _("Memset for %d bytes at %s:%d\n"), (int)num, file, line);
393    }
394    memset(mem, val, num);
395 }
396 #endif
397
398 #if !defined(HAVE_WIN32)
399 static int del_pid_file_ok = FALSE;
400 #endif
401
402 /*
403  * Create a standard "Unix" pid file.
404  */
405 void create_pid_file(char *dir, const char *progname, int port)
406 {
407 #if !defined(HAVE_WIN32)
408    int pidfd, len;
409    int oldpid;
410    char  pidbuf[20];
411    POOLMEM *fname = get_pool_memory(PM_FNAME);
412    struct stat statp;
413
414    Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
415    if (stat(fname, &statp) == 0) {
416       /* File exists, see what we have */
417       *pidbuf = 0;
418       if ((pidfd = open(fname, O_RDONLY|O_BINARY, 0)) < 0 ||
419            read(pidfd, &pidbuf, sizeof(pidbuf)) < 0 ||
420            sscanf(pidbuf, "%d", &oldpid) != 1) {
421          berrno be;
422          Emsg2(M_ERROR_TERM, 0, _("Cannot open pid file. %s ERR=%s\n"), fname, 
423                be.bstrerror());
424       }
425       /* Some OSes (IRIX) don't bother to clean out the old pid files after a crash, and
426        * since they use a deterministic algorithm for assigning PIDs, we can have
427        * pid conflicts with the old PID file after a reboot.
428        * The intent the following code is to check if the oldpid read from the pid
429        * file is the same as the currently executing process's pid,
430        * and if oldpid == getpid(), skip the attempt to
431        * kill(oldpid,0), since the attempt is guaranteed to succeed,
432        * but the success won't actually mean that there is an
433        * another Bacula process already running.
434        * For more details see bug #797.
435        */
436        if ((oldpid != (int)getpid()) && (kill(oldpid, 0) != -1 || errno != ESRCH)) {
437          Emsg3(M_ERROR_TERM, 0, _("%s is already running. pid=%d\nCheck file %s\n"),
438                progname, oldpid, fname);
439       }
440       /* He is not alive, so take over file ownership */
441       unlink(fname);                  /* remove stale pid file */
442    }
443    /* Create new pid file */
444    if ((pidfd = open(fname, O_CREAT|O_TRUNC|O_WRONLY|O_BINARY, 0640)) >= 0) {
445       len = sprintf(pidbuf, "%d\n", (int)getpid());
446       write(pidfd, pidbuf, len);
447       close(pidfd);
448       del_pid_file_ok = TRUE;         /* we created it so we can delete it */
449    } else {
450       berrno be;
451       Emsg2(M_ERROR_TERM, 0, _("Could not open pid file. %s ERR=%s\n"), fname, 
452             be.bstrerror());
453    }
454    free_pool_memory(fname);
455 #endif
456 }
457
458
459 /*
460  * Delete the pid file if we created it
461  */
462 int delete_pid_file(char *dir, const char *progname, int port)
463 {
464 #if !defined(HAVE_WIN32)
465    POOLMEM *fname = get_pool_memory(PM_FNAME);
466
467    if (!del_pid_file_ok) {
468       free_pool_memory(fname);
469       return 0;
470    }
471    del_pid_file_ok = FALSE;
472    Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
473    unlink(fname);
474    free_pool_memory(fname);
475 #endif
476    return 1;
477 }
478
479 struct s_state_hdr {
480    char id[14];
481    int32_t version;
482    uint64_t last_jobs_addr;
483    uint64_t reserved[20];
484 };
485
486 static struct s_state_hdr state_hdr = {
487    "Bacula State\n",
488    4,
489    0
490 };
491
492 /*
493  * Open and read the state file for the daemon
494  */
495 void read_state_file(char *dir, const char *progname, int port)
496 {
497    int sfd;
498    ssize_t stat;
499    bool ok = false;
500    POOLMEM *fname = get_pool_memory(PM_FNAME);
501    struct s_state_hdr hdr;
502    int hdr_size = sizeof(hdr);
503
504    Mmsg(&fname, "%s/%s.%d.state", dir, progname, port);
505    /* If file exists, see what we have */
506 // Dmsg1(10, "O_BINARY=%d\n", O_BINARY);
507    if ((sfd = open(fname, O_RDONLY|O_BINARY)) < 0) {
508       berrno be;
509       Dmsg3(010, "Could not open state file. sfd=%d size=%d: ERR=%s\n",
510                     sfd, sizeof(hdr), be.bstrerror());
511       goto bail_out;
512    }
513    if ((stat=read(sfd, &hdr, hdr_size)) != hdr_size) {
514       berrno be;
515       Dmsg4(010, "Could not read state file. sfd=%d stat=%d size=%d: ERR=%s\n",
516                     sfd, (int)stat, hdr_size, be.bstrerror());
517       goto bail_out;
518    }
519    if (hdr.version != state_hdr.version) {
520       Dmsg2(010, "Bad hdr version. Wanted %d got %d\n",
521          state_hdr.version, hdr.version);
522       goto bail_out;
523    }
524    hdr.id[13] = 0;
525    if (strcmp(hdr.id, state_hdr.id) != 0) {
526       Dmsg0(000, "State file header id invalid.\n");
527       goto bail_out;
528    }
529 // Dmsg1(010, "Read header of %d bytes.\n", sizeof(hdr));
530    if (!read_last_jobs_list(sfd, hdr.last_jobs_addr)) {
531       goto bail_out;
532    }
533    ok = true;
534 bail_out:
535    if (sfd >= 0) {
536       close(sfd);
537    }
538    if (!ok) {
539       unlink(fname);
540     }
541    free_pool_memory(fname);
542 }
543
544 /*
545  * Write the state file
546  */
547 static pthread_mutex_t state_mutex = PTHREAD_MUTEX_INITIALIZER;
548
549 void write_state_file(char *dir, const char *progname, int port)
550 {
551    int sfd;
552    bool ok = false;
553    POOLMEM *fname = get_pool_memory(PM_FNAME);
554    
555    P(state_mutex);                    /* Only one job at a time can call here */
556    Mmsg(&fname, "%s/%s.%d.state", dir, progname, port);
557    /* Create new state file */
558    unlink(fname);
559    if ((sfd = open(fname, O_CREAT|O_WRONLY|O_BINARY, 0640)) < 0) {
560       berrno be;
561       Dmsg2(000, "Could not create state file. %s ERR=%s\n", fname, be.bstrerror());
562       Emsg2(M_ERROR, 0, _("Could not create state file. %s ERR=%s\n"), fname, be.bstrerror());
563       goto bail_out;
564    }
565    if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
566       berrno be;
567       Dmsg1(000, "Write hdr error: ERR=%s\n", be.bstrerror());
568       goto bail_out;
569    }
570 // Dmsg1(010, "Wrote header of %d bytes\n", sizeof(state_hdr));
571    state_hdr.last_jobs_addr = sizeof(state_hdr);
572    state_hdr.reserved[0] = write_last_jobs_list(sfd, state_hdr.last_jobs_addr);
573 // Dmsg1(010, "write last job end = %d\n", (int)state_hdr.reserved[0]);
574    if (lseek(sfd, 0, SEEK_SET) < 0) {
575       berrno be;
576       Dmsg1(000, "lseek error: ERR=%s\n", be.bstrerror());
577       goto bail_out;
578    }
579    if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
580       berrno be;
581       Pmsg1(000, _("Write final hdr error: ERR=%s\n"), be.bstrerror());
582       goto bail_out;
583    }
584    ok = true;
585 // Dmsg1(010, "rewrote header = %d\n", sizeof(state_hdr));
586 bail_out:
587    if (sfd >= 0) {
588       close(sfd);
589    }
590    if (!ok) {
591       unlink(fname);
592    }
593    V(state_mutex);
594    free_pool_memory(fname);
595 }
596
597
598 /* BSDI does not have this.  This is a *poor* simulation */
599 #ifndef HAVE_STRTOLL
600 long long int
601 strtoll(const char *ptr, char **endptr, int base)
602 {
603    return (long long int)strtod(ptr, endptr);
604 }
605 #endif
606
607 /*
608  * Bacula's implementation of fgets(). The difference is that it handles
609  *   being interrupted by a signal (e.g. a SIGCHLD).
610  */
611 #undef fgetc
612 char *bfgets(char *s, int size, FILE *fd)
613 {
614    char *p = s;
615    int ch;
616    *p = 0;
617    for (int i=0; i < size-1; i++) {
618       do {
619          errno = 0;
620          ch = fgetc(fd);
621       } while (ch == EOF && ferror(fd) && (errno == EINTR || errno == EAGAIN));
622       if (ch == EOF) {
623          if (i == 0) {
624             return NULL;
625          } else {
626             return s;
627          }
628       }
629       *p++ = ch;
630       *p = 0;
631       if (ch == '\r') { /* Support for Mac/Windows file format */
632          ch = fgetc(fd);
633          if (ch != '\n') { /* Mac (\r only) */
634             (void)ungetc(ch, fd); /* Push next character back to fd */
635          }
636          p[-1] = '\n';
637          break;
638       }
639       if (ch == '\n') {
640          break;
641       }
642    }
643    return s;
644 }
645
646 /*
647  * Make a "unique" filename.  It is important that if
648  *   called again with the same "what" that the result
649  *   will be identical. This allows us to use the file
650  *   without saving its name, and re-generate the name
651  *   so that it can be deleted.
652  */
653 void make_unique_filename(POOLMEM **name, int Id, char *what)
654 {
655    Mmsg(name, "%s/%s.%s.%d.tmp", working_directory, my_name, what, Id);
656 }
657
658 char *escape_filename(const char *file_path)
659 {
660    if (file_path == NULL || strpbrk(file_path, "\"\\") == NULL) {
661       return NULL;
662    }
663
664    char *escaped_path = (char *)bmalloc(2 * (strlen(file_path) + 1));
665    char *cur_char = escaped_path;
666
667    while (*file_path) {
668       if (*file_path == '\\' || *file_path == '"') {
669          *cur_char++ = '\\';
670       }
671
672       *cur_char++ = *file_path++;
673    }
674
675    *cur_char = '\0';
676
677    return escaped_path;
678 }
679
680 #if HAVE_BACKTRACE && HAVE_GCC
681 #include <cxxabi.h>
682 #include <execinfo.h>
683 void stack_trace()
684 {
685    const size_t max_depth = 100;
686    size_t stack_depth;
687    void *stack_addrs[max_depth];
688    char **stack_strings;
689    
690    stack_depth = backtrace(stack_addrs, max_depth);
691    stack_strings = backtrace_symbols(stack_addrs, stack_depth);
692    
693    for (size_t i = 3; i < stack_depth; i++) {
694       size_t sz = 200; /* just a guess, template names will go much wider */
695       char *function = (char *)actuallymalloc(sz);
696       char *begin = 0, *end = 0;
697       /* find the parentheses and address offset surrounding the mangled name */
698       for (char *j = stack_strings[i]; *j; ++j) {
699          if (*j == '(') {
700             begin = j;
701          } else if (*j == '+') {
702             end = j;
703          }
704       }
705       if (begin && end) {
706          *begin++ = '\0';
707          *end = '\0';
708          /* found our mangled name, now in [begin, end] */
709          
710          int status;
711          char *ret = abi::__cxa_demangle(begin, function, &sz, &status);
712          if (ret) {
713             /* return value may be a realloc() of the input */
714             function = ret;
715          } else {
716             /* demangling failed, just pretend it's a C function with no args */
717             strncpy(function, begin, sz);
718             strncat(function, "()", sz);
719             function[sz-1] = '\0';
720          }
721          Pmsg2(000, "    %s:%s\n", stack_strings[i], function);
722
723       } else {
724          /* didn't find the mangled name, just print the whole line */
725          Pmsg1(000, "    %s\n", stack_strings[i]);
726       }
727       actuallyfree(function);
728    }
729    actuallyfree(stack_strings); /* malloc()ed by backtrace_symbols */
730 }
731 #else /* HAVE_BACKTRACE && HAVE_GCC */
732 void stack_trace() {}
733 #endif /* HAVE_BACKTRACE && HAVE_GCC */