2 Bacula® - The Network Backup Solution
4 Copyright (C) 2000-2007 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 two of the GNU 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 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 John Walker.
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
47 extern "C" int initgroups(char *,int);
51 static pthread_mutex_t timer_mutex = PTHREAD_MUTEX_INITIALIZER;
52 static pthread_cond_t timer = PTHREAD_COND_INITIALIZER;
55 * This routine will sleep (sec, microsec). Note, however, that if a
56 * signal occurs, it will return early. It is up to the caller
57 * to recall this routine if he/she REALLY wants to sleep the
60 int bmicrosleep(time_t sec, long usec)
62 struct timespec timeout;
68 timeout.tv_nsec = usec * 1000;
71 stat = nanosleep(&timeout, NULL);
72 if (!(stat < 0 && errno == ENOSYS)) {
75 /* If we reach here it is because nanosleep is not supported by the OS */
78 /* Do it the old way */
79 gettimeofday(&tv, &tz);
80 timeout.tv_nsec += tv.tv_usec * 1000;
81 timeout.tv_sec += tv.tv_sec;
82 while (timeout.tv_nsec >= 1000000000) {
83 timeout.tv_nsec -= 1000000000;
87 Dmsg2(200, "pthread_cond_timedwait sec=%d usec=%d\n", sec, usec);
88 /* Note, this unlocks mutex during the sleep */
90 stat = pthread_cond_timedwait(&timer, &timer_mutex, &timeout);
93 Dmsg2(200, "pthread_cond_timedwait stat=%d ERR=%s\n", stat,
101 * Guarantee that the string is properly terminated */
102 char *bstrncpy(char *dest, const char *src, int maxlen)
104 strncpy(dest, src, maxlen-1);
110 * Guarantee that the string is properly terminated */
111 char *bstrncpy(char *dest, POOL_MEM &src, int maxlen)
113 strncpy(dest, src.c_str(), maxlen-1);
119 char *bstrncat(char *dest, const char *src, int maxlen)
121 strncat(dest, src, maxlen-1);
126 char *bstrncat(char *dest, POOL_MEM &src, int maxlen)
128 strncat(dest, src.c_str(), maxlen-1);
134 * Allows one or both pointers to be NULL
136 bool bstrcmp(const char *s1, const char *s2)
138 if (s1 == s2) return true;
139 if (s1 == NULL || s2 == NULL) return false;
140 return strcmp(s1, s2) == 0;
144 * Get character length of UTF-8 string
147 * U-00000000 - U-0000007F: 0xxxxxxx
148 * U-00000080 - U-000007FF: 110xxxxx 10xxxxxx
149 * U-00000800 - U-0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx
150 * U-00010000 - U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
151 * U-00200000 - U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
152 * U-04000000 - U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
154 int cstrlen(const char *str)
156 uint8_t *p = (uint8_t *)str;
159 if ((*p & 0xC0) != 0xC0) {
164 if ((*p & 0xD0) == 0xC0) {
169 if ((*p & 0xF0) == 0xD0) {
174 if ((*p & 0xF8) == 0xF0) {
179 if ((*p & 0xFC) == 0xF8) {
184 if ((*p & 0xFE) == 0xFC) {
189 p++; /* Shouln't get here but must advance */
197 void *bmalloc(size_t size)
202 buf = sm_malloc(file, line, size);
208 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.bstrerror());
214 void *b_malloc(const char *file, int line, size_t size)
219 buf = sm_malloc(file, line, size);
225 e_msg(file, line, M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.bstrerror());
231 void bfree(void *buf)
234 sm_free(__FILE__, __LINE__, buf);
240 void *brealloc (void *buf, size_t size)
243 buf = sm_realloc(__FILE__, __LINE__, buf, size);
245 buf = realloc(buf, size);
249 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.bstrerror());
255 void *bcalloc(size_t size1, size_t size2)
259 buf = calloc(size1, size2);
262 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.bstrerror());
267 /* Code now in src/lib/bsnprintf.c */
268 #ifndef USE_BSNPRINTF
274 int bsnprintf(char *str, int32_t size, const char *fmt, ...)
279 va_start(arg_ptr, fmt);
280 len = bvsnprintf(str, size, fmt, arg_ptr);
286 * Implement vsnprintf()
288 int bvsnprintf(char *str, int32_t size, const char *format, va_list ap)
290 #ifdef HAVE_VSNPRINTF
292 len = vsnprintf(str, size, format, ap);
300 buflen = size > BIG_BUF ? size : BIG_BUF;
301 buf = get_memory(buflen);
302 len = vsprintf(buf, format, ap);
304 Emsg0(M_ABORT, 0, _("Buffer overflow.\n"));
306 memcpy(str, buf, len);
307 str[len] = 0; /* len excludes the null */
312 #endif /* USE_BSNPRINTF */
314 #ifndef HAVE_LOCALTIME_R
316 struct tm *localtime_r(const time_t *timep, struct tm *tm)
318 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
322 ltm = localtime(timep);
324 memcpy(tm, ltm, sizeof(struct tm));
327 return ltm ? tm : NULL;
329 #endif /* HAVE_LOCALTIME_R */
331 #ifndef HAVE_READDIR_R
335 int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
337 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
343 ndir = readdir(dirp);
346 memcpy(entry, ndir, sizeof(struct dirent));
347 strcpy(entry->d_name, ndir->d_name);
357 #endif /* HAVE_READDIR_R */
360 int b_strerror(int errnum, char *buf, size_t bufsiz)
362 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
368 msg = strerror(errnum);
370 msg = _("Bad errno");
373 bstrncpy(buf, msg, bufsiz);
379 * These are mutex routines that do error checking
380 * for deadlock and such. Normally not turned on.
383 void _p(char *file, int line, pthread_mutex_t *m)
386 if ((errstat = pthread_mutex_trylock(m))) {
387 e_msg(file, line, M_ERROR, 0, _("Possible mutex deadlock.\n"));
388 /* We didn't get the lock, so do it definitely now */
389 if ((errstat=pthread_mutex_lock(m))) {
391 e_msg(file, line, M_ABORT, 0, _("Mutex lock failure. ERR=%s\n"),
392 be.bstrerror(errstat));
394 e_msg(file, line, M_ERROR, 0, _("Possible mutex deadlock resolved.\n"));
400 void _v(char *file, int line, pthread_mutex_t *m)
404 /* Note, this trylock *should* fail if the mutex is locked */
405 if ((errstat=pthread_mutex_trylock(m)) == 0) {
407 e_msg(file, line, M_ERROR, 0, _("Mutex unlock not locked. ERR=%s\n"),
408 be.bstrerror(errstat));
410 if ((errstat=pthread_mutex_unlock(m))) {
412 e_msg(file, line, M_ABORT, 0, _("Mutex unlock failure. ERR=%s\n"),
413 be.bstrerror(errstat));
419 void _p(pthread_mutex_t *m)
422 if ((errstat=pthread_mutex_lock(m))) {
424 e_msg(__FILE__, __LINE__, M_ABORT, 0, _("Mutex lock failure. ERR=%s\n"),
425 be.bstrerror(errstat));
429 void _v(pthread_mutex_t *m)
432 if ((errstat=pthread_mutex_unlock(m))) {
434 e_msg(__FILE__, __LINE__, M_ABORT, 0, _("Mutex unlock failure. ERR=%s\n"),
435 be.bstrerror(errstat));
439 #endif /* DEBUG_MUTEX */
442 /* These routines are not normally turned on */
444 void b_memset(const char *file, int line, void *mem, int val, size_t num)
446 /* Testing for 2000 byte zero at beginning of Volume block */
447 if (num > 1900 && num < 3000) {
448 Pmsg3(000, _("Memset for %d bytes at %s:%d\n"), (int)num, file, line);
450 memset(mem, val, num);
454 #if !defined(HAVE_WIN32)
455 static int del_pid_file_ok = FALSE;
459 * Create a standard "Unix" pid file.
461 void create_pid_file(char *dir, const char *progname, int port)
463 #if !defined(HAVE_WIN32)
467 POOLMEM *fname = get_pool_memory(PM_FNAME);
470 Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
471 if (stat(fname, &statp) == 0) {
472 /* File exists, see what we have */
474 if ((pidfd = open(fname, O_RDONLY|O_BINARY, 0)) < 0 ||
475 read(pidfd, &pidbuf, sizeof(pidbuf)) < 0 ||
476 sscanf(pidbuf, "%d", &oldpid) != 1) {
477 Emsg2(M_ERROR_TERM, 0, _("Cannot open pid file. %s ERR=%s\n"), fname, strerror(errno));
479 /* Some OSes (IRIX) don't bother to clean out the old pid files after a crash, and
480 * since they use a deterministic algorithm for assigning PIDs, we can have
481 * pid conflicts with the old PID file after a reboot.
482 * The intent the following code is to check if the oldpid read from the pid
483 * file is the same as the currently executing process's pid,
484 * and if oldpid == getpid(), skip the attempt to
485 * kill(oldpid,0), since the attempt is guaranteed to succeed,
486 * but the success won't actually mean that there is an
487 * another Bacula process already running.
488 * For more details see bug #797.
490 if ((oldpid != (int)getpid()) && (kill(oldpid, 0) != -1 || errno != ESRCH)) {
491 Emsg3(M_ERROR_TERM, 0, _("%s is already running. pid=%d\nCheck file %s\n"),
492 progname, oldpid, fname);
494 /* He is not alive, so take over file ownership */
495 unlink(fname); /* remove stale pid file */
497 /* Create new pid file */
498 if ((pidfd = open(fname, O_CREAT|O_TRUNC|O_WRONLY|O_BINARY, 0640)) >= 0) {
499 len = sprintf(pidbuf, "%d\n", (int)getpid());
500 write(pidfd, pidbuf, len);
502 del_pid_file_ok = TRUE; /* we created it so we can delete it */
504 Emsg2(M_ERROR_TERM, 0, _("Could not open pid file. %s ERR=%s\n"), fname, strerror(errno));
506 free_pool_memory(fname);
512 * Delete the pid file if we created it
514 int delete_pid_file(char *dir, const char *progname, int port)
516 #if !defined(HAVE_WIN32)
517 POOLMEM *fname = get_pool_memory(PM_FNAME);
519 if (!del_pid_file_ok) {
520 free_pool_memory(fname);
523 del_pid_file_ok = FALSE;
524 Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
526 free_pool_memory(fname);
534 uint64_t last_jobs_addr;
535 uint64_t reserved[20];
538 static struct s_state_hdr state_hdr = {
545 * Open and read the state file for the daemon
547 void read_state_file(char *dir, const char *progname, int port)
552 POOLMEM *fname = get_pool_memory(PM_FNAME);
553 struct s_state_hdr hdr;
554 int hdr_size = sizeof(hdr);
556 Mmsg(&fname, "%s/%s.%d.state", dir, progname, port);
557 /* If file exists, see what we have */
558 // Dmsg1(10, "O_BINARY=%d\n", O_BINARY);
559 if ((sfd = open(fname, O_RDONLY|O_BINARY)) < 0) {
560 Dmsg3(010, "Could not open state file. sfd=%d size=%d: ERR=%s\n",
561 sfd, sizeof(hdr), strerror(errno));
564 if ((stat=read(sfd, &hdr, hdr_size)) != hdr_size) {
565 Dmsg4(010, "Could not read state file. sfd=%d stat=%d size=%d: ERR=%s\n",
566 sfd, (int)stat, hdr_size, strerror(errno));
569 if (hdr.version != state_hdr.version) {
570 Dmsg2(010, "Bad hdr version. Wanted %d got %d\n",
571 state_hdr.version, hdr.version);
575 if (strcmp(hdr.id, state_hdr.id) != 0) {
576 Dmsg0(000, "State file header id invalid.\n");
579 // Dmsg1(010, "Read header of %d bytes.\n", sizeof(hdr));
580 if (!read_last_jobs_list(sfd, hdr.last_jobs_addr)) {
591 free_pool_memory(fname);
595 * Write the state file
597 void write_state_file(char *dir, const char *progname, int port)
601 POOLMEM *fname = get_pool_memory(PM_FNAME);
603 Mmsg(&fname, "%s/%s.%d.state", dir, progname, port);
604 /* Create new state file */
606 if ((sfd = open(fname, O_CREAT|O_WRONLY|O_BINARY, 0640)) < 0) {
608 Dmsg2(000, "Could not create state file. %s ERR=%s\n", fname, be.bstrerror());
609 Emsg2(M_ERROR, 0, _("Could not create state file. %s ERR=%s\n"), fname, be.bstrerror());
612 if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
614 Dmsg1(000, "Write hdr error: ERR=%s\n", be.bstrerror());
617 // Dmsg1(010, "Wrote header of %d bytes\n", sizeof(state_hdr));
618 state_hdr.last_jobs_addr = sizeof(state_hdr);
619 state_hdr.reserved[0] = write_last_jobs_list(sfd, state_hdr.last_jobs_addr);
620 // Dmsg1(010, "write last job end = %d\n", (int)state_hdr.reserved[0]);
621 if (lseek(sfd, 0, SEEK_SET) < 0) {
623 Dmsg1(000, "lseek error: ERR=%s\n", be.bstrerror());
626 if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
628 Pmsg1(000, _("Write final hdr error: ERR=%s\n"), be.bstrerror());
632 // Dmsg1(010, "rewrote header = %d\n", sizeof(state_hdr));
640 free_pool_memory(fname);
645 * Drop to privilege new userid and new gid if non-NULL
647 void drop(char *uname, char *gname)
649 #if defined(HAVE_PWD_H) && defined(HAVE_GRP_H)
650 struct passwd *passw = NULL;
651 struct group *group = NULL;
656 Dmsg2(900, "uname=%s gname=%s\n", uname?uname:"NONE", gname?gname:"NONE");
657 if (!uname && !gname) {
658 return; /* Nothing to do */
662 if ((passw = getpwnam(uname)) == NULL) {
664 Emsg2(M_ERROR_TERM, 0, _("Could not find userid=%s: ERR=%s\n"), uname,
668 if ((passw = getpwuid(getuid())) == NULL) {
670 Emsg1(M_ERROR_TERM, 0, _("Could not find password entry. ERR=%s\n"),
673 uname = passw->pw_name;
676 /* Any OS uname pointer may get overwritten, so save name, uid, and gid */
677 bstrncpy(username, uname, sizeof(username));
681 if ((group = getgrnam(gname)) == NULL) {
683 Emsg2(M_ERROR_TERM, 0, _("Could not find group=%s: ERR=%s\n"), gname,
688 if (initgroups(username, gid)) {
691 Emsg3(M_ERROR_TERM, 0, _("Could not initgroups for group=%s, userid=%s: ERR=%s\n"),
692 gname, username, be.bstrerror());
694 Emsg2(M_ERROR_TERM, 0, _("Could not initgroups for userid=%s: ERR=%s\n"),
695 username, be.bstrerror());
701 Emsg2(M_ERROR_TERM, 0, _("Could not set group=%s: ERR=%s\n"), gname,
707 Emsg1(M_ERROR_TERM, 0, _("Could not set specified userid: %s\n"), username);
713 /* BSDI does not have this. This is a *poor* simulation */
716 strtoll(const char *ptr, char **endptr, int base)
718 return (long long int)strtod(ptr, endptr);
723 * Bacula's implementation of fgets(). The difference is that it handles
724 * being interrupted by a signal (e.g. a SIGCHLD).
727 char *bfgets(char *s, int size, FILE *fd)
732 for (int i=0; i < size-1; i++) {
736 } while (ch == EOF && ferror(fd) && (errno == EINTR || errno == EAGAIN));
746 if (ch == '\r') { /* Support for Mac/Windows file format */
748 if (ch != '\n') { /* Mac (\r only) */
749 (void)ungetc(ch, fd); /* Push next character back to fd */
762 * Make a "unique" filename. It is important that if
763 * called again with the same "what" that the result
764 * will be identical. This allows us to use the file
765 * without saving its name, and re-generate the name
766 * so that it can be deleted.
768 void make_unique_filename(POOLMEM **name, int Id, char *what)
770 Mmsg(name, "%s/%s.%s.%d.tmp", working_directory, my_name, what, Id);
773 char *escape_filename(const char *file_path)
775 if (file_path == NULL || strpbrk(file_path, "\"\\") == NULL) {
779 char *escaped_path = (char *)bmalloc(2 * (strlen(file_path) + 1));
780 char *cur_char = escaped_path;
783 if (*file_path == '\\' || *file_path == '"') {
787 *cur_char++ = *file_path++;