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