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);
124 void *bmalloc(size_t size)
130 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), strerror(errno));
136 void *b_malloc(const char *file, int line, size_t size)
141 buf = sm_malloc(file, line, size);
146 e_msg(file, line, M_ABORT, 0, _("Out of memory: ERR=%s\n"), strerror(errno));
152 void *brealloc (void *buf, size_t size)
154 buf = realloc(buf, size);
156 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), strerror(errno));
162 void *bcalloc (size_t size1, size_t size2)
166 buf = calloc(size1, size2);
168 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), strerror(errno));
178 int bsnprintf(char *str, int32_t size, const char *fmt, ...)
183 va_start(arg_ptr, fmt);
184 len = bvsnprintf(str, size, fmt, arg_ptr);
190 * Implement vsnprintf()
192 int bvsnprintf(char *str, int32_t size, const char *format, va_list ap)
194 #ifdef HAVE_VSNPRINTF
196 len = vsnprintf(str, size, format, ap);
204 buflen = size > BIG_BUF ? size : BIG_BUF;
205 buf = get_memory(buflen);
206 len = vsprintf(buf, format, ap);
208 Emsg0(M_ABORT, 0, _("Buffer overflow.\n"));
210 memcpy(str, buf, len);
211 str[len] = 0; /* len excludes the null */
217 #ifndef HAVE_LOCALTIME_R
219 struct tm *localtime_r(const time_t *timep, struct tm *tm)
221 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
225 ltm = localtime(timep);
227 memcpy(tm, ltm, sizeof(struct tm));
230 return ltm ? tm : NULL;
232 #endif /* HAVE_LOCALTIME_R */
234 #ifndef HAVE_READDIR_R
238 int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
240 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
246 ndir = readdir(dirp);
249 memcpy(entry, ndir, sizeof(struct dirent));
250 strcpy(entry->d_name, ndir->d_name);
260 #endif /* HAVE_READDIR_R */
263 int bstrerror(int errnum, char *buf, size_t bufsiz)
265 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
271 msg = strerror(errnum);
273 msg = _("Bad errno");
276 bstrncpy(buf, msg, bufsiz);
282 * These are mutex routines that do error checking
283 * for deadlock and such. Normally not turned on.
286 void _p(char *file, int line, pthread_mutex_t *m)
289 if ((errstat = pthread_mutex_trylock(m))) {
290 e_msg(file, line, M_ERROR, 0, _("Possible mutex deadlock.\n"));
291 /* We didn't get the lock, so do it definitely now */
292 if ((errstat=pthread_mutex_lock(m))) {
294 e_msg(file, line, M_ABORT, 0, _("Mutex lock failure. ERR=%s\n"),
295 be.strerror(errstat));
297 e_msg(file, line, M_ERROR, 0, _("Possible mutex deadlock resolved.\n"));
303 void _v(char *file, int line, pthread_mutex_t *m)
307 if ((errstat=pthread_mutex_trylock(m)) == 0) {
309 e_msg(file, line, M_ERROR, 0, _("Mutex unlock not locked. ERR=%s\n"),
310 be.strerror(errstat));
312 if ((errstat=pthread_mutex_unlock(m))) {
314 e_msg(file, line, M_ABORT, 0, _("Mutex unlock failure. ERR=%s\n"),
315 be.strerror(errstat));
321 void _p(pthread_mutex_t *m)
324 if ((errstat=pthread_mutex_lock(m))) {
326 e_msg(__FILE__, __LINE__, M_ABORT, 0, _("Mutex lock failure. ERR=%s\n"),
327 be.strerror(errstat));
331 void _v(pthread_mutex_t *m)
334 if ((errstat=pthread_mutex_unlock(m))) {
336 e_msg(__FILE__, __LINE__, M_ABORT, 0, _("Mutex unlock failure. ERR=%s\n"),
337 be.strerror(errstat));
341 #endif /* DEBUG_MUTEX */
344 /* These routines are not normally turned on */
346 void b_memset(const char *file, int line, void *mem, int val, size_t num)
348 /* Testing for 2000 byte zero at beginning of Volume block */
349 if (num > 1900 && num < 3000) {
350 Pmsg3(000, "Memset for %d bytes at %s:%d\n", (int)num, file, line);
352 memset(mem, val, num);
356 #if !defined(HAVE_CYGWIN) && !defined(HAVE_WIN32)
357 static int del_pid_file_ok = FALSE;
361 * Create a standard "Unix" pid file.
363 void create_pid_file(char *dir, const char *progname, int port)
365 #if !defined(HAVE_CYGWIN) && !defined(HAVE_WIN32)
369 POOLMEM *fname = get_pool_memory(PM_FNAME);
372 Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
373 if (stat(fname, &statp) == 0) {
374 /* File exists, see what we have */
376 if ((pidfd = open(fname, O_RDONLY|O_BINARY, 0)) < 0 ||
377 read(pidfd, &pidbuf, sizeof(pidbuf)) < 0 ||
378 sscanf(pidbuf, "%d", &oldpid) != 1) {
379 Emsg2(M_ERROR_TERM, 0, _("Cannot open pid file. %s ERR=%s\n"), fname, strerror(errno));
381 /* See if other Bacula is still alive */
382 if (kill(oldpid, 0) != -1 || errno != ESRCH) {
383 Emsg3(M_ERROR_TERM, 0, _("%s is already running. pid=%d\nCheck file %s\n"),
384 progname, oldpid, fname);
386 /* He is not alive, so take over file ownership */
387 unlink(fname); /* remove stale pid file */
389 /* Create new pid file */
390 if ((pidfd = open(fname, O_CREAT|O_TRUNC|O_WRONLY|O_BINARY, 0640)) >= 0) {
391 len = sprintf(pidbuf, "%d\n", (int)getpid());
392 write(pidfd, pidbuf, len);
394 del_pid_file_ok = TRUE; /* we created it so we can delete it */
396 Emsg2(M_ERROR_TERM, 0, _("Could not open pid file. %s ERR=%s\n"), fname, strerror(errno));
398 free_pool_memory(fname);
404 * Delete the pid file if we created it
406 int delete_pid_file(char *dir, const char *progname, int port)
408 #if !defined(HAVE_CYGWIN) && !defined(HAVE_WIN32)
409 POOLMEM *fname = get_pool_memory(PM_FNAME);
411 if (!del_pid_file_ok) {
412 free_pool_memory(fname);
415 del_pid_file_ok = FALSE;
416 Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
418 free_pool_memory(fname);
426 uint64_t last_jobs_addr;
427 uint64_t reserved[20];
430 static struct s_state_hdr state_hdr = {
437 * Open and read the state file for the daemon
439 void read_state_file(char *dir, const char *progname, int port)
443 POOLMEM *fname = get_pool_memory(PM_FNAME);
444 struct s_state_hdr hdr;
445 int hdr_size = sizeof(hdr);
447 Mmsg(&fname, "%s/%s.%d.state", dir, progname, port);
448 /* If file exists, see what we have */
449 // Dmsg1(10, "O_BINARY=%d\n", O_BINARY);
450 if ((sfd = open(fname, O_RDONLY|O_BINARY, 0)) < 0) {
451 Dmsg3(010, "Could not open state file. sfd=%d size=%d: ERR=%s\n",
452 sfd, sizeof(hdr), strerror(errno));
455 if ((stat=read(sfd, &hdr, hdr_size)) != hdr_size) {
456 Dmsg4(010, "Could not read state file. sfd=%d stat=%d size=%d: ERR=%s\n",
457 sfd, (int)stat, hdr_size, strerror(errno));
460 if (hdr.version != state_hdr.version) {
461 Dmsg2(010, "Bad hdr version. Wanted %d got %d\n",
462 state_hdr.version, hdr.version);
465 if (strcmp(hdr.id, state_hdr.id) != 0) {
466 Dmsg0(000, "State file header id invalid.\n");
469 // Dmsg1(010, "Read header of %d bytes.\n", sizeof(hdr));
470 read_last_jobs_list(sfd, hdr.last_jobs_addr);
475 free_pool_memory(fname);
479 * Write the state file
481 void write_state_file(char *dir, const char *progname, int port)
484 POOLMEM *fname = get_pool_memory(PM_FNAME);
486 Mmsg(&fname, "%s/%s.%d.state", dir, progname, port);
487 /* Create new state file */
488 if ((sfd = open(fname, O_CREAT|O_WRONLY|O_BINARY, 0640)) < 0) {
489 Dmsg2(000, _("Could not create state file. %s ERR=%s\n"), fname, strerror(errno));
490 Emsg2(M_ERROR, 0, _("Could not create state file. %s ERR=%s\n"), fname, strerror(errno));
493 if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
494 Dmsg1(000, "Write hdr error: ERR=%s\n", strerror(errno));
497 // Dmsg1(010, "Wrote header of %d bytes\n", sizeof(state_hdr));
498 state_hdr.last_jobs_addr = sizeof(state_hdr);
499 state_hdr.reserved[0] = write_last_jobs_list(sfd, state_hdr.last_jobs_addr);
500 // Dmsg1(010, "write last job end = %d\n", (int)state_hdr.reserved[0]);
501 if (lseek(sfd, 0, SEEK_SET) < 0) {
502 Dmsg1(000, "lseek error: ERR=%s\n", strerror(errno));
505 if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
506 Pmsg1(000, "Write final hdr error: ERR=%s\n", strerror(errno));
508 // Dmsg1(010, "rewrote header = %d\n", sizeof(state_hdr));
513 free_pool_memory(fname);
518 * Drop to privilege new userid and new gid if non-NULL
520 void drop(char *uid, char *gid)
527 if ((group = getgrnam(gid)) == NULL) {
528 Emsg1(M_ERROR_TERM, 0, _("Could not find specified group: %s\n"), gid);
530 if (setgid(group->gr_gid)) {
531 Emsg1(M_ERROR_TERM, 0, _("Could not set specified group: %s\n"), gid);
533 gr_list[0] = group->gr_gid;
534 if (setgroups(1, gr_list)) {
535 Emsg1(M_ERROR_TERM, 0, _("Could not set specified group: %s\n"), gid);
542 struct passwd *passw;
543 if ((passw = getpwnam(uid)) == NULL) {
544 Emsg1(M_ERROR_TERM, 0, _("Could not find specified userid: %s\n"), uid);
546 if (setuid(passw->pw_uid)) {
547 Emsg1(M_ERROR_TERM, 0, _("Could not set specified userid: %s\n"), uid);
555 /* BSDI does not have this. This is a *poor* simulation */
558 strtoll(const char *ptr, char **endptr, int base)
560 return (long long int)strtod(ptr, endptr);
565 * Bacula's implementation of fgets(). The difference is that it handles
566 * being interrupted by a signal (e.g. a SIGCHLD).
569 char *bfgets(char *s, int size, FILE *fd)
574 for (int i=0; i < size-1; i++) {
578 } while (ch == -1 && (errno == EINTR || errno == EAGAIN));
588 if (ch == '\r') { /* Support for Mac/Windows file format */
590 if (ch == '\n') { /* Windows (\r\n) */
594 else { /* Mac (\r only) */
595 ungetc(ch, fd); /* Push next character back to fd */
607 * Make a "unique" filename. It is important that if
608 * called again with the same "what" that the result
609 * will be identical. This allows us to use the file
610 * without saving its name, and re-generate the name
611 * so that it can be deleted.
613 void make_unique_filename(POOLMEM **name, int Id, char *what)
615 Mmsg(name, "%s/%s.%s.%d.tmp", working_directory, my_name, what, Id);