2 * Miscellaneous Bacula memory and thread safe routines
3 * Generally, these are interfaces to system or standard
6 * Bacula utility functions are in util.c
11 Bacula® - The Network Backup Solution
13 Copyright (C) 2000-2006 Free Software Foundation Europe e.V.
15 The main author of Bacula is Kern Sibbald, with contributions from
16 many others, a complete list can be found in the file AUTHORS.
17 This program is Free Software; you can redistribute it and/or
18 modify it under the terms of version two of the GNU General Public
19 License as published by the Free Software Foundation plus additions
20 that are listed in the file LICENSE.
22 This program is distributed in the hope that it will be useful, but
23 WITHOUT ANY WARRANTY; without even the implied warranty of
24 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
25 General Public License for more details.
27 You should have received a copy of the GNU General Public License
28 along with this program; if not, write to the Free Software
29 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
32 Bacula® is a registered trademark of John Walker.
33 The licensor of Bacula is the Free Software Foundation Europe
34 (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
35 Switzerland, email:ftf@fsfeurope.org.
47 static pthread_mutex_t timer_mutex = PTHREAD_MUTEX_INITIALIZER;
48 static pthread_cond_t timer = PTHREAD_COND_INITIALIZER;
51 * This routine will sleep (sec, microsec). Note, however, that if a
52 * signal occurs, it will return early. It is up to the caller
53 * to recall this routine if he/she REALLY wants to sleep the
56 int bmicrosleep(time_t sec, long usec)
58 struct timespec timeout;
64 timeout.tv_nsec = usec * 1000;
67 stat = nanosleep(&timeout, NULL);
68 if (!(stat < 0 && errno == ENOSYS)) {
71 /* If we reach here it is because nanosleep is not supported by the OS */
74 /* Do it the old way */
75 gettimeofday(&tv, &tz);
76 timeout.tv_nsec += tv.tv_usec * 1000;
77 timeout.tv_sec += tv.tv_sec;
78 while (timeout.tv_nsec >= 1000000000) {
79 timeout.tv_nsec -= 1000000000;
83 Dmsg2(200, "pthread_cond_timedwait sec=%d usec=%d\n", sec, usec);
84 /* Note, this unlocks mutex during the sleep */
86 stat = pthread_cond_timedwait(&timer, &timer_mutex, &timeout);
89 Dmsg2(200, "pthread_cond_timedwait stat=%d ERR=%s\n", stat,
97 * Guarantee that the string is properly terminated */
98 char *bstrncpy(char *dest, const char *src, int maxlen)
100 strncpy(dest, src, maxlen-1);
106 * Guarantee that the string is properly terminated */
107 char *bstrncpy(char *dest, POOL_MEM &src, int maxlen)
109 strncpy(dest, src.c_str(), maxlen-1);
115 char *bstrncat(char *dest, const char *src, int maxlen)
117 strncat(dest, src, maxlen-1);
122 char *bstrncat(char *dest, POOL_MEM &src, int maxlen)
124 strncat(dest, src.c_str(), maxlen-1);
130 * Allows one or both pointers to be NULL
132 bool bstrcmp(const char *s1, const char *s2)
134 if (s1 == s2) return true;
135 if (s1 == NULL || s2 == NULL) return false;
136 return strcmp(s1, s2) == 0;
140 * Get character length of UTF-8 string
143 * U-00000000 - U-0000007F: 0xxxxxxx
144 * U-00000080 - U-000007FF: 110xxxxx 10xxxxxx
145 * U-00000800 - U-0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx
146 * U-00010000 - U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
147 * U-00200000 - U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
148 * U-04000000 - U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
150 int cstrlen(const char *str)
152 uint8_t *p = (uint8_t *)str;
155 if ((*p & 0xC0) != 0xC0) {
160 if ((*p & 0xD0) == 0xC0) {
165 if ((*p & 0xF0) == 0xD0) {
170 if ((*p & 0xF8) == 0xF0) {
175 if ((*p & 0xFC) == 0xF8) {
180 if ((*p & 0xFE) == 0xFC) {
185 p++; /* Shouln't get here but must advance */
193 void *bmalloc(size_t size)
198 buf = sm_malloc(file, line, size);
204 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.strerror());
210 void *b_malloc(const char *file, int line, size_t size)
215 buf = sm_malloc(file, line, size);
221 e_msg(file, line, M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.strerror());
227 void bfree(void *buf)
230 sm_free(__FILE__, __LINE__, buf);
239 void *brealloc (void *buf, size_t size)
241 buf = realloc(buf, size);
244 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.strerror());
250 void *bcalloc (size_t size1, size_t size2)
254 buf = calloc(size1, size2);
257 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.strerror());
262 /* Code now in src/lib/bsnprintf.c */
263 #ifndef USE_BSNPRINTF
269 int bsnprintf(char *str, int32_t size, const char *fmt, ...)
274 va_start(arg_ptr, fmt);
275 len = bvsnprintf(str, size, fmt, arg_ptr);
281 * Implement vsnprintf()
283 int bvsnprintf(char *str, int32_t size, const char *format, va_list ap)
285 #ifdef HAVE_VSNPRINTF
287 len = vsnprintf(str, size, format, ap);
295 buflen = size > BIG_BUF ? size : BIG_BUF;
296 buf = get_memory(buflen);
297 len = vsprintf(buf, format, ap);
299 Emsg0(M_ABORT, 0, _("Buffer overflow.\n"));
301 memcpy(str, buf, len);
302 str[len] = 0; /* len excludes the null */
307 #endif /* USE_BSNPRINTF */
309 #ifndef HAVE_LOCALTIME_R
311 struct tm *localtime_r(const time_t *timep, struct tm *tm)
313 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
317 ltm = localtime(timep);
319 memcpy(tm, ltm, sizeof(struct tm));
322 return ltm ? tm : NULL;
324 #endif /* HAVE_LOCALTIME_R */
326 #ifndef HAVE_READDIR_R
330 int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
332 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
338 ndir = readdir(dirp);
341 memcpy(entry, ndir, sizeof(struct dirent));
342 strcpy(entry->d_name, ndir->d_name);
352 #endif /* HAVE_READDIR_R */
355 int bstrerror(int errnum, char *buf, size_t bufsiz)
357 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
363 msg = strerror(errnum);
365 msg = _("Bad errno");
368 bstrncpy(buf, msg, bufsiz);
374 * These are mutex routines that do error checking
375 * for deadlock and such. Normally not turned on.
378 void _p(char *file, int line, pthread_mutex_t *m)
381 if ((errstat = pthread_mutex_trylock(m))) {
382 e_msg(file, line, M_ERROR, 0, _("Possible mutex deadlock.\n"));
383 /* We didn't get the lock, so do it definitely now */
384 if ((errstat=pthread_mutex_lock(m))) {
386 e_msg(file, line, M_ABORT, 0, _("Mutex lock failure. ERR=%s\n"),
387 be.strerror(errstat));
389 e_msg(file, line, M_ERROR, 0, _("Possible mutex deadlock resolved.\n"));
395 void _v(char *file, int line, pthread_mutex_t *m)
399 /* Note, this trylock *should* fail if the mutex is locked */
400 if ((errstat=pthread_mutex_trylock(m)) == 0) {
402 e_msg(file, line, M_ERROR, 0, _("Mutex unlock not locked. ERR=%s\n"),
403 be.strerror(errstat));
405 if ((errstat=pthread_mutex_unlock(m))) {
407 e_msg(file, line, M_ABORT, 0, _("Mutex unlock failure. ERR=%s\n"),
408 be.strerror(errstat));
414 void _p(pthread_mutex_t *m)
417 if ((errstat=pthread_mutex_lock(m))) {
419 e_msg(__FILE__, __LINE__, M_ABORT, 0, _("Mutex lock failure. ERR=%s\n"),
420 be.strerror(errstat));
424 void _v(pthread_mutex_t *m)
427 if ((errstat=pthread_mutex_unlock(m))) {
429 e_msg(__FILE__, __LINE__, M_ABORT, 0, _("Mutex unlock failure. ERR=%s\n"),
430 be.strerror(errstat));
434 #endif /* DEBUG_MUTEX */
437 /* These routines are not normally turned on */
439 void b_memset(const char *file, int line, void *mem, int val, size_t num)
441 /* Testing for 2000 byte zero at beginning of Volume block */
442 if (num > 1900 && num < 3000) {
443 Pmsg3(000, _("Memset for %d bytes at %s:%d\n"), (int)num, file, line);
445 memset(mem, val, num);
449 #if !defined(HAVE_WIN32)
450 static int del_pid_file_ok = FALSE;
454 * Create a standard "Unix" pid file.
456 void create_pid_file(char *dir, const char *progname, int port)
458 #if !defined(HAVE_WIN32)
462 POOLMEM *fname = get_pool_memory(PM_FNAME);
465 Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
466 if (stat(fname, &statp) == 0) {
467 /* File exists, see what we have */
469 if ((pidfd = open(fname, O_RDONLY|O_BINARY, 0)) < 0 ||
470 read(pidfd, &pidbuf, sizeof(pidbuf)) < 0 ||
471 sscanf(pidbuf, "%d", &oldpid) != 1) {
472 Emsg2(M_ERROR_TERM, 0, _("Cannot open pid file. %s ERR=%s\n"), fname, strerror(errno));
474 /* See if other Bacula is still alive */
475 if (kill(oldpid, 0) != -1 || errno != ESRCH) {
476 Emsg3(M_ERROR_TERM, 0, _("%s is already running. pid=%d\nCheck file %s\n"),
477 progname, oldpid, fname);
479 /* He is not alive, so take over file ownership */
480 unlink(fname); /* remove stale pid file */
482 /* Create new pid file */
483 if ((pidfd = open(fname, O_CREAT|O_TRUNC|O_WRONLY|O_BINARY, 0640)) >= 0) {
484 len = sprintf(pidbuf, "%d\n", (int)getpid());
485 write(pidfd, pidbuf, len);
487 del_pid_file_ok = TRUE; /* we created it so we can delete it */
489 Emsg2(M_ERROR_TERM, 0, _("Could not open pid file. %s ERR=%s\n"), fname, strerror(errno));
491 free_pool_memory(fname);
497 * Delete the pid file if we created it
499 int delete_pid_file(char *dir, const char *progname, int port)
501 #if !defined(HAVE_WIN32)
502 POOLMEM *fname = get_pool_memory(PM_FNAME);
504 if (!del_pid_file_ok) {
505 free_pool_memory(fname);
508 del_pid_file_ok = FALSE;
509 Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
511 free_pool_memory(fname);
519 uint64_t last_jobs_addr;
520 uint64_t reserved[20];
523 static struct s_state_hdr state_hdr = {
530 * Open and read the state file for the daemon
532 void read_state_file(char *dir, const char *progname, int port)
537 POOLMEM *fname = get_pool_memory(PM_FNAME);
538 struct s_state_hdr hdr;
539 int hdr_size = sizeof(hdr);
541 Mmsg(&fname, "%s/%s.%d.state", dir, progname, port);
542 /* If file exists, see what we have */
543 // Dmsg1(10, "O_BINARY=%d\n", O_BINARY);
544 if ((sfd = open(fname, O_RDONLY|O_BINARY)) < 0) {
545 Dmsg3(010, "Could not open state file. sfd=%d size=%d: ERR=%s\n",
546 sfd, sizeof(hdr), strerror(errno));
549 if ((stat=read(sfd, &hdr, hdr_size)) != hdr_size) {
550 Dmsg4(010, "Could not read state file. sfd=%d stat=%d size=%d: ERR=%s\n",
551 sfd, (int)stat, hdr_size, strerror(errno));
554 if (hdr.version != state_hdr.version) {
555 Dmsg2(010, "Bad hdr version. Wanted %d got %d\n",
556 state_hdr.version, hdr.version);
560 if (strcmp(hdr.id, state_hdr.id) != 0) {
561 Dmsg0(000, "State file header id invalid.\n");
564 // Dmsg1(010, "Read header of %d bytes.\n", sizeof(hdr));
565 if (!read_last_jobs_list(sfd, hdr.last_jobs_addr)) {
576 free_pool_memory(fname);
580 * Write the state file
582 void write_state_file(char *dir, const char *progname, int port)
586 POOLMEM *fname = get_pool_memory(PM_FNAME);
588 Mmsg(&fname, "%s/%s.%d.state", dir, progname, port);
589 /* Create new state file */
591 if ((sfd = open(fname, O_CREAT|O_WRONLY|O_BINARY, 0640)) < 0) {
593 Dmsg2(000, "Could not create state file. %s ERR=%s\n", fname, be.strerror());
594 Emsg2(M_ERROR, 0, _("Could not create state file. %s ERR=%s\n"), fname, be.strerror());
597 if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
599 Dmsg1(000, "Write hdr error: ERR=%s\n", be.strerror());
602 // Dmsg1(010, "Wrote header of %d bytes\n", sizeof(state_hdr));
603 state_hdr.last_jobs_addr = sizeof(state_hdr);
604 state_hdr.reserved[0] = write_last_jobs_list(sfd, state_hdr.last_jobs_addr);
605 // Dmsg1(010, "write last job end = %d\n", (int)state_hdr.reserved[0]);
606 if (lseek(sfd, 0, SEEK_SET) < 0) {
608 Dmsg1(000, "lseek error: ERR=%s\n", be.strerror());
611 if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
613 Pmsg1(000, _("Write final hdr error: ERR=%s\n"), be.strerror());
617 // Dmsg1(010, "rewrote header = %d\n", sizeof(state_hdr));
625 free_pool_memory(fname);
630 * Drop to privilege new userid and new gid if non-NULL
632 void drop(char *uname, char *gname)
634 #if defined(HAVE_PWD_H) && defined(HAVE_GRP_H)
635 struct passwd *passw = NULL;
636 struct group *group = NULL;
641 Dmsg2(900, "uname=%s gname=%s\n", uname?uname:"NONE", gname?gname:"NONE");
642 if (!uname && !gname) {
643 return; /* Nothing to do */
647 if ((passw = getpwnam(uname)) == NULL) {
649 Emsg2(M_ERROR_TERM, 0, _("Could not find userid=%s: ERR=%s\n"), uname,
653 if ((passw = getpwuid(getuid())) == NULL) {
655 Emsg1(M_ERROR_TERM, 0, _("Could not find password entry. ERR=%s\n"),
658 uname = passw->pw_name;
661 /* Any OS uname pointer may get overwritten, so save name, uid, and gid */
662 bstrncpy(username, uname, sizeof(username));
666 if ((group = getgrnam(gname)) == NULL) {
668 Emsg2(M_ERROR_TERM, 0, _("Could not find group=%s: ERR=%s\n"), gname,
673 if (initgroups(username, gid)) {
676 Emsg3(M_ERROR_TERM, 0, _("Could not initgroups for group=%s, userid=%s: ERR=%s\n"),
677 gname, username, be.strerror());
679 Emsg2(M_ERROR_TERM, 0, _("Could not initgroups for userid=%s: ERR=%s\n"),
680 username, be.strerror());
686 Emsg2(M_ERROR_TERM, 0, _("Could not set group=%s: ERR=%s\n"), gname,
692 Emsg1(M_ERROR_TERM, 0, _("Could not set specified userid: %s\n"), username);
698 /* BSDI does not have this. This is a *poor* simulation */
701 strtoll(const char *ptr, char **endptr, int base)
703 return (long long int)strtod(ptr, endptr);
708 * Bacula's implementation of fgets(). The difference is that it handles
709 * being interrupted by a signal (e.g. a SIGCHLD).
712 char *bfgets(char *s, int size, FILE *fd)
717 for (int i=0; i < size-1; i++) {
721 } while (ch == EOF && ferror(fd) && (errno == EINTR || errno == EAGAIN));
731 if (ch == '\r') { /* Support for Mac/Windows file format */
733 if (ch != '\n') { /* Mac (\r only) */
734 (void)ungetc(ch, fd); /* Push next character back to fd */
747 * Make a "unique" filename. It is important that if
748 * called again with the same "what" that the result
749 * will be identical. This allows us to use the file
750 * without saving its name, and re-generate the name
751 * so that it can be deleted.
753 void make_unique_filename(POOLMEM **name, int Id, char *what)
755 Mmsg(name, "%s/%s.%s.%d.tmp", working_directory, my_name, what, Id);
758 char *escape_filename(const char *file_path)
760 if (file_path == NULL || strpbrk(file_path, "\"\\") == NULL) {
764 char *escaped_path = (char *)bmalloc(2 * (strlen(file_path) + 1));
765 char *cur_char = escaped_path;
768 if (*file_path == '\\' || *file_path == '"') {
772 *cur_char++ = *file_path++;