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-2004 Kern Sibbald and John Walker
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,
40 * Guarantee that the string is properly terminated */
41 char *bstrncpy(char *dest, const char *src, int maxlen)
43 strncpy(dest, src, maxlen-1);
49 * Guarantee that the string is properly terminated */
50 char *bstrncpy(char *dest, POOL_MEM &src, int maxlen)
52 strncpy(dest, src.c_str(), maxlen-1);
58 char *bstrncat(char *dest, const char *src, int maxlen)
60 strncat(dest, src, maxlen-1);
65 char *bstrncat(char *dest, POOL_MEM &src, int maxlen)
67 strncat(dest, src.c_str(), maxlen-1);
75 void *bmalloc(size_t size)
81 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), strerror(errno));
87 void *b_malloc(const char *file, int line, size_t size)
92 buf = sm_malloc(file, line, size);
97 e_msg(file, line, M_ABORT, 0, _("Out of memory: ERR=%s\n"), strerror(errno));
103 void *brealloc (void *buf, size_t size)
105 buf = realloc(buf, size);
107 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), strerror(errno));
113 void *bcalloc (size_t size1, size_t size2)
117 buf = calloc(size1, size2);
119 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), strerror(errno));
129 int bsnprintf(char *str, int32_t size, const char *fmt, ...)
134 va_start(arg_ptr, fmt);
135 len = bvsnprintf(str, size, fmt, arg_ptr);
141 * Implement vsnprintf()
143 int bvsnprintf(char *str, int32_t size, const char *format, va_list ap)
145 #ifdef HAVE_VSNPRINTF
147 len = vsnprintf(str, size, format, ap);
155 buf = get_memory(BIG_BUF);
156 len = vsprintf(buf, format, ap);
157 if (len >= BIG_BUF) {
158 Emsg0(M_ABORT, 0, _("Buffer overflow.\n"));
160 memcpy(str, buf, size);
167 #ifndef HAVE_LOCALTIME_R
169 struct tm *localtime_r(const time_t *timep, struct tm *tm)
171 static pthread_mutex_t mutex;
172 static bool first = true;
176 pthread_mutex_init(&mutex, NULL);
182 ltm = localtime(timep);
184 memcpy(tm, ltm, sizeof(struct tm));
187 return ltm ? tm : NULL;
189 #endif /* HAVE_LOCALTIME_R */
191 #ifndef HAVE_READDIR_R
195 int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
197 static pthread_mutex_t mutex;
198 static int first = 1;
203 pthread_mutex_init(&mutex, NULL);
208 ndir = readdir(dirp);
211 memcpy(entry, ndir, sizeof(struct dirent));
212 strcpy(entry->d_name, ndir->d_name);
222 #endif /* HAVE_READDIR_R */
225 int bstrerror(int errnum, char *buf, size_t bufsiz)
227 static pthread_mutex_t mutex;
228 static int first = 1;
233 pthread_mutex_init(&mutex, NULL);
238 msg = strerror(errnum);
240 msg = _("Bad errno");
243 bstrncpy(buf, msg, bufsiz);
249 * These are mutex routines that do error checking
250 * for deadlock and such. Normally not turned on.
253 void _p(char *file, int line, pthread_mutex_t *m)
256 if ((errstat = pthread_mutex_trylock(m))) {
257 e_msg(file, line, M_ERROR, 0, _("Possible mutex deadlock.\n"));
258 /* We didn't get the lock, so do it definitely now */
259 if ((errstat=pthread_mutex_lock(m))) {
260 e_msg(file, line, M_ABORT, 0, _("Mutex lock failure. ERR=%s\n"),
263 e_msg(file, line, M_ERROR, 0, _("Possible mutex deadlock resolved.\n"));
269 void _v(char *file, int line, pthread_mutex_t *m)
273 if ((errstat=pthread_mutex_trylock(m)) == 0) {
274 e_msg(file, line, M_ERROR, 0, _("Mutex unlock not locked. ERR=%s\n"),
277 if ((errstat=pthread_mutex_unlock(m))) {
278 e_msg(file, line, M_ABORT, 0, _("Mutex unlock failure. ERR=%s\n"),
282 #endif /* DEBUG_MUTEX */
285 /* These routines are not normally turned on */
287 void b_memset(const char *file, int line, void *mem, int val, size_t num)
289 /* Testing for 2000 byte zero at beginning of Volume block */
290 if (num > 1900 && num < 3000) {
291 Pmsg3(000, "Memset for %d bytes at %s:%d\n", (int)num, file, line);
293 memset(mem, val, num);
297 #if !defined(HAVE_CYGWIN) && !defined(HAVE_WIN32)
298 static int del_pid_file_ok = FALSE;
302 * Create a standard "Unix" pid file.
304 void create_pid_file(char *dir, const char *progname, int port)
306 #if !defined(HAVE_CYGWIN) && !defined(HAVE_WIN32)
310 POOLMEM *fname = get_pool_memory(PM_FNAME);
313 Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
314 if (stat(fname, &statp) == 0) {
315 /* File exists, see what we have */
317 if ((pidfd = open(fname, O_RDONLY|O_BINARY, 0)) < 0 ||
318 read(pidfd, &pidbuf, sizeof(pidbuf)) < 0 ||
319 sscanf(pidbuf, "%d", &oldpid) != 1) {
320 Emsg2(M_ERROR_TERM, 0, _("Cannot open pid file. %s ERR=%s\n"), fname, strerror(errno));
322 /* See if other Bacula is still alive */
323 if (kill(oldpid, 0) != -1 || errno != ESRCH) {
324 Emsg3(M_ERROR_TERM, 0, _("%s is already running. pid=%d\nCheck file %s\n"),
325 progname, oldpid, fname);
327 /* He is not alive, so take over file ownership */
328 unlink(fname); /* remove stale pid file */
330 /* Create new pid file */
331 if ((pidfd = open(fname, O_CREAT|O_TRUNC|O_WRONLY|O_BINARY, 0640)) >= 0) {
332 len = sprintf(pidbuf, "%d\n", (int)getpid());
333 write(pidfd, pidbuf, len);
335 del_pid_file_ok = TRUE; /* we created it so we can delete it */
337 Emsg2(M_ERROR_TERM, 0, _("Could not open pid file. %s ERR=%s\n"), fname, strerror(errno));
339 free_pool_memory(fname);
345 * Delete the pid file if we created it
347 int delete_pid_file(char *dir, const char *progname, int port)
349 #if !defined(HAVE_CYGWIN) && !defined(HAVE_WIN32)
350 POOLMEM *fname = get_pool_memory(PM_FNAME);
352 if (!del_pid_file_ok) {
353 free_pool_memory(fname);
356 del_pid_file_ok = FALSE;
357 Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
359 free_pool_memory(fname);
367 uint64_t last_jobs_addr;
368 uint64_t reserved[20];
371 static struct s_state_hdr state_hdr = {
378 * Open and read the state file for the daemon
380 void read_state_file(char *dir, const char *progname, int port)
384 POOLMEM *fname = get_pool_memory(PM_FNAME);
385 struct s_state_hdr hdr;
386 int hdr_size = sizeof(hdr);
388 Mmsg(&fname, "%s/%s.%d.state", dir, progname, port);
389 /* If file exists, see what we have */
390 // Dmsg1(10, "O_BINARY=%d\n", O_BINARY);
391 if ((sfd = open(fname, O_RDONLY|O_BINARY, 0)) < 0) {
392 Dmsg3(010, "Could not open state file. sfd=%d size=%d: ERR=%s\n",
393 sfd, sizeof(hdr), strerror(errno));
396 if ((stat=read(sfd, &hdr, hdr_size)) != hdr_size) {
397 Dmsg4(010, "Could not read state file. sfd=%d stat=%d size=%d: ERR=%s\n",
398 sfd, (int)stat, hdr_size, strerror(errno));
401 if (hdr.version != state_hdr.version) {
402 Dmsg2(010, "Bad hdr version. Wanted %d got %d\n",
403 state_hdr.version, hdr.version);
406 if (strcmp(hdr.id, state_hdr.id) != 0) {
407 Dmsg0(000, "State file header id invalid.\n");
410 // Dmsg1(010, "Read header of %d bytes.\n", sizeof(hdr));
411 read_last_jobs_list(sfd, hdr.last_jobs_addr);
416 free_pool_memory(fname);
420 * Write the state file
422 void write_state_file(char *dir, const char *progname, int port)
425 POOLMEM *fname = get_pool_memory(PM_FNAME);
427 Mmsg(&fname, "%s/%s.%d.state", dir, progname, port);
428 /* Create new state file */
429 if ((sfd = open(fname, O_CREAT|O_WRONLY|O_BINARY, 0640)) < 0) {
430 Dmsg2(000, _("Could not create state file. %s ERR=%s\n"), fname, strerror(errno));
431 Emsg2(M_ERROR, 0, _("Could not create state file. %s ERR=%s\n"), fname, strerror(errno));
434 if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
435 Dmsg1(000, "Write hdr error: ERR=%s\n", strerror(errno));
438 // Dmsg1(010, "Wrote header of %d bytes\n", sizeof(state_hdr));
439 state_hdr.last_jobs_addr = sizeof(state_hdr);
440 state_hdr.reserved[0] = write_last_jobs_list(sfd, state_hdr.last_jobs_addr);
441 // Dmsg1(010, "write last job end = %d\n", (int)state_hdr.reserved[0]);
442 if (lseek(sfd, 0, SEEK_SET) < 0) {
443 Dmsg1(000, "lseek error: ERR=%s\n", strerror(errno));
446 if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
447 Pmsg1(000, "Write final hdr error: ERR=%s\n", strerror(errno));
449 // Dmsg1(010, "rewrote header = %d\n", sizeof(state_hdr));
454 free_pool_memory(fname);
459 * Drop to privilege new userid and new gid if non-NULL
461 void drop(char *uid, char *gid)
468 if ((group = getgrnam(gid)) == NULL) {
469 Emsg1(M_ERROR_TERM, 0, _("Could not find specified group: %s\n"), gid);
471 if (setgid(group->gr_gid)) {
472 Emsg1(M_ERROR_TERM, 0, _("Could not set specified group: %s\n"), gid);
474 gr_list[0] = group->gr_gid;
475 if (setgroups(1, gr_list)) {
476 Emsg1(M_ERROR_TERM, 0, _("Could not set specified group: %s\n"), gid);
483 struct passwd *passw;
484 if ((passw = getpwnam(uid)) == NULL) {
485 Emsg1(M_ERROR_TERM, 0, _("Could not find specified userid: %s\n"), uid);
487 if (setuid(passw->pw_uid)) {
488 Emsg1(M_ERROR_TERM, 0, _("Could not set specified userid: %s\n"), uid);
495 static pthread_mutex_t timer_mutex = PTHREAD_MUTEX_INITIALIZER;
496 static pthread_cond_t timer = PTHREAD_COND_INITIALIZER;
499 * This routine will sleep (sec, microsec). Note, however, that if a
500 * signal occurs, it will return early. It is up to the caller
501 * to recall this routine if he/she REALLY wants to sleep the
504 int bmicrosleep(time_t sec, long usec)
506 struct timespec timeout;
511 timeout.tv_sec = sec;
512 timeout.tv_nsec = usec * 1000;
514 #ifdef HAVE_NANOSLEEP
515 stat = nanosleep(&timeout, NULL);
516 if (!(stat < 0 && errno == ENOSYS)) {
519 /* If we reach here it is because nanosleep is not supported by the OS */
522 /* Do it the old way */
523 gettimeofday(&tv, &tz);
524 timeout.tv_nsec += tv.tv_usec * 1000;
525 timeout.tv_sec += tv.tv_sec;
526 while (timeout.tv_nsec >= 1000000000) {
527 timeout.tv_nsec -= 1000000000;
531 Dmsg2(200, "pthread_cond_timedwait sec=%d usec=%d\n", sec, usec);
532 /* Note, this unlocks mutex during the sleep */
534 stat = pthread_cond_timedwait(&timer, &timer_mutex, &timeout);
537 Dmsg2(200, "pthread_cond_timedwait stat=%d ERR=%s\n", stat,
544 /* BSDI does not have this. This is a *poor* simulation */
547 strtoll(const char *ptr, char **endptr, int base)
549 return (long long int)strtod(ptr, endptr);
554 * Bacula's implementation of fgets(). The difference is that it handles
555 * being interrupted by a signal (e.g. a SIGCHLD).
558 char *bfgets(char *s, int size, FILE *fd)
563 for (int i=0; i < size-1; i++) {
567 } while (ch == -1 && (errno == EINTR || errno == EAGAIN));
577 if (ch == '\r') { /* Support for Mac/Windows file format */
579 if (ch == '\n') { /* Windows (\r\n) */
583 else { /* Mac (\r only) */
584 ungetc(ch, fd); /* Push next character back to fd */
596 * Make a "unique" filename. It is important that if
597 * called again with the same "what" that the result
598 * will be identical. This allows us to use the file
599 * without saving its name, and re-generate the name
600 * so that it can be deleted.
602 void make_unique_filename(POOLMEM **name, int Id, char *what)
604 Mmsg(name, "%s/%s.%s.%d.tmp", working_directory, my_name, what, Id);