]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/bsys.c
This commit was manufactured by cvs2svn to create tag
[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-2003 Kern Sibbald and John Walker
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 /*
40  * Guarantee that the string is properly terminated */
41 char *bstrncpy(char *dest, const char *src, int maxlen)
42 {
43    strncpy(dest, src, maxlen-1);
44    dest[maxlen-1] = 0;
45    return dest;
46 }
47
48 char *bstrncat(char *dest, const char *src, int maxlen)
49 {
50    strncat(dest, src, maxlen-1);
51    dest[maxlen-1] = 0;
52    return dest;
53 }
54
55
56 #ifndef DEBUG
57 void *bmalloc(size_t size)
58 {
59   void *buf;
60
61   buf = malloc(size);
62   if (buf == NULL) {
63      Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), strerror(errno));
64   }
65   return buf;
66 }
67 #endif
68
69 void *b_malloc(char *file, int line, size_t size)
70 {
71   void *buf;
72
73 #ifdef SMARTALLOC
74   buf = sm_malloc(file, line, size);
75 #else
76   buf = malloc(size);
77 #endif
78   if (buf == NULL) {
79      e_msg(file, line, M_ABORT, 0, _("Out of memory: ERR=%s\n"), strerror(errno));
80   }
81   return buf;
82 }
83
84
85 void *brealloc (void *buf, size_t size)
86 {
87    buf = realloc(buf, size);
88    if (buf == NULL) {
89       Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), strerror(errno));
90    }
91    return buf;
92 }
93
94
95 void *bcalloc (size_t size1, size_t size2)
96 {
97   void *buf;
98
99    buf = calloc(size1, size2);
100    if (buf == NULL) {
101       Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), strerror(errno));
102    }
103    return buf;
104 }
105
106
107 #define BIG_BUF 5000
108 /*
109  * Implement snprintf
110  */
111 int bsnprintf(char *str, int32_t size, const  char  *fmt,  ...) 
112 {
113 #ifdef HAVE_VSNPRINTF
114    va_list   arg_ptr;
115    int len;
116
117    va_start(arg_ptr, fmt);
118    len = vsnprintf(str, size, fmt, arg_ptr);
119    va_end(arg_ptr);
120    str[size-1] = 0;
121    return len;
122
123 #else
124
125    va_list   arg_ptr;
126    int len;
127    char *buf;
128
129    buf = get_memory(BIG_BUF);
130    va_start(arg_ptr, fmt);
131    len = vsprintf(buf, fmt, arg_ptr);
132    va_end(arg_ptr);
133    if (len >= BIG_BUF) {
134       Emsg0(M_ABORT, 0, _("Buffer overflow.\n"));
135    }
136    memcpy(str, buf, size);
137    str[size-1] = 0;
138    free_memory(buf);
139    return len;
140 #endif
141 }
142
143 /*
144  * Implement vsnprintf()
145  */
146 int bvsnprintf(char *str, int32_t size, const char  *format, va_list ap)
147 {
148 #ifdef HAVE_VSNPRINTF
149    int len;
150    len = vsnprintf(str, size, format, ap);
151    str[size-1] = 0;
152    return len;
153
154 #else
155
156    int len;
157    char *buf;
158    buf = get_memory(BIG_BUF);
159    len = vsprintf(buf, format, ap);
160    if (len >= BIG_BUF) {
161       Emsg0(M_ABORT, 0, _("Buffer overflow.\n"));
162    }
163    memcpy(str, buf, size);
164    str[size-1] = 0;
165    free_memory(buf);
166    return len;
167 #endif
168 }
169
170 #ifndef HAVE_LOCALTIME_R
171
172 struct tm *localtime_r(const time_t *timep, struct tm *tm)
173 {
174     static pthread_mutex_t mutex;
175     static int first = 1;
176     struct tm *ltm;
177
178     if (first) {
179        pthread_mutex_init(&mutex, NULL);
180        first = 0;
181     }
182     P(mutex);
183     ltm = localtime(timep);
184     if (ltm) {
185        memcpy(tm, ltm, sizeof(struct tm));
186     }
187     V(mutex);
188     return ltm ? tm : NULL;
189 }
190 #endif /* HAVE_LOCALTIME_R */
191
192 #ifndef HAVE_READDIR_R
193
194 #include <dirent.h>
195
196 int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
197 {
198     static pthread_mutex_t mutex;
199     static int first = 1;
200     struct dirent *ndir;
201     int stat;
202
203     if (first) {
204        pthread_mutex_init(&mutex, NULL);
205        first = 0;
206     }
207     P(mutex);
208     errno = 0;
209     ndir = readdir(dirp);
210     stat = errno;
211     if (ndir) {
212        memcpy(entry, ndir, sizeof(struct dirent));
213        strcpy(entry->d_name, ndir->d_name);
214        *result = entry;
215     } else {
216        *result = NULL;
217     }
218     V(mutex);
219     return stat;
220 }
221
222 #endif /* HAVE_READDIR_R */
223
224 #ifdef xxxxxxxxxx_STRERROR_R
225 int strerror_r(int errnum, char *buf, size_t bufsiz)
226 {
227     static pthread_mutex_t mutex;
228     static int first = 1;
229     int stat = 0;
230     char *msg;
231
232     if (first) {
233        pthread_mutex_init(&mutex, NULL);
234        first = 0;
235     }
236     P(mutex);
237
238     msg = strerror(errnum);
239     if (!msg) {
240        msg = _("Bad errno");
241        stat = -1;
242     }
243     bstrncpy(buf, msg, bufsiz);
244     V(mutex);
245     return stat;
246 }
247 #endif /* HAVE_STRERROR_R */
248
249 /*
250  * These are mutex routines that do error checking
251  *  for deadlock and such.  Normally not turned on.
252  */
253 #ifdef DEBUG_MUTEX
254 void _p(char *file, int line, pthread_mutex_t *m)
255 {
256    int errstat;
257    if ((errstat = pthread_mutex_trylock(m))) {
258       e_msg(file, line, M_ERROR, 0, _("Possible mutex deadlock.\n"));
259       /* We didn't get the lock, so do it definitely now */
260       if ((errstat=pthread_mutex_lock(m))) {
261          e_msg(file, line, M_ABORT, 0, _("Mutex lock failure. ERR=%s\n"),
262                strerror(errstat));
263       } else {
264          e_msg(file, line, M_ERROR, 0, _("Possible mutex deadlock resolved.\n"));
265       }
266          
267    }
268 }
269
270 void _v(char *file, int line, pthread_mutex_t *m)
271 {
272    int errstat;
273
274    if ((errstat=pthread_mutex_trylock(m)) == 0) {
275       e_msg(file, line, M_ERROR, 0, _("Mutex unlock not locked. ERR=%s\n"),
276            strerror(errstat));
277     }
278     if ((errstat=pthread_mutex_unlock(m))) {
279        e_msg(file, line, M_ABORT, 0, _("Mutex unlock failure. ERR=%s\n"),
280               strerror(errstat));
281     }
282 }
283 #endif /* DEBUG_MUTEX */
284
285 #ifndef HAVE_CYGWIN
286 static int del_pid_file_ok = FALSE;
287 #endif
288
289 /*
290  * Create a standard "Unix" pid file.
291  */
292 void create_pid_file(char *dir, char *progname, int port)
293 {
294 #ifndef HAVE_CYGWIN
295    int pidfd, len;
296    int oldpid;
297    char  pidbuf[20];
298    POOLMEM *fname = get_pool_memory(PM_FNAME);
299    struct stat statp;
300
301    Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
302    if (stat(mp_chr(fname), &statp) == 0) {
303       /* File exists, see what we have */
304       *pidbuf = 0;
305       if ((pidfd = open(mp_chr(fname), O_RDONLY)) < 0 || 
306            read(pidfd, &pidbuf, sizeof(pidbuf)) < 0 ||
307            sscanf(pidbuf, "%d", &oldpid) != 1) {
308          Emsg2(M_ERROR_TERM, 0, _("Cannot open pid file. %s ERR=%s\n"), fname, strerror(errno));
309       }
310       /* See if other Bacula is still alive */
311       if (kill(oldpid, 0) != -1 || errno != ESRCH) {
312          Emsg3(M_ERROR_TERM, 0, _("%s is already running. pid=%d\nCheck file %s\n"),
313                progname, oldpid, fname);
314       }
315       /* He is not alive, so take over file ownership */
316       unlink(mp_chr(fname));                  /* remove stale pid file */
317    }
318    /* Create new pid file */
319    if ((pidfd = open(mp_chr(fname), O_CREAT | O_TRUNC | O_WRONLY, 0644)) >= 0) {
320       len = sprintf(pidbuf, "%d\n", (int)getpid());
321       write(pidfd, pidbuf, len);
322       close(pidfd);
323       del_pid_file_ok = TRUE;         /* we created it so we can delete it */
324    } else {
325       Emsg2(M_ERROR_TERM, 0, _("Could not open pid file. %s ERR=%s\n"), fname, strerror(errno));
326    }
327    free_pool_memory(fname);
328 #endif
329 }
330
331 /*
332  * Delete the pid file if we created it
333  */
334 int delete_pid_file(char *dir, char *progname, int port)
335 {
336 #ifndef HAVE_CYGWIN
337    POOLMEM *fname = get_pool_memory(PM_FNAME);
338
339    if (!del_pid_file_ok) {
340       free_pool_memory(fname);
341       return 0;
342    }
343    del_pid_file_ok = FALSE;
344    Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
345    unlink(mp_chr(fname));
346    free_pool_memory(fname);
347 #endif
348    return 1;
349 }
350
351 /*
352  * Drop to privilege new userid and new gid if non-NULL
353  */
354 void drop(char *uid, char *gid)
355 {
356 #ifdef HAVE_GRP_H
357    if (gid) {
358       struct group *group;
359       gid_t gr_list[1];
360
361       if ((group = getgrnam(gid)) == NULL) {
362          Emsg1(M_ERROR_TERM, 0, _("Could not find specified group: %s\n"), gid);
363       }
364       if (setgid(group->gr_gid)) {
365          Emsg1(M_ERROR_TERM, 0, _("Could not set specified group: %s\n"), gid);
366       }
367       gr_list[0] = group->gr_gid;
368       if (setgroups(1, gr_list)) {
369          Emsg1(M_ERROR_TERM, 0, _("Could not set specified group: %s\n"), gid);
370       }
371    }
372 #endif
373
374 #ifdef HAVE_PWD_H
375    if (uid) {
376       struct passwd *passw;
377       if ((passw = getpwnam(uid)) == NULL) {
378          Emsg1(M_ERROR_TERM, 0, _("Could not find specified userid: %s\n"), uid);
379       }
380       if (setuid(passw->pw_uid)) {
381          Emsg1(M_ERROR_TERM, 0, _("Could not set specified userid: %s\n"), uid);
382       }
383    }
384 #endif
385           
386 }
387
388 static pthread_mutex_t timer_mutex = PTHREAD_MUTEX_INITIALIZER;
389 static pthread_cond_t timer = PTHREAD_COND_INITIALIZER;
390
391 /*
392  * This routine will sleep (sec, microsec).  Note, however, that if a 
393  *   signal occurs, it will return early.  It is up to the caller
394  *   to recall this routine if he/she REALLY wants to sleep the
395  *   requested time.
396  */
397 int bmicrosleep(time_t sec, long usec)
398 {
399    struct timespec timeout;
400    struct timeval tv;
401    struct timezone tz;
402    int stat;
403
404    timeout.tv_sec = sec;
405    timeout.tv_nsec = usec * 1000;
406
407 #ifdef HAVE_NANOSLEEP
408    stat = nanosleep(&timeout, NULL);
409    if (!(stat < 0 && errno == ENOSYS)) {
410       return stat;                   
411    }
412    /* If we reach here it is because nanosleep is not supported by the OS */
413 #endif
414
415    /* Do it the old way */
416    gettimeofday(&tv, &tz);
417    timeout.tv_nsec += tv.tv_usec * 1000;
418    timeout.tv_sec += tv.tv_sec;
419    while (timeout.tv_nsec >= 1000000000) {
420       timeout.tv_nsec -= 1000000000;
421       timeout.tv_sec++;
422    }
423
424    Dmsg1(200, "pthread_cond_timedwait sec=%d\n", timeout.tv_sec);
425    /* Note, this unlocks mutex during the sleep */
426    P(timer_mutex);
427    stat = pthread_cond_timedwait(&timer, &timer_mutex, &timeout);
428    Dmsg1(200, "pthread_cond_timedwait stat=%d\n", stat);
429    V(timer_mutex);
430    return stat;
431 }
432
433 /* BSDI does not have this.  This is a *poor* simulation */
434 #ifndef HAVE_STRTOLL
435 long long int
436 strtoll(const char *ptr, char **endptr, int base)
437 {
438    return (long long int)strtod(ptr, endptr);   
439 }
440 #endif
441
442 /*
443  * Bacula's implementation of fgets(). The difference is that it handles
444  *   being interrupted by a signal (e.g. a SIGCHLD).
445  */
446 #undef fgetc
447 char *bfgets(char *s, int size, FILE *fd)
448 {
449    char *p = s;
450    int ch;       
451    *p = 0;
452    for (int i=0; i < size-1; i++) {
453       do {
454          errno = 0;
455          ch = fgetc(fd);
456       } while (ch == -1 && (errno == EINTR || errno == EAGAIN));
457       if (ch == -1) {
458          if (i == 0) {
459             return NULL;
460          } else {
461             return s;
462          }
463       }
464       *p++ = ch;
465       *p = 0;
466       if (ch == '\n') {
467          break;
468       }
469    }
470    return s;
471 }
472
473 /*
474  * Make a "unique" filename.  It is important that if
475  *   called again with the same "what" that the result
476  *   will be identical. This allows us to use the file
477  *   without saving its name, and re-generate the name
478  *   so that it can be deleted.
479  */
480 void make_unique_filename(POOLMEM **name, int Id, char *what)
481 {
482    Mmsg(name, "%s/%s.%s.%d.tmp", working_directory, my_name, what, Id);
483 }