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-2005 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 as
15 published by the Free Software Foundation; either version 2 of
16 the License, or (at your option) any later version.
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 GNU
21 General Public License for more details.
23 You should have received a copy of the GNU General Public
24 License along with this program; if not, write to the Free
25 Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
39 static pthread_mutex_t timer_mutex = PTHREAD_MUTEX_INITIALIZER;
40 static pthread_cond_t timer = PTHREAD_COND_INITIALIZER;
43 * This routine will sleep (sec, microsec). Note, however, that if a
44 * signal occurs, it will return early. It is up to the caller
45 * to recall this routine if he/she REALLY wants to sleep the
48 int bmicrosleep(time_t sec, long usec)
50 struct timespec timeout;
56 timeout.tv_nsec = usec * 1000;
59 stat = nanosleep(&timeout, NULL);
60 if (!(stat < 0 && errno == ENOSYS)) {
63 /* If we reach here it is because nanosleep is not supported by the OS */
66 /* Do it the old way */
67 gettimeofday(&tv, &tz);
68 timeout.tv_nsec += tv.tv_usec * 1000;
69 timeout.tv_sec += tv.tv_sec;
70 while (timeout.tv_nsec >= 1000000000) {
71 timeout.tv_nsec -= 1000000000;
75 Dmsg2(200, "pthread_cond_timedwait sec=%d usec=%d\n", sec, usec);
76 /* Note, this unlocks mutex during the sleep */
78 stat = pthread_cond_timedwait(&timer, &timer_mutex, &timeout);
81 Dmsg2(200, "pthread_cond_timedwait stat=%d ERR=%s\n", stat,
89 * Guarantee that the string is properly terminated */
90 char *bstrncpy(char *dest, const char *src, int maxlen)
92 strncpy(dest, src, maxlen-1);
98 * Guarantee that the string is properly terminated */
99 char *bstrncpy(char *dest, POOL_MEM &src, int maxlen)
101 strncpy(dest, src.c_str(), maxlen-1);
107 char *bstrncat(char *dest, const char *src, int maxlen)
109 strncat(dest, src, maxlen-1);
114 char *bstrncat(char *dest, POOL_MEM &src, int maxlen)
116 strncat(dest, src.c_str(), maxlen-1);
122 * Get character length of UTF-8 string
125 * U-00000000 - U-0000007F: 0xxxxxxx
126 * U-00000080 - U-000007FF: 110xxxxx 10xxxxxx
127 * U-00000800 - U-0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx
128 * U-00010000 - U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
129 * U-00200000 - U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
130 * U-04000000 - U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
132 int cstrlen(const char *str)
134 uint8_t *p = (uint8_t *)str;
137 if ((*p & 0xC0) != 0xC0) {
142 if ((*p & 0xD0) == 0xC0) {
147 if ((*p & 0xF0) == 0xD0) {
152 if ((*p & 0xF8) == 0xF0) {
157 if ((*p & 0xFC) == 0xF8) {
162 if ((*p & 0xFE) == 0xFC) {
167 p++; /* Shouln't get here but must advance */
175 void *bmalloc(size_t size)
181 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), strerror(errno));
187 void *b_malloc(const char *file, int line, size_t size)
192 buf = sm_malloc(file, line, size);
197 e_msg(file, line, M_ABORT, 0, _("Out of memory: ERR=%s\n"), strerror(errno));
203 void *brealloc (void *buf, size_t size)
205 buf = realloc(buf, size);
207 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), strerror(errno));
213 void *bcalloc (size_t size1, size_t size2)
217 buf = calloc(size1, size2);
219 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), strerror(errno));
229 int bsnprintf(char *str, int32_t size, const char *fmt, ...)
234 va_start(arg_ptr, fmt);
235 len = bvsnprintf(str, size, fmt, arg_ptr);
241 * Implement vsnprintf()
243 int bvsnprintf(char *str, int32_t size, const char *format, va_list ap)
245 #ifdef HAVE_VSNPRINTF
247 len = vsnprintf(str, size, format, ap);
255 buflen = size > BIG_BUF ? size : BIG_BUF;
256 buf = get_memory(buflen);
257 len = vsprintf(buf, format, ap);
259 Emsg0(M_ABORT, 0, _("Buffer overflow.\n"));
261 memcpy(str, buf, len);
262 str[len] = 0; /* len excludes the null */
268 #ifndef HAVE_LOCALTIME_R
270 struct tm *localtime_r(const time_t *timep, struct tm *tm)
272 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
276 ltm = localtime(timep);
278 memcpy(tm, ltm, sizeof(struct tm));
281 return ltm ? tm : NULL;
283 #endif /* HAVE_LOCALTIME_R */
285 #ifndef HAVE_READDIR_R
289 int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
291 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
297 ndir = readdir(dirp);
300 memcpy(entry, ndir, sizeof(struct dirent));
301 strcpy(entry->d_name, ndir->d_name);
311 #endif /* HAVE_READDIR_R */
314 int bstrerror(int errnum, char *buf, size_t bufsiz)
316 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
322 msg = strerror(errnum);
324 msg = _("Bad errno");
327 bstrncpy(buf, msg, bufsiz);
333 * These are mutex routines that do error checking
334 * for deadlock and such. Normally not turned on.
337 void _p(char *file, int line, pthread_mutex_t *m)
340 if ((errstat = pthread_mutex_trylock(m))) {
341 e_msg(file, line, M_ERROR, 0, _("Possible mutex deadlock.\n"));
342 /* We didn't get the lock, so do it definitely now */
343 if ((errstat=pthread_mutex_lock(m))) {
345 e_msg(file, line, M_ABORT, 0, _("Mutex lock failure. ERR=%s\n"),
346 be.strerror(errstat));
348 e_msg(file, line, M_ERROR, 0, _("Possible mutex deadlock resolved.\n"));
354 void _v(char *file, int line, pthread_mutex_t *m)
358 if ((errstat=pthread_mutex_trylock(m)) == 0) {
360 e_msg(file, line, M_ERROR, 0, _("Mutex unlock not locked. ERR=%s\n"),
361 be.strerror(errstat));
363 if ((errstat=pthread_mutex_unlock(m))) {
365 e_msg(file, line, M_ABORT, 0, _("Mutex unlock failure. ERR=%s\n"),
366 be.strerror(errstat));
372 void _p(pthread_mutex_t *m)
375 if ((errstat=pthread_mutex_lock(m))) {
377 e_msg(__FILE__, __LINE__, M_ABORT, 0, _("Mutex lock failure. ERR=%s\n"),
378 be.strerror(errstat));
382 void _v(pthread_mutex_t *m)
385 if ((errstat=pthread_mutex_unlock(m))) {
387 e_msg(__FILE__, __LINE__, M_ABORT, 0, _("Mutex unlock failure. ERR=%s\n"),
388 be.strerror(errstat));
392 #endif /* DEBUG_MUTEX */
395 /* These routines are not normally turned on */
397 void b_memset(const char *file, int line, void *mem, int val, size_t num)
399 /* Testing for 2000 byte zero at beginning of Volume block */
400 if (num > 1900 && num < 3000) {
401 Pmsg3(000, "Memset for %d bytes at %s:%d\n", (int)num, file, line);
403 memset(mem, val, num);
407 #if !defined(HAVE_CYGWIN) && !defined(HAVE_WIN32)
408 static int del_pid_file_ok = FALSE;
412 * Create a standard "Unix" pid file.
414 void create_pid_file(char *dir, const char *progname, int port)
416 #if !defined(HAVE_CYGWIN) && !defined(HAVE_WIN32)
420 POOLMEM *fname = get_pool_memory(PM_FNAME);
423 Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
424 if (stat(fname, &statp) == 0) {
425 /* File exists, see what we have */
427 if ((pidfd = open(fname, O_RDONLY|O_BINARY, 0)) < 0 ||
428 read(pidfd, &pidbuf, sizeof(pidbuf)) < 0 ||
429 sscanf(pidbuf, "%d", &oldpid) != 1) {
430 Emsg2(M_ERROR_TERM, 0, _("Cannot open pid file. %s ERR=%s\n"), fname, strerror(errno));
432 /* See if other Bacula is still alive */
433 if (kill(oldpid, 0) != -1 || errno != ESRCH) {
434 Emsg3(M_ERROR_TERM, 0, _("%s is already running. pid=%d\nCheck file %s\n"),
435 progname, oldpid, fname);
437 /* He is not alive, so take over file ownership */
438 unlink(fname); /* remove stale pid file */
440 /* Create new pid file */
441 if ((pidfd = open(fname, O_CREAT|O_TRUNC|O_WRONLY|O_BINARY, 0640)) >= 0) {
442 len = sprintf(pidbuf, "%d\n", (int)getpid());
443 write(pidfd, pidbuf, len);
445 del_pid_file_ok = TRUE; /* we created it so we can delete it */
447 Emsg2(M_ERROR_TERM, 0, _("Could not open pid file. %s ERR=%s\n"), fname, strerror(errno));
449 free_pool_memory(fname);
455 * Delete the pid file if we created it
457 int delete_pid_file(char *dir, const char *progname, int port)
459 #if !defined(HAVE_CYGWIN) && !defined(HAVE_WIN32)
460 POOLMEM *fname = get_pool_memory(PM_FNAME);
462 if (!del_pid_file_ok) {
463 free_pool_memory(fname);
466 del_pid_file_ok = FALSE;
467 Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
469 free_pool_memory(fname);
477 uint64_t last_jobs_addr;
478 uint64_t reserved[20];
481 static struct s_state_hdr state_hdr = {
488 * Open and read the state file for the daemon
490 void read_state_file(char *dir, const char *progname, int port)
494 POOLMEM *fname = get_pool_memory(PM_FNAME);
495 struct s_state_hdr hdr;
496 int hdr_size = sizeof(hdr);
498 Mmsg(&fname, "%s/%s.%d.state", dir, progname, port);
499 /* If file exists, see what we have */
500 // Dmsg1(10, "O_BINARY=%d\n", O_BINARY);
501 if ((sfd = open(fname, O_RDONLY|O_BINARY, 0)) < 0) {
502 Dmsg3(010, "Could not open state file. sfd=%d size=%d: ERR=%s\n",
503 sfd, sizeof(hdr), strerror(errno));
506 if ((stat=read(sfd, &hdr, hdr_size)) != hdr_size) {
507 Dmsg4(010, "Could not read state file. sfd=%d stat=%d size=%d: ERR=%s\n",
508 sfd, (int)stat, hdr_size, strerror(errno));
511 if (hdr.version != state_hdr.version) {
512 Dmsg2(010, "Bad hdr version. Wanted %d got %d\n",
513 state_hdr.version, hdr.version);
516 if (strcmp(hdr.id, state_hdr.id) != 0) {
517 Dmsg0(000, "State file header id invalid.\n");
520 // Dmsg1(010, "Read header of %d bytes.\n", sizeof(hdr));
521 read_last_jobs_list(sfd, hdr.last_jobs_addr);
526 free_pool_memory(fname);
530 * Write the state file
532 void write_state_file(char *dir, const char *progname, int port)
535 POOLMEM *fname = get_pool_memory(PM_FNAME);
537 Mmsg(&fname, "%s/%s.%d.state", dir, progname, port);
538 /* Create new state file */
539 if ((sfd = open(fname, O_CREAT|O_WRONLY|O_BINARY, 0640)) < 0) {
540 Dmsg2(000, _("Could not create state file. %s ERR=%s\n"), fname, strerror(errno));
541 Emsg2(M_ERROR, 0, _("Could not create state file. %s ERR=%s\n"), fname, strerror(errno));
544 if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
545 Dmsg1(000, "Write hdr error: ERR=%s\n", strerror(errno));
548 // Dmsg1(010, "Wrote header of %d bytes\n", sizeof(state_hdr));
549 state_hdr.last_jobs_addr = sizeof(state_hdr);
550 state_hdr.reserved[0] = write_last_jobs_list(sfd, state_hdr.last_jobs_addr);
551 // Dmsg1(010, "write last job end = %d\n", (int)state_hdr.reserved[0]);
552 if (lseek(sfd, 0, SEEK_SET) < 0) {
553 Dmsg1(000, "lseek error: ERR=%s\n", strerror(errno));
556 if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
557 Pmsg1(000, "Write final hdr error: ERR=%s\n", strerror(errno));
559 // Dmsg1(010, "rewrote header = %d\n", sizeof(state_hdr));
564 free_pool_memory(fname);
569 * Drop to privilege new userid and new gid if non-NULL
571 void drop(char *uid, char *gid)
578 if ((group = getgrnam(gid)) == NULL) {
579 Emsg1(M_ERROR_TERM, 0, _("Could not find specified group: %s\n"), gid);
581 if (setgid(group->gr_gid)) {
582 Emsg1(M_ERROR_TERM, 0, _("Could not set specified group: %s\n"), gid);
584 gr_list[0] = group->gr_gid;
585 if (setgroups(1, gr_list)) {
586 Emsg1(M_ERROR_TERM, 0, _("Could not set specified group: %s\n"), gid);
593 struct passwd *passw;
594 if ((passw = getpwnam(uid)) == NULL) {
595 Emsg1(M_ERROR_TERM, 0, _("Could not find specified userid: %s\n"), uid);
597 if (setuid(passw->pw_uid)) {
598 Emsg1(M_ERROR_TERM, 0, _("Could not set specified userid: %s\n"), uid);
606 /* BSDI does not have this. This is a *poor* simulation */
609 strtoll(const char *ptr, char **endptr, int base)
611 return (long long int)strtod(ptr, endptr);
616 * Bacula's implementation of fgets(). The difference is that it handles
617 * being interrupted by a signal (e.g. a SIGCHLD).
620 char *bfgets(char *s, int size, FILE *fd)
625 for (int i=0; i < size-1; i++) {
629 } while (ch == -1 && (errno == EINTR || errno == EAGAIN));
639 if (ch == '\r') { /* Support for Mac/Windows file format */
641 if (ch == '\n') { /* Windows (\r\n) */
645 else { /* Mac (\r only) */
646 ungetc(ch, fd); /* Push next character back to fd */
658 * Make a "unique" filename. It is important that if
659 * called again with the same "what" that the result
660 * will be identical. This allows us to use the file
661 * without saving its name, and re-generate the name
662 * so that it can be deleted.
664 void make_unique_filename(POOLMEM **name, int Id, char *what)
666 Mmsg(name, "%s/%s.%s.%d.tmp", working_directory, my_name, what, Id);