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);
48 char *bstrncat(char *dest, const char *src, int maxlen)
50 strncat(dest, src, maxlen-1);
57 void *bmalloc(size_t size)
63 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), strerror(errno));
69 void *b_malloc(const char *file, int line, size_t size)
74 buf = sm_malloc(file, line, size);
79 e_msg(file, line, M_ABORT, 0, _("Out of memory: ERR=%s\n"), strerror(errno));
85 void *brealloc (void *buf, size_t size)
87 buf = realloc(buf, size);
89 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), strerror(errno));
95 void *bcalloc (size_t size1, size_t size2)
99 buf = calloc(size1, size2);
101 Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), strerror(errno));
111 int bsnprintf(char *str, int32_t size, const char *fmt, ...)
116 va_start(arg_ptr, fmt);
117 len = bvsnprintf(str, size, fmt, arg_ptr);
123 * Implement vsnprintf()
125 int bvsnprintf(char *str, int32_t size, const char *format, va_list ap)
127 #ifdef HAVE_VSNPRINTF
129 len = vsnprintf(str, size, format, ap);
137 buf = get_memory(BIG_BUF);
138 len = vsprintf(buf, format, ap);
139 if (len >= BIG_BUF) {
140 Emsg0(M_ABORT, 0, _("Buffer overflow.\n"));
142 memcpy(str, buf, size);
149 #ifndef HAVE_LOCALTIME_R
151 struct tm *localtime_r(const time_t *timep, struct tm *tm)
153 static pthread_mutex_t mutex;
154 static int first = 1;
158 pthread_mutex_init(&mutex, NULL);
162 ltm = localtime(timep);
164 memcpy(tm, ltm, sizeof(struct tm));
167 return ltm ? tm : NULL;
169 #endif /* HAVE_LOCALTIME_R */
171 #ifndef HAVE_READDIR_R
175 int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
177 static pthread_mutex_t mutex;
178 static int first = 1;
183 pthread_mutex_init(&mutex, NULL);
188 ndir = readdir(dirp);
191 memcpy(entry, ndir, sizeof(struct dirent));
192 strcpy(entry->d_name, ndir->d_name);
202 #endif /* HAVE_READDIR_R */
205 int bstrerror(int errnum, char *buf, size_t bufsiz)
207 static pthread_mutex_t mutex;
208 static int first = 1;
213 pthread_mutex_init(&mutex, NULL);
218 msg = strerror(errnum);
220 msg = _("Bad errno");
223 bstrncpy(buf, msg, bufsiz);
229 * These are mutex routines that do error checking
230 * for deadlock and such. Normally not turned on.
233 void _p(char *file, int line, pthread_mutex_t *m)
236 if ((errstat = pthread_mutex_trylock(m))) {
237 e_msg(file, line, M_ERROR, 0, _("Possible mutex deadlock.\n"));
238 /* We didn't get the lock, so do it definitely now */
239 if ((errstat=pthread_mutex_lock(m))) {
240 e_msg(file, line, M_ABORT, 0, _("Mutex lock failure. ERR=%s\n"),
243 e_msg(file, line, M_ERROR, 0, _("Possible mutex deadlock resolved.\n"));
249 void _v(char *file, int line, pthread_mutex_t *m)
253 if ((errstat=pthread_mutex_trylock(m)) == 0) {
254 e_msg(file, line, M_ERROR, 0, _("Mutex unlock not locked. ERR=%s\n"),
257 if ((errstat=pthread_mutex_unlock(m))) {
258 e_msg(file, line, M_ABORT, 0, _("Mutex unlock failure. ERR=%s\n"),
262 #endif /* DEBUG_MUTEX */
265 /* These routines are not normally turned on */
267 void b_memset(const char *file, int line, void *mem, int val, size_t num)
269 /* Testing for 2000 byte zero at beginning of Volume block */
270 if (num > 1900 && num < 3000) {
271 Pmsg3(000, "Memset for %d bytes at %s:%d\n", (int)num, file, line);
273 memset(mem, val, num);
277 #if !defined(HAVE_CYGWIN) && !defined(HAVE_WIN32)
278 static int del_pid_file_ok = FALSE;
282 * Create a standard "Unix" pid file.
284 void create_pid_file(char *dir, const char *progname, int port)
286 #if !defined(HAVE_CYGWIN) && !defined(HAVE_WIN32)
290 POOLMEM *fname = get_pool_memory(PM_FNAME);
293 Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
294 if (stat(mp_chr(fname), &statp) == 0) {
295 /* File exists, see what we have */
297 if ((pidfd = open(mp_chr(fname), O_RDONLY|O_BINARY, 0)) < 0 ||
298 read(pidfd, &pidbuf, sizeof(pidbuf)) < 0 ||
299 sscanf(pidbuf, "%d", &oldpid) != 1) {
300 Emsg2(M_ERROR_TERM, 0, _("Cannot open pid file. %s ERR=%s\n"), fname, strerror(errno));
302 /* See if other Bacula is still alive */
303 if (kill(oldpid, 0) != -1 || errno != ESRCH) {
304 Emsg3(M_ERROR_TERM, 0, _("%s is already running. pid=%d\nCheck file %s\n"),
305 progname, oldpid, fname);
307 /* He is not alive, so take over file ownership */
308 unlink(mp_chr(fname)); /* remove stale pid file */
310 /* Create new pid file */
311 if ((pidfd = open(mp_chr(fname), O_CREAT|O_TRUNC|O_WRONLY|O_BINARY, 0640)) >= 0) {
312 len = sprintf(pidbuf, "%d\n", (int)getpid());
313 write(pidfd, pidbuf, len);
315 del_pid_file_ok = TRUE; /* we created it so we can delete it */
317 Emsg2(M_ERROR_TERM, 0, _("Could not open pid file. %s ERR=%s\n"), fname, strerror(errno));
319 free_pool_memory(fname);
325 * Delete the pid file if we created it
327 int delete_pid_file(char *dir, const char *progname, int port)
329 #if !defined(HAVE_CYGWIN) && !defined(HAVE_WIN32)
330 POOLMEM *fname = get_pool_memory(PM_FNAME);
332 if (!del_pid_file_ok) {
333 free_pool_memory(fname);
336 del_pid_file_ok = FALSE;
337 Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
338 unlink(mp_chr(fname));
339 free_pool_memory(fname);
347 uint64_t last_jobs_addr;
348 uint64_t reserved[20];
351 static struct s_state_hdr state_hdr = {
358 * Open and read the state file for the daemon
360 void read_state_file(char *dir, const char *progname, int port)
364 POOLMEM *fname = get_pool_memory(PM_FNAME);
365 struct s_state_hdr hdr;
366 int hdr_size = sizeof(hdr);
368 Mmsg(&fname, "%s/%s.%d.state", dir, progname, port);
369 /* If file exists, see what we have */
370 // Dmsg1(10, "O_BINARY=%d\n", O_BINARY);
371 if ((sfd = open(mp_chr(fname), O_RDONLY|O_BINARY, 0)) < 0) {
372 Dmsg3(010, "Could not open state file. sfd=%d size=%d: ERR=%s\n",
373 sfd, sizeof(hdr), strerror(errno));
376 if ((stat=read(sfd, &hdr, hdr_size)) != hdr_size) {
377 Dmsg4(010, "Could not read state file. sfd=%d stat=%d size=%d: ERR=%s\n",
378 sfd, (int)stat, hdr_size, strerror(errno));
381 if (hdr.version != state_hdr.version) {
382 Dmsg2(010, "Bad hdr version. Wanted %d got %d\n",
383 state_hdr.version, hdr.version);
386 if (strcmp(hdr.id, state_hdr.id) != 0) {
387 Dmsg0(000, "State file header id invalid.\n");
390 // Dmsg1(010, "Read header of %d bytes.\n", sizeof(hdr));
391 read_last_jobs_list(sfd, hdr.last_jobs_addr);
396 free_pool_memory(fname);
400 * Write the state file
402 void write_state_file(char *dir, const char *progname, int port)
405 POOLMEM *fname = get_pool_memory(PM_FNAME);
407 Mmsg(&fname, "%s/%s.%d.state", dir, progname, port);
408 /* Create new state file */
409 if ((sfd = open(mp_chr(fname), O_CREAT|O_WRONLY|O_BINARY, 0640)) < 0) {
410 Dmsg2(000, _("Could not create state file. %s ERR=%s\n"), fname, strerror(errno));
411 Emsg2(M_ERROR, 0, _("Could not create state file. %s ERR=%s\n"), fname, strerror(errno));
414 if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
415 Dmsg1(000, "Write hdr error: ERR=%s\n", strerror(errno));
418 // Dmsg1(010, "Wrote header of %d bytes\n", sizeof(state_hdr));
419 state_hdr.last_jobs_addr = sizeof(state_hdr);
420 state_hdr.reserved[0] = write_last_jobs_list(sfd, state_hdr.last_jobs_addr);
421 // Dmsg1(010, "write last job end = %d\n", (int)state_hdr.reserved[0]);
422 if (lseek(sfd, 0, SEEK_SET) < 0) {
423 Dmsg1(000, "lseek error: ERR=%s\n", strerror(errno));
426 if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
427 Pmsg1(000, "Write final hdr error: ERR=%s\n", strerror(errno));
429 // Dmsg1(010, "rewrote header = %d\n", sizeof(state_hdr));
434 free_pool_memory(fname);
439 * Drop to privilege new userid and new gid if non-NULL
441 void drop(char *uid, char *gid)
448 if ((group = getgrnam(gid)) == NULL) {
449 Emsg1(M_ERROR_TERM, 0, _("Could not find specified group: %s\n"), gid);
451 if (setgid(group->gr_gid)) {
452 Emsg1(M_ERROR_TERM, 0, _("Could not set specified group: %s\n"), gid);
454 gr_list[0] = group->gr_gid;
455 if (setgroups(1, gr_list)) {
456 Emsg1(M_ERROR_TERM, 0, _("Could not set specified group: %s\n"), gid);
463 struct passwd *passw;
464 if ((passw = getpwnam(uid)) == NULL) {
465 Emsg1(M_ERROR_TERM, 0, _("Could not find specified userid: %s\n"), uid);
467 if (setuid(passw->pw_uid)) {
468 Emsg1(M_ERROR_TERM, 0, _("Could not set specified userid: %s\n"), uid);
475 static pthread_mutex_t timer_mutex = PTHREAD_MUTEX_INITIALIZER;
476 static pthread_cond_t timer = PTHREAD_COND_INITIALIZER;
479 * This routine will sleep (sec, microsec). Note, however, that if a
480 * signal occurs, it will return early. It is up to the caller
481 * to recall this routine if he/she REALLY wants to sleep the
484 int bmicrosleep(time_t sec, long usec)
486 struct timespec timeout;
491 timeout.tv_sec = sec;
492 timeout.tv_nsec = usec * 1000;
494 #ifdef HAVE_NANOSLEEP
495 stat = nanosleep(&timeout, NULL);
496 if (!(stat < 0 && errno == ENOSYS)) {
499 /* If we reach here it is because nanosleep is not supported by the OS */
502 /* Do it the old way */
503 gettimeofday(&tv, &tz);
504 timeout.tv_nsec += tv.tv_usec * 1000;
505 timeout.tv_sec += tv.tv_sec;
506 while (timeout.tv_nsec >= 1000000000) {
507 timeout.tv_nsec -= 1000000000;
511 Dmsg2(200, "pthread_cond_timedwait sec=%d usec=%d\n", sec, usec);
512 /* Note, this unlocks mutex during the sleep */
514 stat = pthread_cond_timedwait(&timer, &timer_mutex, &timeout);
516 Dmsg2(200, "pthread_cond_timedwait stat=%d ERR=%s\n", stat,
523 /* BSDI does not have this. This is a *poor* simulation */
526 strtoll(const char *ptr, char **endptr, int base)
528 return (long long int)strtod(ptr, endptr);
533 * Bacula's implementation of fgets(). The difference is that it handles
534 * being interrupted by a signal (e.g. a SIGCHLD).
537 char *bfgets(char *s, int size, FILE *fd)
542 for (int i=0; i < size-1; i++) {
546 } while (ch == -1 && (errno == EINTR || errno == EAGAIN));
556 if (ch == '\r') { /* Support for Mac/Windows file format */
558 if (ch == '\n') { /* Windows (\r\n) */
562 else { /* Mac (\r only) */
563 ungetc(ch, fd); /* Push next character back to fd */
575 * Make a "unique" filename. It is important that if
576 * called again with the same "what" that the result
577 * will be identical. This allows us to use the file
578 * without saving its name, and re-generate the name
579 * so that it can be deleted.
581 void make_unique_filename(POOLMEM **name, int Id, char *what)
583 Mmsg(name, "%s/%s.%s.%d.tmp", working_directory, my_name, what, Id);