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
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 * Get character length of UTF-8 string
120 * U-00000000 - U-0000007F: 0xxxxxxx
121 * U-00000080 - U-000007FF: 110xxxxx 10xxxxxx
122 * U-00000800 - U-0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx
123 * U-00010000 - U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
124 * U-00200000 - U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
125 * U-04000000 - U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
127 int cstrlen(const char *str)
129 uint8_t *p = (uint8_t *)str;
132 if ((*p & 0xC0) != 0xC0) {
137 if ((*p & 0xD0) == 0xC0) {
142 if ((*p & 0xF0) == 0xD0) {
147 if ((*p & 0xF8) == 0xF0) {
152 if ((*p & 0xFC) == 0xF8) {
157 if ((*p & 0xFE) == 0xFC) {
162 p++; /* Shouln't get here but must advance */
170 void *bmalloc(size_t size)
176 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), strerror(errno));
182 void *b_malloc(const char *file, int line, size_t size)
187 buf = sm_malloc(file, line, size);
192 e_msg(file, line, M_ABORT, 0, _("Out of memory: ERR=%s\n"), strerror(errno));
198 void *brealloc (void *buf, size_t size)
200 buf = realloc(buf, size);
202 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), strerror(errno));
208 void *bcalloc (size_t size1, size_t size2)
212 buf = calloc(size1, size2);
214 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), strerror(errno));
219 /* Code now in src/lib/bsnprintf.c */
220 #ifndef USE_BSNPRINTF
226 int bsnprintf(char *str, int32_t size, const char *fmt, ...)
231 va_start(arg_ptr, fmt);
232 len = bvsnprintf(str, size, fmt, arg_ptr);
238 * Implement vsnprintf()
240 int bvsnprintf(char *str, int32_t size, const char *format, va_list ap)
242 #ifdef HAVE_VSNPRINTF
244 len = vsnprintf(str, size, format, ap);
252 buflen = size > BIG_BUF ? size : BIG_BUF;
253 buf = get_memory(buflen);
254 len = vsprintf(buf, format, ap);
256 Emsg0(M_ABORT, 0, _("Buffer overflow.\n"));
258 memcpy(str, buf, len);
259 str[len] = 0; /* len excludes the null */
264 #endif /* USE_BSNPRINTF */
266 #ifndef HAVE_LOCALTIME_R
268 struct tm *localtime_r(const time_t *timep, struct tm *tm)
270 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
274 ltm = localtime(timep);
276 memcpy(tm, ltm, sizeof(struct tm));
279 return ltm ? tm : NULL;
281 #endif /* HAVE_LOCALTIME_R */
283 #ifndef HAVE_READDIR_R
287 int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
289 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
295 ndir = readdir(dirp);
298 memcpy(entry, ndir, sizeof(struct dirent));
299 strcpy(entry->d_name, ndir->d_name);
309 #endif /* HAVE_READDIR_R */
312 int bstrerror(int errnum, char *buf, size_t bufsiz)
314 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
320 msg = strerror(errnum);
322 msg = _("Bad errno");
325 bstrncpy(buf, msg, bufsiz);
331 * These are mutex routines that do error checking
332 * for deadlock and such. Normally not turned on.
335 void _p(char *file, int line, pthread_mutex_t *m)
338 if ((errstat = pthread_mutex_trylock(m))) {
339 e_msg(file, line, M_ERROR, 0, _("Possible mutex deadlock.\n"));
340 /* We didn't get the lock, so do it definitely now */
341 if ((errstat=pthread_mutex_lock(m))) {
343 e_msg(file, line, M_ABORT, 0, _("Mutex lock failure. ERR=%s\n"),
344 be.strerror(errstat));
346 e_msg(file, line, M_ERROR, 0, _("Possible mutex deadlock resolved.\n"));
352 void _v(char *file, int line, pthread_mutex_t *m)
356 if ((errstat=pthread_mutex_trylock(m)) == 0) {
358 e_msg(file, line, M_ERROR, 0, _("Mutex unlock not locked. ERR=%s\n"),
359 be.strerror(errstat));
361 if ((errstat=pthread_mutex_unlock(m))) {
363 e_msg(file, line, M_ABORT, 0, _("Mutex unlock failure. ERR=%s\n"),
364 be.strerror(errstat));
370 void _p(pthread_mutex_t *m)
373 if ((errstat=pthread_mutex_lock(m))) {
375 e_msg(__FILE__, __LINE__, M_ABORT, 0, _("Mutex lock failure. ERR=%s\n"),
376 be.strerror(errstat));
380 void _v(pthread_mutex_t *m)
383 if ((errstat=pthread_mutex_unlock(m))) {
385 e_msg(__FILE__, __LINE__, M_ABORT, 0, _("Mutex unlock failure. ERR=%s\n"),
386 be.strerror(errstat));
390 #endif /* DEBUG_MUTEX */
393 /* These routines are not normally turned on */
395 void b_memset(const char *file, int line, void *mem, int val, size_t num)
397 /* Testing for 2000 byte zero at beginning of Volume block */
398 if (num > 1900 && num < 3000) {
399 Pmsg3(000, _("Memset for %d bytes at %s:%d\n"), (int)num, file, line);
401 memset(mem, val, num);
405 #if !defined(HAVE_CYGWIN) && !defined(HAVE_WIN32)
406 static int del_pid_file_ok = FALSE;
410 * Create a standard "Unix" pid file.
412 void create_pid_file(char *dir, const char *progname, int port)
414 #if !defined(HAVE_CYGWIN) && !defined(HAVE_WIN32)
418 POOLMEM *fname = get_pool_memory(PM_FNAME);
421 Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
422 if (stat(fname, &statp) == 0) {
423 /* File exists, see what we have */
425 if ((pidfd = open(fname, O_RDONLY|O_BINARY, 0)) < 0 ||
426 read(pidfd, &pidbuf, sizeof(pidbuf)) < 0 ||
427 sscanf(pidbuf, "%d", &oldpid) != 1) {
428 Emsg2(M_ERROR_TERM, 0, _("Cannot open pid file. %s ERR=%s\n"), fname, strerror(errno));
430 /* See if other Bacula is still alive */
431 if (kill(oldpid, 0) != -1 || errno != ESRCH) {
432 Emsg3(M_ERROR_TERM, 0, _("%s is already running. pid=%d\nCheck file %s\n"),
433 progname, oldpid, fname);
435 /* He is not alive, so take over file ownership */
436 unlink(fname); /* remove stale pid file */
438 /* Create new pid file */
439 if ((pidfd = open(fname, O_CREAT|O_TRUNC|O_WRONLY|O_BINARY, 0640)) >= 0) {
440 len = sprintf(pidbuf, "%d\n", (int)getpid());
441 write(pidfd, pidbuf, len);
443 del_pid_file_ok = TRUE; /* we created it so we can delete it */
445 Emsg2(M_ERROR_TERM, 0, _("Could not open pid file. %s ERR=%s\n"), fname, strerror(errno));
447 free_pool_memory(fname);
453 * Delete the pid file if we created it
455 int delete_pid_file(char *dir, const char *progname, int port)
457 #if !defined(HAVE_CYGWIN) && !defined(HAVE_WIN32)
458 POOLMEM *fname = get_pool_memory(PM_FNAME);
460 if (!del_pid_file_ok) {
461 free_pool_memory(fname);
464 del_pid_file_ok = FALSE;
465 Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
467 free_pool_memory(fname);
475 uint64_t last_jobs_addr;
476 uint64_t reserved[20];
479 static struct s_state_hdr state_hdr = {
486 * Open and read the state file for the daemon
488 void read_state_file(char *dir, const char *progname, int port)
493 POOLMEM *fname = get_pool_memory(PM_FNAME);
494 struct s_state_hdr hdr;
495 int hdr_size = sizeof(hdr);
497 Mmsg(&fname, "%s/%s.%d.state", dir, progname, port);
498 /* If file exists, see what we have */
499 // Dmsg1(10, "O_BINARY=%d\n", O_BINARY);
500 if ((sfd = open(fname, O_RDONLY|O_BINARY, 0)) < 0) {
501 Dmsg3(010, "Could not open state file. sfd=%d size=%d: ERR=%s\n",
502 sfd, sizeof(hdr), strerror(errno));
505 if ((stat=read(sfd, &hdr, hdr_size)) != hdr_size) {
506 Dmsg4(010, "Could not read state file. sfd=%d stat=%d size=%d: ERR=%s\n",
507 sfd, (int)stat, hdr_size, strerror(errno));
510 if (hdr.version != state_hdr.version) {
511 Dmsg2(010, "Bad hdr version. Wanted %d got %d\n",
512 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 if (!read_last_jobs_list(sfd, hdr.last_jobs_addr)) {
532 free_pool_memory(fname);
536 * Write the state file
538 void write_state_file(char *dir, const char *progname, int port)
542 POOLMEM *fname = get_pool_memory(PM_FNAME);
544 Mmsg(&fname, "%s/%s.%d.state", dir, progname, port);
545 /* Create new state file */
546 if ((sfd = open(fname, O_CREAT|O_WRONLY|O_BINARY, 0640)) < 0) {
548 Dmsg2(000, "Could not create state file. %s ERR=%s\n", fname, be.strerror());
549 Emsg2(M_ERROR, 0, _("Could not create state file. %s ERR=%s\n"), fname, be.strerror());
552 if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
554 Dmsg1(000, "Write hdr error: ERR=%s\n", be.strerror());
557 // Dmsg1(010, "Wrote header of %d bytes\n", sizeof(state_hdr));
558 state_hdr.last_jobs_addr = sizeof(state_hdr);
559 state_hdr.reserved[0] = write_last_jobs_list(sfd, state_hdr.last_jobs_addr);
560 // Dmsg1(010, "write last job end = %d\n", (int)state_hdr.reserved[0]);
561 if (lseek(sfd, 0, SEEK_SET) < 0) {
563 Dmsg1(000, "lseek error: ERR=%s\n", be.strerror());
566 if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
568 Pmsg1(000, _("Write final hdr error: ERR=%s\n"), be.strerror());
572 // Dmsg1(010, "rewrote header = %d\n", sizeof(state_hdr));
580 free_pool_memory(fname);
585 * Drop to privilege new userid and new gid if non-NULL
587 void drop(char *uid, char *gid)
594 if ((group = getgrnam(gid)) == NULL) {
595 Emsg1(M_ERROR_TERM, 0, _("Could not find specified group: %s\n"), gid);
597 if (setgid(group->gr_gid)) {
598 Emsg1(M_ERROR_TERM, 0, _("Could not set specified group: %s\n"), gid);
600 gr_list[0] = group->gr_gid;
601 if (setgroups(1, gr_list)) {
602 Emsg1(M_ERROR_TERM, 0, _("Could not set specified group: %s\n"), gid);
609 struct passwd *passw;
610 if ((passw = getpwnam(uid)) == NULL) {
611 Emsg1(M_ERROR_TERM, 0, _("Could not find specified userid: %s\n"), uid);
613 if (setuid(passw->pw_uid)) {
614 Emsg1(M_ERROR_TERM, 0, _("Could not set specified userid: %s\n"), uid);
622 /* BSDI does not have this. This is a *poor* simulation */
625 strtoll(const char *ptr, char **endptr, int base)
627 return (long long int)strtod(ptr, endptr);
632 * Bacula's implementation of fgets(). The difference is that it handles
633 * being interrupted by a signal (e.g. a SIGCHLD).
636 char *bfgets(char *s, int size, FILE *fd)
641 for (int i=0; i < size-1; i++) {
645 } while (ch == -1 && (errno == EINTR || errno == EAGAIN));
655 if (ch == '\r') { /* Support for Mac/Windows file format */
657 if (ch == '\n') { /* Windows (\r\n) */
661 else { /* Mac (\r only) */
662 ungetc(ch, fd); /* Push next character back to fd */
674 * Make a "unique" filename. It is important that if
675 * called again with the same "what" that the result
676 * will be identical. This allows us to use the file
677 * without saving its name, and re-generate the name
678 * so that it can be deleted.
680 void make_unique_filename(POOLMEM **name, int Id, char *what)
682 Mmsg(name, "%s/%s.%s.%d.tmp", working_directory, my_name, what, Id);