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
43 static pthread_mutex_t timer_mutex = PTHREAD_MUTEX_INITIALIZER;
44 static pthread_cond_t timer = PTHREAD_COND_INITIALIZER;
47 * This routine will sleep (sec, microsec). Note, however, that if a
48 * signal occurs, it will return early. It is up to the caller
49 * to recall this routine if he/she REALLY wants to sleep the
52 int bmicrosleep(int32_t sec, int32_t usec)
54 struct timespec timeout;
60 timeout.tv_nsec = usec * 1000;
63 stat = nanosleep(&timeout, NULL);
64 if (!(stat < 0 && errno == ENOSYS)) {
67 /* If we reach here it is because nanosleep is not supported by the OS */
70 /* Do it the old way */
71 gettimeofday(&tv, &tz);
72 timeout.tv_nsec += tv.tv_usec * 1000;
73 timeout.tv_sec += tv.tv_sec;
74 while (timeout.tv_nsec >= 1000000000) {
75 timeout.tv_nsec -= 1000000000;
79 Dmsg2(200, "pthread_cond_timedwait sec=%lld usec=%d\n", sec, usec);
80 /* Note, this unlocks mutex during the sleep */
82 stat = pthread_cond_timedwait(&timer, &timer_mutex, &timeout);
85 Dmsg2(200, "pthread_cond_timedwait stat=%d ERR=%s\n", stat,
93 * Guarantee that the string is properly terminated */
94 char *bstrncpy(char *dest, const char *src, int maxlen)
96 strncpy(dest, src, maxlen-1);
102 * Guarantee that the string is properly terminated */
103 char *bstrncpy(char *dest, POOL_MEM &src, int maxlen)
105 strncpy(dest, src.c_str(), maxlen-1);
111 * Note: Here the maxlen is the maximum length permitted
112 * stored in dest, while on Unix systems, it is the maximum characters
113 * that may be copied from src.
115 char *bstrncat(char *dest, const char *src, int maxlen)
117 int len = strlen(dest);
118 if (len < maxlen-1) {
119 strncpy(dest+len, src, maxlen-len-1);
126 * Note: Here the maxlen is the maximum length permitted
127 * stored in dest, while on Unix systems, it is the maximum characters
128 * that may be copied from src.
130 char *bstrncat(char *dest, POOL_MEM &src, int maxlen)
132 int len = strlen(dest);
133 if (len < maxlen-1) {
134 strncpy(dest+len, src.c_str(), maxlen-len-1);
141 * Allows one or both pointers to be NULL
143 bool bstrcmp(const char *s1, const char *s2)
145 if (s1 == s2) return true;
146 if (s1 == NULL || s2 == NULL) return false;
147 return strcmp(s1, s2) == 0;
151 * Get character length of UTF-8 string
154 * U-00000000 - U-0000007F: 0xxxxxxx
155 * U-00000080 - U-000007FF: 110xxxxx 10xxxxxx
156 * U-00000800 - U-0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx
157 * U-00010000 - U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
158 * U-00200000 - U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
159 * U-04000000 - U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
161 int cstrlen(const char *str)
163 uint8_t *p = (uint8_t *)str;
169 if ((*p & 0xC0) != 0xC0) {
174 if ((*p & 0xD0) == 0xC0) {
179 if ((*p & 0xF0) == 0xD0) {
184 if ((*p & 0xF8) == 0xF0) {
189 if ((*p & 0xFC) == 0xF8) {
194 if ((*p & 0xFE) == 0xFC) {
199 p++; /* Shouln't get here but must advance */
207 void *bmalloc(size_t size)
212 buf = sm_malloc(file, line, size);
218 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.bstrerror());
224 void *b_malloc(const char *file, int line, size_t size)
229 buf = sm_malloc(file, line, size);
235 e_msg(file, line, M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.bstrerror());
241 void bfree(void *buf)
244 sm_free(__FILE__, __LINE__, buf);
250 void *brealloc (void *buf, size_t size)
253 buf = sm_realloc(__FILE__, __LINE__, buf, size);
255 buf = realloc(buf, size);
259 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.bstrerror());
265 void *bcalloc(size_t size1, size_t size2)
269 buf = calloc(size1, size2);
272 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.bstrerror());
277 /* Code now in src/lib/bsnprintf.c */
278 #ifndef USE_BSNPRINTF
284 int bsnprintf(char *str, int32_t size, const char *fmt, ...)
289 va_start(arg_ptr, fmt);
290 len = bvsnprintf(str, size, fmt, arg_ptr);
296 * Implement vsnprintf()
298 int bvsnprintf(char *str, int32_t size, const char *format, va_list ap)
300 #ifdef HAVE_VSNPRINTF
302 len = vsnprintf(str, size, format, ap);
310 buflen = size > BIG_BUF ? size : BIG_BUF;
311 buf = get_memory(buflen);
312 len = vsprintf(buf, format, ap);
314 Emsg0(M_ABORT, 0, _("Buffer overflow.\n"));
316 memcpy(str, buf, len);
317 str[len] = 0; /* len excludes the null */
322 #endif /* USE_BSNPRINTF */
324 #ifndef HAVE_LOCALTIME_R
326 struct tm *localtime_r(const time_t *timep, struct tm *tm)
328 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
332 ltm = localtime(timep);
334 memcpy(tm, ltm, sizeof(struct tm));
337 return ltm ? tm : NULL;
339 #endif /* HAVE_LOCALTIME_R */
341 #ifndef HAVE_READDIR_R
345 int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
347 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
353 ndir = readdir(dirp);
356 memcpy(entry, ndir, sizeof(struct dirent));
357 strcpy(entry->d_name, ndir->d_name);
367 #endif /* HAVE_READDIR_R */
370 int b_strerror(int errnum, char *buf, size_t bufsiz)
372 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
378 msg = strerror(errnum);
380 msg = _("Bad errno");
383 bstrncpy(buf, msg, bufsiz);
389 /* These routines are not normally turned on */
391 void b_memset(const char *file, int line, void *mem, int val, size_t num)
393 /* Testing for 2000 byte zero at beginning of Volume block */
394 if (num > 1900 && num < 3000) {
395 Pmsg3(000, _("Memset for %d bytes at %s:%d\n"), (int)num, file, line);
397 memset(mem, val, num);
401 #if !defined(HAVE_WIN32)
402 static int del_pid_file_ok = FALSE;
406 * Create a standard "Unix" pid file.
408 void create_pid_file(char *dir, const char *progname, int port)
410 #if !defined(HAVE_WIN32)
414 POOLMEM *fname = get_pool_memory(PM_FNAME);
417 Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
418 if (stat(fname, &statp) == 0) {
419 /* File exists, see what we have */
421 if ((pidfd = open(fname, O_RDONLY|O_BINARY, 0)) < 0 ||
422 read(pidfd, &pidbuf, sizeof(pidbuf)) < 0 ||
423 sscanf(pidbuf, "%d", &oldpid) != 1) {
425 Emsg2(M_ERROR_TERM, 0, _("Cannot open pid file. %s ERR=%s\n"), fname,
428 /* Some OSes (IRIX) don't bother to clean out the old pid files after a crash, and
429 * since they use a deterministic algorithm for assigning PIDs, we can have
430 * pid conflicts with the old PID file after a reboot.
431 * The intent the following code is to check if the oldpid read from the pid
432 * file is the same as the currently executing process's pid,
433 * and if oldpid == getpid(), skip the attempt to
434 * kill(oldpid,0), since the attempt is guaranteed to succeed,
435 * but the success won't actually mean that there is an
436 * another Bacula process already running.
437 * For more details see bug #797.
439 if ((oldpid != (int)getpid()) && (kill(oldpid, 0) != -1 || errno != ESRCH)) {
440 Emsg3(M_ERROR_TERM, 0, _("%s is already running. pid=%d\nCheck file %s\n"),
441 progname, oldpid, fname);
443 /* He is not alive, so take over file ownership */
444 unlink(fname); /* remove stale pid file */
446 /* Create new pid file */
447 if ((pidfd = open(fname, O_CREAT|O_TRUNC|O_WRONLY|O_BINARY, 0640)) >= 0) {
448 len = sprintf(pidbuf, "%d\n", (int)getpid());
449 write(pidfd, pidbuf, len);
451 del_pid_file_ok = TRUE; /* we created it so we can delete it */
454 Emsg2(M_ERROR_TERM, 0, _("Could not open pid file. %s ERR=%s\n"), fname,
457 free_pool_memory(fname);
463 * Delete the pid file if we created it
465 int delete_pid_file(char *dir, const char *progname, int port)
467 #if !defined(HAVE_WIN32)
468 POOLMEM *fname = get_pool_memory(PM_FNAME);
470 if (!del_pid_file_ok) {
471 free_pool_memory(fname);
474 del_pid_file_ok = FALSE;
475 Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
477 free_pool_memory(fname);
485 uint64_t last_jobs_addr;
486 uint64_t reserved[20];
489 static struct s_state_hdr state_hdr = {
496 * Open and read the state file for the daemon
498 void read_state_file(char *dir, const char *progname, int port)
503 POOLMEM *fname = get_pool_memory(PM_FNAME);
504 struct s_state_hdr hdr;
505 int hdr_size = sizeof(hdr);
507 Mmsg(&fname, "%s/%s.%d.state", dir, progname, port);
508 /* If file exists, see what we have */
509 // Dmsg1(10, "O_BINARY=%d\n", O_BINARY);
510 if ((sfd = open(fname, O_RDONLY|O_BINARY)) < 0) {
512 Dmsg3(010, "Could not open state file. sfd=%d size=%d: ERR=%s\n",
513 sfd, sizeof(hdr), be.bstrerror());
516 if ((stat=read(sfd, &hdr, hdr_size)) != hdr_size) {
518 Dmsg4(010, "Could not read state file. sfd=%d stat=%d size=%d: ERR=%s\n",
519 sfd, (int)stat, hdr_size, be.bstrerror());
522 if (hdr.version != state_hdr.version) {
523 Dmsg2(010, "Bad hdr version. Wanted %d got %d\n",
524 state_hdr.version, hdr.version);
528 if (strcmp(hdr.id, state_hdr.id) != 0) {
529 Dmsg0(000, "State file header id invalid.\n");
532 // Dmsg1(010, "Read header of %d bytes.\n", sizeof(hdr));
533 if (!read_last_jobs_list(sfd, hdr.last_jobs_addr)) {
544 free_pool_memory(fname);
548 * Write the state file
550 static pthread_mutex_t state_mutex = PTHREAD_MUTEX_INITIALIZER;
552 void write_state_file(char *dir, const char *progname, int port)
556 POOLMEM *fname = get_pool_memory(PM_FNAME);
558 P(state_mutex); /* Only one job at a time can call here */
559 Mmsg(&fname, "%s/%s.%d.state", dir, progname, port);
560 /* Create new state file */
562 if ((sfd = open(fname, O_CREAT|O_WRONLY|O_BINARY, 0640)) < 0) {
564 Dmsg2(000, "Could not create state file. %s ERR=%s\n", fname, be.bstrerror());
565 Emsg2(M_ERROR, 0, _("Could not create state file. %s ERR=%s\n"), fname, be.bstrerror());
568 if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
570 Dmsg1(000, "Write hdr error: ERR=%s\n", be.bstrerror());
573 // Dmsg1(010, "Wrote header of %d bytes\n", sizeof(state_hdr));
574 state_hdr.last_jobs_addr = sizeof(state_hdr);
575 state_hdr.reserved[0] = write_last_jobs_list(sfd, state_hdr.last_jobs_addr);
576 // Dmsg1(010, "write last job end = %d\n", (int)state_hdr.reserved[0]);
577 if (lseek(sfd, 0, SEEK_SET) < 0) {
579 Dmsg1(000, "lseek error: ERR=%s\n", be.bstrerror());
582 if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
584 Pmsg1(000, _("Write final hdr error: ERR=%s\n"), be.bstrerror());
588 // Dmsg1(010, "rewrote header = %d\n", sizeof(state_hdr));
597 free_pool_memory(fname);
601 /* BSDI does not have this. This is a *poor* simulation */
604 strtoll(const char *ptr, char **endptr, int base)
606 return (long long int)strtod(ptr, endptr);
611 * Bacula's implementation of fgets(). The difference is that it handles
612 * being interrupted by a signal (e.g. a SIGCHLD).
615 char *bfgets(char *s, int size, FILE *fd)
620 for (int i=0; i < size-1; i++) {
624 } while (ch == EOF && ferror(fd) && (errno == EINTR || errno == EAGAIN));
634 if (ch == '\r') { /* Support for Mac/Windows file format */
636 if (ch != '\n') { /* Mac (\r only) */
637 (void)ungetc(ch, fd); /* Push next character back to fd */
650 * Make a "unique" filename. It is important that if
651 * called again with the same "what" that the result
652 * will be identical. This allows us to use the file
653 * without saving its name, and re-generate the name
654 * so that it can be deleted.
656 void make_unique_filename(POOLMEM **name, int Id, char *what)
658 Mmsg(name, "%s/%s.%s.%d.tmp", working_directory, my_name, what, Id);
661 char *escape_filename(const char *file_path)
663 if (file_path == NULL || strpbrk(file_path, "\"\\") == NULL) {
667 char *escaped_path = (char *)bmalloc(2 * (strlen(file_path) + 1));
668 char *cur_char = escaped_path;
671 if (*file_path == '\\' || *file_path == '"') {
675 *cur_char++ = *file_path++;
684 * Deflate or compress and input buffer. You must supply an
685 * output buffer sufficiently long and the length of the
686 * output buffer. Generally, if the output buffer is the
687 * same size as the input buffer, it should work (at least
690 int Zdeflate(char *in, int in_len, char *out, int &out_len)
696 /* allocate deflate state */
697 strm.zalloc = Z_NULL;
699 strm.opaque = Z_NULL;
700 ret = deflateInit(&strm, 9);
702 Dmsg0(200, "deflateInit error\n");
703 (void)deflateEnd(&strm);
707 strm.next_in = (Bytef *)in;
708 strm.avail_in = in_len;
709 Dmsg1(200, "In: %d bytes\n", strm.avail_in);
710 strm.avail_out = out_len;
711 strm.next_out = (Bytef *)out;
712 ret = deflate(&strm, Z_FINISH);
713 out_len = out_len - strm.avail_out;
714 Dmsg1(200, "compressed=%d\n", out_len);
715 (void)deflateEnd(&strm);
723 * Inflate or uncompress an input buffer. You must supply
724 * and output buffer and an output length sufficiently long
725 * or there will be an error. This uncompresses in one call.
727 int Zinflate(char *in, int in_len, char *out, int &out_len)
733 /* allocate deflate state */
734 strm.zalloc = Z_NULL;
736 strm.opaque = Z_NULL;
737 strm.next_in = (Bytef *)in;
738 strm.avail_in = in_len;
739 ret = inflateInit(&strm);
741 Dmsg0(200, "inflateInit error\n");
742 (void)inflateEnd(&strm);
746 Dmsg1(200, "In len: %d bytes\n", strm.avail_in);
747 strm.avail_out = out_len;
748 strm.next_out = (Bytef *)out;
749 ret = inflate(&strm, Z_FINISH);
750 out_len -= strm.avail_out;
751 Dmsg1(200, "Uncompressed=%d\n", out_len);
752 (void)inflateEnd(&strm);
759 #if HAVE_BACKTRACE && HAVE_GCC
761 #include <execinfo.h>
764 const size_t max_depth = 100;
766 void *stack_addrs[max_depth];
767 char **stack_strings;
769 stack_depth = backtrace(stack_addrs, max_depth);
770 stack_strings = backtrace_symbols(stack_addrs, stack_depth);
772 for (size_t i = 3; i < stack_depth; i++) {
773 size_t sz = 200; /* just a guess, template names will go much wider */
774 char *function = (char *)actuallymalloc(sz);
775 char *begin = 0, *end = 0;
776 /* find the parentheses and address offset surrounding the mangled name */
777 for (char *j = stack_strings[i]; *j; ++j) {
780 } else if (*j == '+') {
787 /* found our mangled name, now in [begin, end] */
790 char *ret = abi::__cxa_demangle(begin, function, &sz, &status);
792 /* return value may be a realloc() of the input */
795 /* demangling failed, just pretend it's a C function with no args */
796 strncpy(function, begin, sz);
797 strncat(function, "()", sz);
798 function[sz-1] = '\0';
800 Pmsg2(000, " %s:%s\n", stack_strings[i], function);
803 /* didn't find the mangled name, just print the whole line */
804 Pmsg1(000, " %s\n", stack_strings[i]);
806 actuallyfree(function);
808 actuallyfree(stack_strings); /* malloc()ed by backtrace_symbols */
810 #else /* HAVE_BACKTRACE && HAVE_GCC */
811 void stack_trace() {}
812 #endif /* HAVE_BACKTRACE && HAVE_GCC */