]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/bsys.c
Change copyright
[bacula/bacula] / bacula / src / lib / bsys.c
1 /*
2  * Miscellaneous Bacula memory and thread safe routines
3  *   Generally, these are interfaces to system or standard
4  *   library routines.
5  *
6  *  Bacula utility functions are in util.c
7  *
8  *   Version $Id$
9  */
10 /*
11    Copyright (C) 2000-2004 Kern Sibbald
12
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.
17
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.
22
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,
26    MA 02111-1307, USA.
27
28  */
29
30
31 #include "bacula.h"
32 #ifdef HAVE_PWD_H
33 #include <pwd.h>
34 #endif
35 #ifdef HAVE_GRP_H
36 #include <grp.h>
37 #endif
38
39 static pthread_mutex_t timer_mutex = PTHREAD_MUTEX_INITIALIZER;
40 static pthread_cond_t timer = PTHREAD_COND_INITIALIZER;
41
42 /*
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
46  *   requested time.
47  */
48 int bmicrosleep(time_t sec, long usec)
49 {
50    struct timespec timeout;
51    struct timeval tv;
52    struct timezone tz;
53    int stat;
54
55    timeout.tv_sec = sec;
56    timeout.tv_nsec = usec * 1000;
57
58 #ifdef HAVE_NANOSLEEP
59    stat = nanosleep(&timeout, NULL);
60    if (!(stat < 0 && errno == ENOSYS)) {
61       return stat;
62    }
63    /* If we reach here it is because nanosleep is not supported by the OS */
64 #endif
65
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;
72       timeout.tv_sec++;
73    }
74
75    Dmsg2(200, "pthread_cond_timedwait sec=%d usec=%d\n", sec, usec);
76    /* Note, this unlocks mutex during the sleep */
77    P(timer_mutex);
78    stat = pthread_cond_timedwait(&timer, &timer_mutex, &timeout);
79    if (stat != 0) {
80       berrno be;
81       Dmsg2(200, "pthread_cond_timedwait stat=%d ERR=%s\n", stat,
82          be.strerror(stat));
83    }
84    V(timer_mutex);
85    return stat;
86 }
87
88 /*
89  * Guarantee that the string is properly terminated */
90 char *bstrncpy(char *dest, const char *src, int maxlen)
91 {
92    strncpy(dest, src, maxlen-1);
93    dest[maxlen-1] = 0;
94    return dest;
95 }
96
97 /*
98  * Guarantee that the string is properly terminated */
99 char *bstrncpy(char *dest, POOL_MEM &src, int maxlen)
100 {
101    strncpy(dest, src.c_str(), maxlen-1);
102    dest[maxlen-1] = 0;
103    return dest;
104 }
105
106
107 char *bstrncat(char *dest, const char *src, int maxlen)
108 {
109    strncat(dest, src, maxlen-1);
110    dest[maxlen-1] = 0;
111    return dest;
112 }
113
114 char *bstrncat(char *dest, POOL_MEM &src, int maxlen)
115 {
116    strncat(dest, src.c_str(), maxlen-1);
117    dest[maxlen-1] = 0;
118    return dest;
119 }
120
121
122
123 #ifndef DEBUG
124 void *bmalloc(size_t size)
125 {
126   void *buf;
127
128   buf = malloc(size);
129   if (buf == NULL) {
130      Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), strerror(errno));
131   }
132   return buf;
133 }
134 #endif
135
136 void *b_malloc(const char *file, int line, size_t size)
137 {
138   void *buf;
139
140 #ifdef SMARTALLOC
141   buf = sm_malloc(file, line, size);
142 #else
143   buf = malloc(size);
144 #endif
145   if (buf == NULL) {
146      e_msg(file, line, M_ABORT, 0, _("Out of memory: ERR=%s\n"), strerror(errno));
147   }
148   return buf;
149 }
150
151
152 void *brealloc (void *buf, size_t size)
153 {
154    buf = realloc(buf, size);
155    if (buf == NULL) {
156       Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), strerror(errno));
157    }
158    return buf;
159 }
160
161
162 void *bcalloc (size_t size1, size_t size2)
163 {
164   void *buf;
165
166    buf = calloc(size1, size2);
167    if (buf == NULL) {
168       Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), strerror(errno));
169    }
170    return buf;
171 }
172
173
174 #define BIG_BUF 5000
175 /*
176  * Implement snprintf
177  */
178 int bsnprintf(char *str, int32_t size, const char *fmt,  ...)
179 {
180    va_list   arg_ptr;
181    int len;
182
183    va_start(arg_ptr, fmt);
184    len = bvsnprintf(str, size, fmt, arg_ptr);
185    va_end(arg_ptr);
186    return len;
187 }
188
189 /*
190  * Implement vsnprintf()
191  */
192 int bvsnprintf(char *str, int32_t size, const char  *format, va_list ap)
193 {
194 #ifdef HAVE_VSNPRINTF
195    int len;
196    len = vsnprintf(str, size, format, ap);
197    str[size-1] = 0;
198    return len;
199
200 #else
201
202    int len, buflen;
203    char *buf;
204    buflen = size > BIG_BUF ? size : BIG_BUF;
205    buf = get_memory(buflen);
206    len = vsprintf(buf, format, ap);
207    if (len >= buflen) {
208       Emsg0(M_ABORT, 0, _("Buffer overflow.\n"));
209    }
210    memcpy(str, buf, len);
211    str[len] = 0;                /* len excludes the null */
212    free_memory(buf);
213    return len;
214 #endif
215 }
216
217 #ifndef HAVE_LOCALTIME_R
218
219 struct tm *localtime_r(const time_t *timep, struct tm *tm)
220 {
221     static pthread_mutex_t mutex;
222     static bool first = true;
223     struct tm *ltm,
224
225     if (first) {
226        pthread_mutex_init(&mutex, NULL);
227        first = false;
228     }
229
230     P(mutex);
231
232     ltm = localtime(timep);
233     if (ltm) {
234        memcpy(tm, ltm, sizeof(struct tm));
235     }
236     V(mutex);
237     return ltm ? tm : NULL;
238 }
239 #endif /* HAVE_LOCALTIME_R */
240
241 #ifndef HAVE_READDIR_R
242 #ifndef HAVE_WIN32
243 #include <dirent.h>
244
245 int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
246 {
247     static pthread_mutex_t mutex;
248     static int first = 1;
249     struct dirent *ndir;
250     int stat;
251
252     if (first) {
253        pthread_mutex_init(&mutex, NULL);
254        first = 0;
255     }
256     P(mutex);
257     errno = 0;
258     ndir = readdir(dirp);
259     stat = errno;
260     if (ndir) {
261        memcpy(entry, ndir, sizeof(struct dirent));
262        strcpy(entry->d_name, ndir->d_name);
263        *result = entry;
264     } else {
265        *result = NULL;
266     }
267     V(mutex);
268     return stat;
269
270 }
271 #endif
272 #endif /* HAVE_READDIR_R */
273
274
275 int bstrerror(int errnum, char *buf, size_t bufsiz)
276 {
277     static pthread_mutex_t mutex;
278     static int first = 1;
279     int stat = 0;
280     const char *msg;
281
282     if (first) {
283        pthread_mutex_init(&mutex, NULL);
284        first = 0;
285     }
286     P(mutex);
287
288     msg = strerror(errnum);
289     if (!msg) {
290        msg = _("Bad errno");
291        stat = -1;
292     }
293     bstrncpy(buf, msg, bufsiz);
294     V(mutex);
295     return stat;
296 }
297
298 /*
299  * These are mutex routines that do error checking
300  *  for deadlock and such.  Normally not turned on.
301  */
302 #ifdef DEBUG_MUTEX
303 void _p(char *file, int line, pthread_mutex_t *m)
304 {
305    int errstat;
306    if ((errstat = pthread_mutex_trylock(m))) {
307       e_msg(file, line, M_ERROR, 0, _("Possible mutex deadlock.\n"));
308       /* We didn't get the lock, so do it definitely now */
309       if ((errstat=pthread_mutex_lock(m))) {
310          e_msg(file, line, M_ABORT, 0, _("Mutex lock failure. ERR=%s\n"),
311                strerror(errstat));
312       } else {
313          e_msg(file, line, M_ERROR, 0, _("Possible mutex deadlock resolved.\n"));
314       }
315
316    }
317 }
318
319 void _v(char *file, int line, pthread_mutex_t *m)
320 {
321    int errstat;
322
323    if ((errstat=pthread_mutex_trylock(m)) == 0) {
324       e_msg(file, line, M_ERROR, 0, _("Mutex unlock not locked. ERR=%s\n"),
325            strerror(errstat));
326     }
327     if ((errstat=pthread_mutex_unlock(m))) {
328        e_msg(file, line, M_ABORT, 0, _("Mutex unlock failure. ERR=%s\n"),
329               strerror(errstat));
330     }
331 }
332 #endif /* DEBUG_MUTEX */
333
334 #ifdef DEBUG_MEMSET
335 /* These routines are not normally turned on */
336 #undef memset
337 void b_memset(const char *file, int line, void *mem, int val, size_t num)
338 {
339    /* Testing for 2000 byte zero at beginning of Volume block */
340    if (num > 1900 && num < 3000) {
341       Pmsg3(000, "Memset for %d bytes at %s:%d\n", (int)num, file, line);
342    }
343    memset(mem, val, num);
344 }
345 #endif
346
347 #if !defined(HAVE_CYGWIN) && !defined(HAVE_WIN32)
348 static int del_pid_file_ok = FALSE;
349 #endif
350
351 /*
352  * Create a standard "Unix" pid file.
353  */
354 void create_pid_file(char *dir, const char *progname, int port)
355 {
356 #if !defined(HAVE_CYGWIN) && !defined(HAVE_WIN32)
357    int pidfd, len;
358    int oldpid;
359    char  pidbuf[20];
360    POOLMEM *fname = get_pool_memory(PM_FNAME);
361    struct stat statp;
362
363    Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
364    if (stat(fname, &statp) == 0) {
365       /* File exists, see what we have */
366       *pidbuf = 0;
367       if ((pidfd = open(fname, O_RDONLY|O_BINARY, 0)) < 0 ||
368            read(pidfd, &pidbuf, sizeof(pidbuf)) < 0 ||
369            sscanf(pidbuf, "%d", &oldpid) != 1) {
370          Emsg2(M_ERROR_TERM, 0, _("Cannot open pid file. %s ERR=%s\n"), fname, strerror(errno));
371       }
372       /* See if other Bacula is still alive */
373       if (kill(oldpid, 0) != -1 || errno != ESRCH) {
374          Emsg3(M_ERROR_TERM, 0, _("%s is already running. pid=%d\nCheck file %s\n"),
375                progname, oldpid, fname);
376       }
377       /* He is not alive, so take over file ownership */
378       unlink(fname);                  /* remove stale pid file */
379    }
380    /* Create new pid file */
381    if ((pidfd = open(fname, O_CREAT|O_TRUNC|O_WRONLY|O_BINARY, 0640)) >= 0) {
382       len = sprintf(pidbuf, "%d\n", (int)getpid());
383       write(pidfd, pidbuf, len);
384       close(pidfd);
385       del_pid_file_ok = TRUE;         /* we created it so we can delete it */
386    } else {
387       Emsg2(M_ERROR_TERM, 0, _("Could not open pid file. %s ERR=%s\n"), fname, strerror(errno));
388    }
389    free_pool_memory(fname);
390 #endif
391 }
392
393
394 /*
395  * Delete the pid file if we created it
396  */
397 int delete_pid_file(char *dir, const char *progname, int port)
398 {
399 #if !defined(HAVE_CYGWIN)  && !defined(HAVE_WIN32)
400    POOLMEM *fname = get_pool_memory(PM_FNAME);
401
402    if (!del_pid_file_ok) {
403       free_pool_memory(fname);
404       return 0;
405    }
406    del_pid_file_ok = FALSE;
407    Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
408    unlink(fname);
409    free_pool_memory(fname);
410 #endif
411    return 1;
412 }
413
414 struct s_state_hdr {
415    char id[14];
416    int32_t version;
417    uint64_t last_jobs_addr;
418    uint64_t reserved[20];
419 };
420
421 static struct s_state_hdr state_hdr = {
422    "Bacula State\n",
423    3,
424    0
425 };
426
427 /*
428  * Open and read the state file for the daemon
429  */
430 void read_state_file(char *dir, const char *progname, int port)
431 {
432    int sfd;
433    ssize_t stat;
434    POOLMEM *fname = get_pool_memory(PM_FNAME);
435    struct s_state_hdr hdr;
436    int hdr_size = sizeof(hdr);
437
438    Mmsg(&fname, "%s/%s.%d.state", dir, progname, port);
439    /* If file exists, see what we have */
440 // Dmsg1(10, "O_BINARY=%d\n", O_BINARY);
441    if ((sfd = open(fname, O_RDONLY|O_BINARY, 0)) < 0) {
442       Dmsg3(010, "Could not open state file. sfd=%d size=%d: ERR=%s\n",
443                     sfd, sizeof(hdr), strerror(errno));
444            goto bail_out;
445    }
446    if ((stat=read(sfd, &hdr, hdr_size)) != hdr_size) {
447       Dmsg4(010, "Could not read state file. sfd=%d stat=%d size=%d: ERR=%s\n",
448                     sfd, (int)stat, hdr_size, strerror(errno));
449       goto bail_out;
450    }
451    if (hdr.version != state_hdr.version) {
452       Dmsg2(010, "Bad hdr version. Wanted %d got %d\n",
453          state_hdr.version, hdr.version);
454    }
455    hdr.id[13] = 0;
456    if (strcmp(hdr.id, state_hdr.id) != 0) {
457       Dmsg0(000, "State file header id invalid.\n");
458       goto bail_out;
459    }
460 // Dmsg1(010, "Read header of %d bytes.\n", sizeof(hdr));
461    read_last_jobs_list(sfd, hdr.last_jobs_addr);
462 bail_out:
463    if (sfd >= 0) {
464       close(sfd);
465    }
466    free_pool_memory(fname);
467 }
468
469 /*
470  * Write the state file
471  */
472 void write_state_file(char *dir, const char *progname, int port)
473 {
474    int sfd;
475    POOLMEM *fname = get_pool_memory(PM_FNAME);
476
477    Mmsg(&fname, "%s/%s.%d.state", dir, progname, port);
478    /* Create new state file */
479    if ((sfd = open(fname, O_CREAT|O_WRONLY|O_BINARY, 0640)) < 0) {
480       Dmsg2(000, _("Could not create state file. %s ERR=%s\n"), fname, strerror(errno));
481       Emsg2(M_ERROR, 0, _("Could not create state file. %s ERR=%s\n"), fname, strerror(errno));
482       goto bail_out;
483    }
484    if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
485       Dmsg1(000, "Write hdr error: ERR=%s\n", strerror(errno));
486       goto bail_out;
487    }
488 // Dmsg1(010, "Wrote header of %d bytes\n", sizeof(state_hdr));
489    state_hdr.last_jobs_addr = sizeof(state_hdr);
490    state_hdr.reserved[0] = write_last_jobs_list(sfd, state_hdr.last_jobs_addr);
491 // Dmsg1(010, "write last job end = %d\n", (int)state_hdr.reserved[0]);
492    if (lseek(sfd, 0, SEEK_SET) < 0) {
493       Dmsg1(000, "lseek error: ERR=%s\n", strerror(errno));
494       goto bail_out;
495    }
496    if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
497       Pmsg1(000, "Write final hdr error: ERR=%s\n", strerror(errno));
498    }
499 // Dmsg1(010, "rewrote header = %d\n", sizeof(state_hdr));
500 bail_out:
501    if (sfd >= 0) {
502       close(sfd);
503    }
504    free_pool_memory(fname);
505 }
506
507
508 /*
509  * Drop to privilege new userid and new gid if non-NULL
510  */
511 void drop(char *uid, char *gid)
512 {
513 #ifdef HAVE_GRP_H
514    if (gid) {
515       struct group *group;
516       gid_t gr_list[1];
517
518       if ((group = getgrnam(gid)) == NULL) {
519          Emsg1(M_ERROR_TERM, 0, _("Could not find specified group: %s\n"), gid);
520       }
521       if (setgid(group->gr_gid)) {
522          Emsg1(M_ERROR_TERM, 0, _("Could not set specified group: %s\n"), gid);
523       }
524       gr_list[0] = group->gr_gid;
525       if (setgroups(1, gr_list)) {
526          Emsg1(M_ERROR_TERM, 0, _("Could not set specified group: %s\n"), gid);
527       }
528    }
529 #endif
530
531 #ifdef HAVE_PWD_H
532    if (uid) {
533       struct passwd *passw;
534       if ((passw = getpwnam(uid)) == NULL) {
535          Emsg1(M_ERROR_TERM, 0, _("Could not find specified userid: %s\n"), uid);
536       }
537       if (setuid(passw->pw_uid)) {
538          Emsg1(M_ERROR_TERM, 0, _("Could not set specified userid: %s\n"), uid);
539       }
540    }
541 #endif
542
543 }
544
545
546 /* BSDI does not have this.  This is a *poor* simulation */
547 #ifndef HAVE_STRTOLL
548 long long int
549 strtoll(const char *ptr, char **endptr, int base)
550 {
551    return (long long int)strtod(ptr, endptr);
552 }
553 #endif
554
555 /*
556  * Bacula's implementation of fgets(). The difference is that it handles
557  *   being interrupted by a signal (e.g. a SIGCHLD).
558  */
559 #undef fgetc
560 char *bfgets(char *s, int size, FILE *fd)
561 {
562    char *p = s;
563    int ch;
564    *p = 0;
565    for (int i=0; i < size-1; i++) {
566       do {
567          errno = 0;
568          ch = fgetc(fd);
569       } while (ch == -1 && (errno == EINTR || errno == EAGAIN));
570       if (ch == -1) {
571          if (i == 0) {
572             return NULL;
573          } else {
574             return s;
575          }
576       }
577       *p++ = ch;
578       *p = 0;
579       if (ch == '\r') { /* Support for Mac/Windows file format */
580          ch = fgetc(fd);
581          if (ch == '\n') { /* Windows (\r\n) */
582             *p++ = ch;
583             *p = 0;
584          }
585          else { /* Mac (\r only) */
586             ungetc(ch, fd); /* Push next character back to fd */
587          }
588          break;
589       }
590       if (ch == '\n') {
591          break;
592       }
593    }
594    return s;
595 }
596
597 /*
598  * Make a "unique" filename.  It is important that if
599  *   called again with the same "what" that the result
600  *   will be identical. This allows us to use the file
601  *   without saving its name, and re-generate the name
602  *   so that it can be deleted.
603  */
604 void make_unique_filename(POOLMEM **name, int Id, char *what)
605 {
606    Mmsg(name, "%s/%s.%s.%d.tmp", working_directory, my_name, what, Id);
607 }