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 Copyright (C) 2000-2006 Kern Sibbald
13 This program is free software; you can redistribute it and/or
14 modify it under the terms of the GNU General Public License
15 version 2 as amended with additional clauses defined in the
16 file LICENSE in the main source directory.
18 This program is distributed in the hope that it will be useful,
19 but WITHOUT ANY WARRANTY; without even the implied warranty of
20 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 the file LICENSE for additional details.
34 static pthread_mutex_t timer_mutex = PTHREAD_MUTEX_INITIALIZER;
35 static pthread_cond_t timer = PTHREAD_COND_INITIALIZER;
38 * This routine will sleep (sec, microsec). Note, however, that if a
39 * signal occurs, it will return early. It is up to the caller
40 * to recall this routine if he/she REALLY wants to sleep the
43 int bmicrosleep(time_t sec, long usec)
45 struct timespec timeout;
51 timeout.tv_nsec = usec * 1000;
54 stat = nanosleep(&timeout, NULL);
55 if (!(stat < 0 && errno == ENOSYS)) {
58 /* If we reach here it is because nanosleep is not supported by the OS */
61 /* Do it the old way */
62 gettimeofday(&tv, &tz);
63 timeout.tv_nsec += tv.tv_usec * 1000;
64 timeout.tv_sec += tv.tv_sec;
65 while (timeout.tv_nsec >= 1000000000) {
66 timeout.tv_nsec -= 1000000000;
70 Dmsg2(200, "pthread_cond_timedwait sec=%d usec=%d\n", sec, usec);
71 /* Note, this unlocks mutex during the sleep */
73 stat = pthread_cond_timedwait(&timer, &timer_mutex, &timeout);
76 Dmsg2(200, "pthread_cond_timedwait stat=%d ERR=%s\n", stat,
84 * Guarantee that the string is properly terminated */
85 char *bstrncpy(char *dest, const char *src, int maxlen)
87 strncpy(dest, src, maxlen-1);
93 * Guarantee that the string is properly terminated */
94 char *bstrncpy(char *dest, POOL_MEM &src, int maxlen)
96 strncpy(dest, src.c_str(), maxlen-1);
102 char *bstrncat(char *dest, const char *src, int maxlen)
104 strncat(dest, src, maxlen-1);
109 char *bstrncat(char *dest, POOL_MEM &src, int maxlen)
111 strncat(dest, src.c_str(), maxlen-1);
117 * Allows one or both pointers to be NULL
119 bool bstrcmp(const char *s1, const char *s2)
121 if (s1 == s2) return true;
122 if (s1 == NULL || s2 == NULL) return false;
123 return strcmp(s1, s2) == 0;
127 * Get character length of UTF-8 string
130 * U-00000000 - U-0000007F: 0xxxxxxx
131 * U-00000080 - U-000007FF: 110xxxxx 10xxxxxx
132 * U-00000800 - U-0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx
133 * U-00010000 - U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
134 * U-00200000 - U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
135 * U-04000000 - U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
137 int cstrlen(const char *str)
139 uint8_t *p = (uint8_t *)str;
142 if ((*p & 0xC0) != 0xC0) {
147 if ((*p & 0xD0) == 0xC0) {
152 if ((*p & 0xF0) == 0xD0) {
157 if ((*p & 0xF8) == 0xF0) {
162 if ((*p & 0xFC) == 0xF8) {
167 if ((*p & 0xFE) == 0xFC) {
172 p++; /* Shouln't get here but must advance */
180 void *bmalloc(size_t size)
185 buf = sm_malloc(file, line, size);
191 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.strerror());
197 void *b_malloc(const char *file, int line, size_t size)
202 buf = sm_malloc(file, line, size);
208 e_msg(file, line, M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.strerror());
214 void bfree(void *buf)
217 sm_free(__FILE__, __LINE__, buf);
226 void *brealloc (void *buf, size_t size)
228 buf = realloc(buf, size);
231 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.strerror());
237 void *bcalloc (size_t size1, size_t size2)
241 buf = calloc(size1, size2);
244 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.strerror());
249 /* Code now in src/lib/bsnprintf.c */
250 #ifndef USE_BSNPRINTF
256 int bsnprintf(char *str, int32_t size, const char *fmt, ...)
261 va_start(arg_ptr, fmt);
262 len = bvsnprintf(str, size, fmt, arg_ptr);
268 * Implement vsnprintf()
270 int bvsnprintf(char *str, int32_t size, const char *format, va_list ap)
272 #ifdef HAVE_VSNPRINTF
274 len = vsnprintf(str, size, format, ap);
282 buflen = size > BIG_BUF ? size : BIG_BUF;
283 buf = get_memory(buflen);
284 len = vsprintf(buf, format, ap);
286 Emsg0(M_ABORT, 0, _("Buffer overflow.\n"));
288 memcpy(str, buf, len);
289 str[len] = 0; /* len excludes the null */
294 #endif /* USE_BSNPRINTF */
296 #ifndef HAVE_LOCALTIME_R
298 struct tm *localtime_r(const time_t *timep, struct tm *tm)
300 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
304 ltm = localtime(timep);
306 memcpy(tm, ltm, sizeof(struct tm));
309 return ltm ? tm : NULL;
311 #endif /* HAVE_LOCALTIME_R */
313 #ifndef HAVE_READDIR_R
317 int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
319 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
325 ndir = readdir(dirp);
328 memcpy(entry, ndir, sizeof(struct dirent));
329 strcpy(entry->d_name, ndir->d_name);
339 #endif /* HAVE_READDIR_R */
342 int bstrerror(int errnum, char *buf, size_t bufsiz)
344 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
350 msg = strerror(errnum);
352 msg = _("Bad errno");
355 bstrncpy(buf, msg, bufsiz);
361 * These are mutex routines that do error checking
362 * for deadlock and such. Normally not turned on.
365 void _p(char *file, int line, pthread_mutex_t *m)
368 if ((errstat = pthread_mutex_trylock(m))) {
369 e_msg(file, line, M_ERROR, 0, _("Possible mutex deadlock.\n"));
370 /* We didn't get the lock, so do it definitely now */
371 if ((errstat=pthread_mutex_lock(m))) {
373 e_msg(file, line, M_ABORT, 0, _("Mutex lock failure. ERR=%s\n"),
374 be.strerror(errstat));
376 e_msg(file, line, M_ERROR, 0, _("Possible mutex deadlock resolved.\n"));
382 void _v(char *file, int line, pthread_mutex_t *m)
386 /* Note, this trylock *should* fail if the mutex is locked */
387 if ((errstat=pthread_mutex_trylock(m)) == 0) {
389 e_msg(file, line, M_ERROR, 0, _("Mutex unlock not locked. ERR=%s\n"),
390 be.strerror(errstat));
392 if ((errstat=pthread_mutex_unlock(m))) {
394 e_msg(file, line, M_ABORT, 0, _("Mutex unlock failure. ERR=%s\n"),
395 be.strerror(errstat));
401 void _p(pthread_mutex_t *m)
404 if ((errstat=pthread_mutex_lock(m))) {
406 e_msg(__FILE__, __LINE__, M_ABORT, 0, _("Mutex lock failure. ERR=%s\n"),
407 be.strerror(errstat));
411 void _v(pthread_mutex_t *m)
414 if ((errstat=pthread_mutex_unlock(m))) {
416 e_msg(__FILE__, __LINE__, M_ABORT, 0, _("Mutex unlock failure. ERR=%s\n"),
417 be.strerror(errstat));
421 #endif /* DEBUG_MUTEX */
424 /* These routines are not normally turned on */
426 void b_memset(const char *file, int line, void *mem, int val, size_t num)
428 /* Testing for 2000 byte zero at beginning of Volume block */
429 if (num > 1900 && num < 3000) {
430 Pmsg3(000, _("Memset for %d bytes at %s:%d\n"), (int)num, file, line);
432 memset(mem, val, num);
436 #if !defined(HAVE_WIN32)
437 static int del_pid_file_ok = FALSE;
441 * Create a standard "Unix" pid file.
443 void create_pid_file(char *dir, const char *progname, int port)
445 #if !defined(HAVE_WIN32)
449 POOLMEM *fname = get_pool_memory(PM_FNAME);
452 Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
453 if (stat(fname, &statp) == 0) {
454 /* File exists, see what we have */
456 if ((pidfd = open(fname, O_RDONLY|O_BINARY, 0)) < 0 ||
457 read(pidfd, &pidbuf, sizeof(pidbuf)) < 0 ||
458 sscanf(pidbuf, "%d", &oldpid) != 1) {
459 Emsg2(M_ERROR_TERM, 0, _("Cannot open pid file. %s ERR=%s\n"), fname, strerror(errno));
461 /* See if other Bacula is still alive */
462 if (kill(oldpid, 0) != -1 || errno != ESRCH) {
463 Emsg3(M_ERROR_TERM, 0, _("%s is already running. pid=%d\nCheck file %s\n"),
464 progname, oldpid, fname);
466 /* He is not alive, so take over file ownership */
467 unlink(fname); /* remove stale pid file */
469 /* Create new pid file */
470 if ((pidfd = open(fname, O_CREAT|O_TRUNC|O_WRONLY|O_BINARY, 0640)) >= 0) {
471 len = sprintf(pidbuf, "%d\n", (int)getpid());
472 write(pidfd, pidbuf, len);
474 del_pid_file_ok = TRUE; /* we created it so we can delete it */
476 Emsg2(M_ERROR_TERM, 0, _("Could not open pid file. %s ERR=%s\n"), fname, strerror(errno));
478 free_pool_memory(fname);
484 * Delete the pid file if we created it
486 int delete_pid_file(char *dir, const char *progname, int port)
488 #if !defined(HAVE_WIN32)
489 POOLMEM *fname = get_pool_memory(PM_FNAME);
491 if (!del_pid_file_ok) {
492 free_pool_memory(fname);
495 del_pid_file_ok = FALSE;
496 Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
498 free_pool_memory(fname);
506 uint64_t last_jobs_addr;
507 uint64_t reserved[20];
510 static struct s_state_hdr state_hdr = {
517 * Open and read the state file for the daemon
519 void read_state_file(char *dir, const char *progname, int port)
524 POOLMEM *fname = get_pool_memory(PM_FNAME);
525 struct s_state_hdr hdr;
526 int hdr_size = sizeof(hdr);
528 Mmsg(&fname, "%s/%s.%d.state", dir, progname, port);
529 /* If file exists, see what we have */
530 // Dmsg1(10, "O_BINARY=%d\n", O_BINARY);
531 if ((sfd = open(fname, O_RDONLY|O_BINARY)) < 0) {
532 Dmsg3(010, "Could not open state file. sfd=%d size=%d: ERR=%s\n",
533 sfd, sizeof(hdr), strerror(errno));
536 if ((stat=read(sfd, &hdr, hdr_size)) != hdr_size) {
537 Dmsg4(010, "Could not read state file. sfd=%d stat=%d size=%d: ERR=%s\n",
538 sfd, (int)stat, hdr_size, strerror(errno));
541 if (hdr.version != state_hdr.version) {
542 Dmsg2(010, "Bad hdr version. Wanted %d got %d\n",
543 state_hdr.version, hdr.version);
547 if (strcmp(hdr.id, state_hdr.id) != 0) {
548 Dmsg0(000, "State file header id invalid.\n");
551 // Dmsg1(010, "Read header of %d bytes.\n", sizeof(hdr));
552 if (!read_last_jobs_list(sfd, hdr.last_jobs_addr)) {
563 free_pool_memory(fname);
567 * Write the state file
569 void write_state_file(char *dir, const char *progname, int port)
573 POOLMEM *fname = get_pool_memory(PM_FNAME);
575 Mmsg(&fname, "%s/%s.%d.state", dir, progname, port);
576 /* Create new state file */
578 if ((sfd = open(fname, O_CREAT|O_WRONLY|O_BINARY, 0640)) < 0) {
580 Dmsg2(000, "Could not create state file. %s ERR=%s\n", fname, be.strerror());
581 Emsg2(M_ERROR, 0, _("Could not create state file. %s ERR=%s\n"), fname, be.strerror());
584 if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
586 Dmsg1(000, "Write hdr error: ERR=%s\n", be.strerror());
589 // Dmsg1(010, "Wrote header of %d bytes\n", sizeof(state_hdr));
590 state_hdr.last_jobs_addr = sizeof(state_hdr);
591 state_hdr.reserved[0] = write_last_jobs_list(sfd, state_hdr.last_jobs_addr);
592 // Dmsg1(010, "write last job end = %d\n", (int)state_hdr.reserved[0]);
593 if (lseek(sfd, 0, SEEK_SET) < 0) {
595 Dmsg1(000, "lseek error: ERR=%s\n", be.strerror());
598 if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
600 Pmsg1(000, _("Write final hdr error: ERR=%s\n"), be.strerror());
604 // Dmsg1(010, "rewrote header = %d\n", sizeof(state_hdr));
612 free_pool_memory(fname);
617 * Drop to privilege new userid and new gid if non-NULL
619 void drop(char *uname, char *gname)
621 #if defined(HAVE_PWD_H) && defined(HAVE_GRP_H)
622 struct passwd *passw = NULL;
623 struct group *group = NULL;
628 Dmsg2(900, "uname=%s gname=%s\n", uname?uname:"NONE", gname?gname:"NONE");
629 if (!uname && !gname) {
630 return; /* Nothing to do */
634 if ((passw = getpwnam(uname)) == NULL) {
636 Emsg2(M_ERROR_TERM, 0, _("Could not find userid=%s: ERR=%s\n"), uname,
640 if ((passw = getpwuid(getuid())) == NULL) {
642 Emsg1(M_ERROR_TERM, 0, _("Could not find password entry. ERR=%s\n"),
645 uname = passw->pw_name;
648 /* Any OS uname pointer may get overwritten, so save name, uid, and gid */
649 bstrncpy(username, uname, sizeof(username));
653 if ((group = getgrnam(gname)) == NULL) {
655 Emsg2(M_ERROR_TERM, 0, _("Could not find group=%s: ERR=%s\n"), gname,
660 if (initgroups(username, gid)) {
663 Emsg3(M_ERROR_TERM, 0, _("Could not initgroups for group=%s, userid=%s: ERR=%s\n"),
664 gname, username, be.strerror());
666 Emsg2(M_ERROR_TERM, 0, _("Could not initgroups for userid=%s: ERR=%s\n"),
667 username, be.strerror());
673 Emsg2(M_ERROR_TERM, 0, _("Could not set group=%s: ERR=%s\n"), gname,
679 Emsg1(M_ERROR_TERM, 0, _("Could not set specified userid: %s\n"), username);
685 /* BSDI does not have this. This is a *poor* simulation */
688 strtoll(const char *ptr, char **endptr, int base)
690 return (long long int)strtod(ptr, endptr);
695 * Bacula's implementation of fgets(). The difference is that it handles
696 * being interrupted by a signal (e.g. a SIGCHLD).
699 char *bfgets(char *s, int size, FILE *fd)
704 for (int i=0; i < size-1; i++) {
708 } while (ch == -1 && (errno == EINTR || errno == EAGAIN));
718 if (ch == '\r') { /* Support for Mac/Windows file format */
720 if (ch == '\n') { /* Windows (\r\n) */
724 else { /* Mac (\r only) */
725 (void)ungetc(ch, fd); /* Push next character back to fd */
737 * Make a "unique" filename. It is important that if
738 * called again with the same "what" that the result
739 * will be identical. This allows us to use the file
740 * without saving its name, and re-generate the name
741 * so that it can be deleted.
743 void make_unique_filename(POOLMEM **name, int Id, char *what)
745 Mmsg(name, "%s/%s.%s.%d.tmp", working_directory, my_name, what, Id);
748 char *escape_filename(const char *file_path)
750 if (file_path == NULL || strpbrk(file_path, "\"\\") == NULL) {
754 char *escaped_path = (char *)bmalloc(2 * (strlen(file_path) + 1));
755 char *cur_char = escaped_path;
758 if (*file_path == '\\' || *file_path == '"') {
762 *cur_char++ = *file_path++;