2 Bacula® - The Network Backup Solution
4 Copyright (C) 2000-2011 Free Software Foundation Europe e.V.
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
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.
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
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.
29 * Miscellaneous Bacula memory and thread safe routines
30 * Generally, these are interfaces to system or standard
33 * Bacula utility functions are in util.c
40 static pthread_mutex_t timer_mutex = PTHREAD_MUTEX_INITIALIZER;
41 static pthread_cond_t timer = PTHREAD_COND_INITIALIZER;
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
49 int bmicrosleep(int32_t sec, int32_t usec)
51 struct timespec timeout;
57 timeout.tv_nsec = usec * 1000;
60 stat = nanosleep(&timeout, NULL);
61 if (!(stat < 0 && errno == ENOSYS)) {
64 /* If we reach here it is because nanosleep is not supported by the OS */
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;
76 Dmsg2(200, "pthread_cond_timedwait sec=%lld usec=%d\n", sec, usec);
77 /* Note, this unlocks mutex during the sleep */
79 stat = pthread_cond_timedwait(&timer, &timer_mutex, &timeout);
82 Dmsg2(200, "pthread_cond_timedwait stat=%d ERR=%s\n", stat,
90 * Guarantee that the string is properly terminated */
91 char *bstrncpy(char *dest, const char *src, int maxlen)
93 strncpy(dest, src, maxlen-1);
99 * Guarantee that the string is properly terminated */
100 char *bstrncpy(char *dest, POOL_MEM &src, int maxlen)
102 strncpy(dest, src.c_str(), maxlen-1);
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.
112 char *bstrncat(char *dest, const char *src, int maxlen)
114 int len = strlen(dest);
115 if (len < maxlen-1) {
116 strncpy(dest+len, src, maxlen-len-1);
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.
127 char *bstrncat(char *dest, POOL_MEM &src, int maxlen)
129 int len = strlen(dest);
130 if (len < maxlen-1) {
131 strncpy(dest+len, src.c_str(), maxlen-len-1);
138 * Allows one or both pointers to be NULL
140 bool bstrcmp(const char *s1, const char *s2)
142 if (s1 == s2) return true;
143 if (s1 == NULL || s2 == NULL) return false;
144 return strcmp(s1, s2) == 0;
148 * Get character length of UTF-8 string
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
158 int cstrlen(const char *str)
160 uint8_t *p = (uint8_t *)str;
166 if ((*p & 0xC0) != 0xC0) {
171 if ((*p & 0xD0) == 0xC0) {
176 if ((*p & 0xF0) == 0xD0) {
181 if ((*p & 0xF8) == 0xF0) {
186 if ((*p & 0xFC) == 0xF8) {
191 if ((*p & 0xFE) == 0xFC) {
196 p++; /* Shouln't get here but must advance */
204 void *bmalloc(size_t size)
209 buf = sm_malloc(file, line, size);
215 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.bstrerror());
221 void *b_malloc(const char *file, int line, size_t size)
226 buf = sm_malloc(file, line, size);
232 e_msg(file, line, M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.bstrerror());
238 void bfree(void *buf)
241 sm_free(__FILE__, __LINE__, buf);
247 void *brealloc (void *buf, size_t size)
250 buf = sm_realloc(__FILE__, __LINE__, buf, size);
252 buf = realloc(buf, size);
256 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.bstrerror());
262 void *bcalloc(size_t size1, size_t size2)
266 buf = calloc(size1, size2);
269 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.bstrerror());
274 /* Code now in src/lib/bsnprintf.c */
275 #ifndef USE_BSNPRINTF
281 int bsnprintf(char *str, int32_t size, const char *fmt, ...)
286 va_start(arg_ptr, fmt);
287 len = bvsnprintf(str, size, fmt, arg_ptr);
293 * Implement vsnprintf()
295 int bvsnprintf(char *str, int32_t size, const char *format, va_list ap)
297 #ifdef HAVE_VSNPRINTF
299 len = vsnprintf(str, size, format, ap);
307 buflen = size > BIG_BUF ? size : BIG_BUF;
308 buf = get_memory(buflen);
309 len = vsprintf(buf, format, ap);
311 Emsg0(M_ABORT, 0, _("Buffer overflow.\n"));
313 memcpy(str, buf, len);
314 str[len] = 0; /* len excludes the null */
319 #endif /* USE_BSNPRINTF */
321 #ifndef HAVE_LOCALTIME_R
323 struct tm *localtime_r(const time_t *timep, struct tm *tm)
325 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
329 ltm = localtime(timep);
331 memcpy(tm, ltm, sizeof(struct tm));
334 return ltm ? tm : NULL;
336 #endif /* HAVE_LOCALTIME_R */
338 #ifndef HAVE_READDIR_R
342 int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
344 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
350 ndir = readdir(dirp);
353 memcpy(entry, ndir, sizeof(struct dirent));
354 strcpy(entry->d_name, ndir->d_name);
364 #endif /* HAVE_READDIR_R */
367 int b_strerror(int errnum, char *buf, size_t bufsiz)
369 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
375 msg = strerror(errnum);
377 msg = _("Bad errno");
380 bstrncpy(buf, msg, bufsiz);
386 /* These routines are not normally turned on */
388 void b_memset(const char *file, int line, void *mem, int val, size_t num)
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);
394 memset(mem, val, num);
398 #if !defined(HAVE_WIN32)
399 static int del_pid_file_ok = FALSE;
403 * Create a standard "Unix" pid file.
405 void create_pid_file(char *dir, const char *progname, int port)
407 #if !defined(HAVE_WIN32)
411 POOLMEM *fname = get_pool_memory(PM_FNAME);
414 Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
415 if (stat(fname, &statp) == 0) {
416 /* File exists, see what we have */
418 if ((pidfd = open(fname, O_RDONLY|O_BINARY, 0)) < 0 ||
419 read(pidfd, &pidbuf, sizeof(pidbuf)) < 0 ||
420 sscanf(pidbuf, "%d", &oldpid) != 1) {
422 Emsg2(M_ERROR_TERM, 0, _("Cannot open pid file. %s ERR=%s\n"), fname,
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.
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);
440 /* He is not alive, so take over file ownership */
441 unlink(fname); /* remove stale pid file */
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);
448 del_pid_file_ok = TRUE; /* we created it so we can delete it */
451 Emsg2(M_ERROR_TERM, 0, _("Could not open pid file. %s ERR=%s\n"), fname,
454 free_pool_memory(fname);
460 * Delete the pid file if we created it
462 int delete_pid_file(char *dir, const char *progname, int port)
464 #if !defined(HAVE_WIN32)
465 POOLMEM *fname = get_pool_memory(PM_FNAME);
467 if (!del_pid_file_ok) {
468 free_pool_memory(fname);
471 del_pid_file_ok = FALSE;
472 Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
474 free_pool_memory(fname);
482 uint64_t last_jobs_addr;
483 uint64_t reserved[20];
486 static struct s_state_hdr state_hdr = {
493 * Open and read the state file for the daemon
495 void read_state_file(char *dir, const char *progname, int port)
500 POOLMEM *fname = get_pool_memory(PM_FNAME);
501 struct s_state_hdr hdr;
502 int hdr_size = sizeof(hdr);
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) {
509 Dmsg3(010, "Could not open state file. sfd=%d size=%d: ERR=%s\n",
510 sfd, sizeof(hdr), be.bstrerror());
513 if ((stat=read(sfd, &hdr, hdr_size)) != hdr_size) {
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());
519 if (hdr.version != state_hdr.version) {
520 Dmsg2(010, "Bad hdr version. Wanted %d got %d\n",
521 state_hdr.version, hdr.version);
525 if (strcmp(hdr.id, state_hdr.id) != 0) {
526 Dmsg0(000, "State file header id invalid.\n");
529 // Dmsg1(010, "Read header of %d bytes.\n", sizeof(hdr));
530 if (!read_last_jobs_list(sfd, hdr.last_jobs_addr)) {
541 free_pool_memory(fname);
545 * Write the state file
547 static pthread_mutex_t state_mutex = PTHREAD_MUTEX_INITIALIZER;
549 void write_state_file(char *dir, const char *progname, int port)
553 POOLMEM *fname = get_pool_memory(PM_FNAME);
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 */
559 if ((sfd = open(fname, O_CREAT|O_WRONLY|O_BINARY, 0640)) < 0) {
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());
565 if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
567 Dmsg1(000, "Write hdr error: ERR=%s\n", be.bstrerror());
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) {
576 Dmsg1(000, "lseek error: ERR=%s\n", be.bstrerror());
579 if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
581 Pmsg1(000, _("Write final hdr error: ERR=%s\n"), be.bstrerror());
585 // Dmsg1(010, "rewrote header = %d\n", sizeof(state_hdr));
594 free_pool_memory(fname);
598 /* BSDI does not have this. This is a *poor* simulation */
601 strtoll(const char *ptr, char **endptr, int base)
603 return (long long int)strtod(ptr, endptr);
608 * Bacula's implementation of fgets(). The difference is that it handles
609 * being interrupted by a signal (e.g. a SIGCHLD).
612 char *bfgets(char *s, int size, FILE *fd)
617 for (int i=0; i < size-1; i++) {
621 } while (ch == EOF && ferror(fd) && (errno == EINTR || errno == EAGAIN));
631 if (ch == '\r') { /* Support for Mac/Windows file format */
633 if (ch != '\n') { /* Mac (\r only) */
634 (void)ungetc(ch, fd); /* Push next character back to fd */
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.
653 void make_unique_filename(POOLMEM **name, int Id, char *what)
655 Mmsg(name, "%s/%s.%s.%d.tmp", working_directory, my_name, what, Id);
658 char *escape_filename(const char *file_path)
660 if (file_path == NULL || strpbrk(file_path, "\"\\") == NULL) {
664 char *escaped_path = (char *)bmalloc(2 * (strlen(file_path) + 1));
665 char *cur_char = escaped_path;
668 if (*file_path == '\\' || *file_path == '"') {
672 *cur_char++ = *file_path++;
680 #if HAVE_BACKTRACE && HAVE_GCC
682 #include <execinfo.h>
685 const size_t max_depth = 100;
687 void *stack_addrs[max_depth];
688 char **stack_strings;
690 stack_depth = backtrace(stack_addrs, max_depth);
691 stack_strings = backtrace_symbols(stack_addrs, stack_depth);
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) {
701 } else if (*j == '+') {
708 /* found our mangled name, now in [begin, end] */
711 char *ret = abi::__cxa_demangle(begin, function, &sz, &status);
713 /* return value may be a realloc() of the input */
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';
721 Pmsg2(000, " %s:%s\n", stack_strings[i], function);
724 /* didn't find the mangled name, just print the whole line */
725 Pmsg1(000, " %s\n", stack_strings[i]);
727 actuallyfree(function);
729 actuallyfree(stack_strings); /* malloc()ed by backtrace_symbols */
731 #else /* HAVE_BACKTRACE && HAVE_GCC */
732 void stack_trace() {}
733 #endif /* HAVE_BACKTRACE && HAVE_GCC */