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 plus additions
11 that are listed in the file LICENSE.
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
46 static pthread_mutex_t timer_mutex = PTHREAD_MUTEX_INITIALIZER;
47 static pthread_cond_t timer = PTHREAD_COND_INITIALIZER;
50 * This routine will sleep (sec, microsec). Note, however, that if a
51 * signal occurs, it will return early. It is up to the caller
52 * to recall this routine if he/she REALLY wants to sleep the
55 int bmicrosleep(time_t sec, long usec)
57 struct timespec timeout;
63 timeout.tv_nsec = usec * 1000;
66 stat = nanosleep(&timeout, NULL);
67 if (!(stat < 0 && errno == ENOSYS)) {
70 /* If we reach here it is because nanosleep is not supported by the OS */
73 /* Do it the old way */
74 gettimeofday(&tv, &tz);
75 timeout.tv_nsec += tv.tv_usec * 1000;
76 timeout.tv_sec += tv.tv_sec;
77 while (timeout.tv_nsec >= 1000000000) {
78 timeout.tv_nsec -= 1000000000;
82 Dmsg2(200, "pthread_cond_timedwait sec=%d usec=%d\n", sec, usec);
83 /* Note, this unlocks mutex during the sleep */
85 stat = pthread_cond_timedwait(&timer, &timer_mutex, &timeout);
88 Dmsg2(200, "pthread_cond_timedwait stat=%d ERR=%s\n", stat,
96 * Guarantee that the string is properly terminated */
97 char *bstrncpy(char *dest, const char *src, int maxlen)
99 strncpy(dest, src, maxlen-1);
105 * Guarantee that the string is properly terminated */
106 char *bstrncpy(char *dest, POOL_MEM &src, int maxlen)
108 strncpy(dest, src.c_str(), maxlen-1);
114 char *bstrncat(char *dest, const char *src, int maxlen)
116 strncat(dest, src, maxlen-1);
121 char *bstrncat(char *dest, POOL_MEM &src, int maxlen)
123 strncat(dest, src.c_str(), maxlen-1);
129 * Allows one or both pointers to be NULL
131 bool bstrcmp(const char *s1, const char *s2)
133 if (s1 == s2) return true;
134 if (s1 == NULL || s2 == NULL) return false;
135 return strcmp(s1, s2) == 0;
139 * Get character length of UTF-8 string
142 * U-00000000 - U-0000007F: 0xxxxxxx
143 * U-00000080 - U-000007FF: 110xxxxx 10xxxxxx
144 * U-00000800 - U-0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx
145 * U-00010000 - U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
146 * U-00200000 - U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
147 * U-04000000 - U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
149 int cstrlen(const char *str)
151 uint8_t *p = (uint8_t *)str;
154 if ((*p & 0xC0) != 0xC0) {
159 if ((*p & 0xD0) == 0xC0) {
164 if ((*p & 0xF0) == 0xD0) {
169 if ((*p & 0xF8) == 0xF0) {
174 if ((*p & 0xFC) == 0xF8) {
179 if ((*p & 0xFE) == 0xFC) {
184 p++; /* Shouln't get here but must advance */
192 void *bmalloc(size_t size)
197 buf = sm_malloc(file, line, size);
203 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.strerror());
209 void *b_malloc(const char *file, int line, size_t size)
214 buf = sm_malloc(file, line, size);
220 e_msg(file, line, M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.strerror());
226 void bfree(void *buf)
229 sm_free(__FILE__, __LINE__, buf);
235 void *brealloc (void *buf, size_t size)
237 buf = realloc(buf, size);
240 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.strerror());
246 void *bcalloc (size_t size1, size_t size2)
250 buf = calloc(size1, size2);
253 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.strerror());
258 /* Code now in src/lib/bsnprintf.c */
259 #ifndef USE_BSNPRINTF
265 int bsnprintf(char *str, int32_t size, const char *fmt, ...)
270 va_start(arg_ptr, fmt);
271 len = bvsnprintf(str, size, fmt, arg_ptr);
277 * Implement vsnprintf()
279 int bvsnprintf(char *str, int32_t size, const char *format, va_list ap)
281 #ifdef HAVE_VSNPRINTF
283 len = vsnprintf(str, size, format, ap);
291 buflen = size > BIG_BUF ? size : BIG_BUF;
292 buf = get_memory(buflen);
293 len = vsprintf(buf, format, ap);
295 Emsg0(M_ABORT, 0, _("Buffer overflow.\n"));
297 memcpy(str, buf, len);
298 str[len] = 0; /* len excludes the null */
303 #endif /* USE_BSNPRINTF */
305 #ifndef HAVE_LOCALTIME_R
307 struct tm *localtime_r(const time_t *timep, struct tm *tm)
309 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
313 ltm = localtime(timep);
315 memcpy(tm, ltm, sizeof(struct tm));
318 return ltm ? tm : NULL;
320 #endif /* HAVE_LOCALTIME_R */
322 #ifndef HAVE_READDIR_R
326 int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
328 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
334 ndir = readdir(dirp);
337 memcpy(entry, ndir, sizeof(struct dirent));
338 strcpy(entry->d_name, ndir->d_name);
348 #endif /* HAVE_READDIR_R */
351 int b_strerror(int errnum, char *buf, size_t bufsiz)
353 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
359 msg = strerror(errnum);
361 msg = _("Bad errno");
364 bstrncpy(buf, msg, bufsiz);
370 * These are mutex routines that do error checking
371 * for deadlock and such. Normally not turned on.
374 void _p(char *file, int line, pthread_mutex_t *m)
377 if ((errstat = pthread_mutex_trylock(m))) {
378 e_msg(file, line, M_ERROR, 0, _("Possible mutex deadlock.\n"));
379 /* We didn't get the lock, so do it definitely now */
380 if ((errstat=pthread_mutex_lock(m))) {
382 e_msg(file, line, M_ABORT, 0, _("Mutex lock failure. ERR=%s\n"),
383 be.strerror(errstat));
385 e_msg(file, line, M_ERROR, 0, _("Possible mutex deadlock resolved.\n"));
391 void _v(char *file, int line, pthread_mutex_t *m)
395 /* Note, this trylock *should* fail if the mutex is locked */
396 if ((errstat=pthread_mutex_trylock(m)) == 0) {
398 e_msg(file, line, M_ERROR, 0, _("Mutex unlock not locked. ERR=%s\n"),
399 be.strerror(errstat));
401 if ((errstat=pthread_mutex_unlock(m))) {
403 e_msg(file, line, M_ABORT, 0, _("Mutex unlock failure. ERR=%s\n"),
404 be.strerror(errstat));
410 void _p(pthread_mutex_t *m)
413 if ((errstat=pthread_mutex_lock(m))) {
415 e_msg(__FILE__, __LINE__, M_ABORT, 0, _("Mutex lock failure. ERR=%s\n"),
416 be.strerror(errstat));
420 void _v(pthread_mutex_t *m)
423 if ((errstat=pthread_mutex_unlock(m))) {
425 e_msg(__FILE__, __LINE__, M_ABORT, 0, _("Mutex unlock failure. ERR=%s\n"),
426 be.strerror(errstat));
430 #endif /* DEBUG_MUTEX */
433 /* These routines are not normally turned on */
435 void b_memset(const char *file, int line, void *mem, int val, size_t num)
437 /* Testing for 2000 byte zero at beginning of Volume block */
438 if (num > 1900 && num < 3000) {
439 Pmsg3(000, _("Memset for %d bytes at %s:%d\n"), (int)num, file, line);
441 memset(mem, val, num);
445 #if !defined(HAVE_WIN32)
446 static int del_pid_file_ok = FALSE;
450 * Create a standard "Unix" pid file.
452 void create_pid_file(char *dir, const char *progname, int port)
454 #if !defined(HAVE_WIN32)
458 POOLMEM *fname = get_pool_memory(PM_FNAME);
461 Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
462 if (stat(fname, &statp) == 0) {
463 /* File exists, see what we have */
465 if ((pidfd = open(fname, O_RDONLY|O_BINARY, 0)) < 0 ||
466 read(pidfd, &pidbuf, sizeof(pidbuf)) < 0 ||
467 sscanf(pidbuf, "%d", &oldpid) != 1) {
468 Emsg2(M_ERROR_TERM, 0, _("Cannot open pid file. %s ERR=%s\n"), fname, strerror(errno));
470 /* Some OSes (IRIX) don't bother to clean out the old pid files after a crash, and
471 * since they use a deterministic algorithm for assigning PIDs, we can have
472 * pid conflicts with the old PID file after a reboot.
473 * The intent the following code is to check if the oldpid read from the pid
474 * file is the same as the currently executing process's pid,
475 * and if oldpid == getpid(), skip the attempt to
476 * kill(oldpid,0), since the attempt is guaranteed to succeed,
477 * but the success won't actually mean that there is an
478 * another Bacula process already running.
479 * For more details see bug #797.
481 if ((oldpid != (int)getpid()) && (kill(oldpid, 0) != -1 || errno != ESRCH)) {
482 Emsg3(M_ERROR_TERM, 0, _("%s is already running. pid=%d\nCheck file %s\n"),
483 progname, oldpid, fname);
485 /* He is not alive, so take over file ownership */
486 unlink(fname); /* remove stale pid file */
488 /* Create new pid file */
489 if ((pidfd = open(fname, O_CREAT|O_TRUNC|O_WRONLY|O_BINARY, 0640)) >= 0) {
490 len = sprintf(pidbuf, "%d\n", (int)getpid());
491 write(pidfd, pidbuf, len);
493 del_pid_file_ok = TRUE; /* we created it so we can delete it */
495 Emsg2(M_ERROR_TERM, 0, _("Could not open pid file. %s ERR=%s\n"), fname, strerror(errno));
497 free_pool_memory(fname);
503 * Delete the pid file if we created it
505 int delete_pid_file(char *dir, const char *progname, int port)
507 #if !defined(HAVE_WIN32)
508 POOLMEM *fname = get_pool_memory(PM_FNAME);
510 if (!del_pid_file_ok) {
511 free_pool_memory(fname);
514 del_pid_file_ok = FALSE;
515 Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
517 free_pool_memory(fname);
525 uint64_t last_jobs_addr;
526 uint64_t reserved[20];
529 static struct s_state_hdr state_hdr = {
536 * Open and read the state file for the daemon
538 void read_state_file(char *dir, const char *progname, int port)
543 POOLMEM *fname = get_pool_memory(PM_FNAME);
544 struct s_state_hdr hdr;
545 int hdr_size = sizeof(hdr);
547 Mmsg(&fname, "%s/%s.%d.state", dir, progname, port);
548 /* If file exists, see what we have */
549 // Dmsg1(10, "O_BINARY=%d\n", O_BINARY);
550 if ((sfd = open(fname, O_RDONLY|O_BINARY)) < 0) {
551 Dmsg3(010, "Could not open state file. sfd=%d size=%d: ERR=%s\n",
552 sfd, sizeof(hdr), strerror(errno));
555 if ((stat=read(sfd, &hdr, hdr_size)) != hdr_size) {
556 Dmsg4(010, "Could not read state file. sfd=%d stat=%d size=%d: ERR=%s\n",
557 sfd, (int)stat, hdr_size, strerror(errno));
560 if (hdr.version != state_hdr.version) {
561 Dmsg2(010, "Bad hdr version. Wanted %d got %d\n",
562 state_hdr.version, hdr.version);
566 if (strcmp(hdr.id, state_hdr.id) != 0) {
567 Dmsg0(000, "State file header id invalid.\n");
570 // Dmsg1(010, "Read header of %d bytes.\n", sizeof(hdr));
571 if (!read_last_jobs_list(sfd, hdr.last_jobs_addr)) {
582 free_pool_memory(fname);
586 * Write the state file
588 void write_state_file(char *dir, const char *progname, int port)
592 POOLMEM *fname = get_pool_memory(PM_FNAME);
594 Mmsg(&fname, "%s/%s.%d.state", dir, progname, port);
595 /* Create new state file */
597 if ((sfd = open(fname, O_CREAT|O_WRONLY|O_BINARY, 0640)) < 0) {
599 Dmsg2(000, "Could not create state file. %s ERR=%s\n", fname, be.strerror());
600 Emsg2(M_ERROR, 0, _("Could not create state file. %s ERR=%s\n"), fname, be.strerror());
603 if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
605 Dmsg1(000, "Write hdr error: ERR=%s\n", be.strerror());
608 // Dmsg1(010, "Wrote header of %d bytes\n", sizeof(state_hdr));
609 state_hdr.last_jobs_addr = sizeof(state_hdr);
610 state_hdr.reserved[0] = write_last_jobs_list(sfd, state_hdr.last_jobs_addr);
611 // Dmsg1(010, "write last job end = %d\n", (int)state_hdr.reserved[0]);
612 if (lseek(sfd, 0, SEEK_SET) < 0) {
614 Dmsg1(000, "lseek error: ERR=%s\n", be.strerror());
617 if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
619 Pmsg1(000, _("Write final hdr error: ERR=%s\n"), be.strerror());
623 // Dmsg1(010, "rewrote header = %d\n", sizeof(state_hdr));
631 free_pool_memory(fname);
636 * Drop to privilege new userid and new gid if non-NULL
638 void drop(char *uname, char *gname)
640 #if defined(HAVE_PWD_H) && defined(HAVE_GRP_H)
641 struct passwd *passw = NULL;
642 struct group *group = NULL;
647 Dmsg2(900, "uname=%s gname=%s\n", uname?uname:"NONE", gname?gname:"NONE");
648 if (!uname && !gname) {
649 return; /* Nothing to do */
653 if ((passw = getpwnam(uname)) == NULL) {
655 Emsg2(M_ERROR_TERM, 0, _("Could not find userid=%s: ERR=%s\n"), uname,
659 if ((passw = getpwuid(getuid())) == NULL) {
661 Emsg1(M_ERROR_TERM, 0, _("Could not find password entry. ERR=%s\n"),
664 uname = passw->pw_name;
667 /* Any OS uname pointer may get overwritten, so save name, uid, and gid */
668 bstrncpy(username, uname, sizeof(username));
672 if ((group = getgrnam(gname)) == NULL) {
674 Emsg2(M_ERROR_TERM, 0, _("Could not find group=%s: ERR=%s\n"), gname,
679 if (initgroups(username, gid)) {
682 Emsg3(M_ERROR_TERM, 0, _("Could not initgroups for group=%s, userid=%s: ERR=%s\n"),
683 gname, username, be.strerror());
685 Emsg2(M_ERROR_TERM, 0, _("Could not initgroups for userid=%s: ERR=%s\n"),
686 username, be.strerror());
692 Emsg2(M_ERROR_TERM, 0, _("Could not set group=%s: ERR=%s\n"), gname,
698 Emsg1(M_ERROR_TERM, 0, _("Could not set specified userid: %s\n"), username);
704 /* BSDI does not have this. This is a *poor* simulation */
707 strtoll(const char *ptr, char **endptr, int base)
709 return (long long int)strtod(ptr, endptr);
714 * Bacula's implementation of fgets(). The difference is that it handles
715 * being interrupted by a signal (e.g. a SIGCHLD).
718 char *bfgets(char *s, int size, FILE *fd)
723 for (int i=0; i < size-1; i++) {
727 } while (ch == EOF && ferror(fd) && (errno == EINTR || errno == EAGAIN));
737 if (ch == '\r') { /* Support for Mac/Windows file format */
739 if (ch != '\n') { /* Mac (\r only) */
740 (void)ungetc(ch, fd); /* Push next character back to fd */
753 * Make a "unique" filename. It is important that if
754 * called again with the same "what" that the result
755 * will be identical. This allows us to use the file
756 * without saving its name, and re-generate the name
757 * so that it can be deleted.
759 void make_unique_filename(POOLMEM **name, int Id, char *what)
761 Mmsg(name, "%s/%s.%s.%d.tmp", working_directory, my_name, what, Id);
764 char *escape_filename(const char *file_path)
766 if (file_path == NULL || strpbrk(file_path, "\"\\") == NULL) {
770 char *escaped_path = (char *)bmalloc(2 * (strlen(file_path) + 1));
771 char *cur_char = escaped_path;
774 if (*file_path == '\\' || *file_path == '"') {
778 *cur_char++ = *file_path++;