]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/bsys.c
Update projects
[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-2005 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 = PTHREAD_MUTEX_INITIALIZER;
222     struct tm *ltm,
223
224     P(mutex);
225     ltm = localtime(timep);
226     if (ltm) {
227        memcpy(tm, ltm, sizeof(struct tm));
228     }
229     V(mutex);
230     return ltm ? tm : NULL;
231 }
232 #endif /* HAVE_LOCALTIME_R */
233
234 #ifndef HAVE_READDIR_R
235 #ifndef HAVE_WIN32
236 #include <dirent.h>
237
238 int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
239 {
240     static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
241     struct dirent *ndir;
242     int stat;
243
244     P(mutex);
245     errno = 0;
246     ndir = readdir(dirp);
247     stat = errno;
248     if (ndir) {
249        memcpy(entry, ndir, sizeof(struct dirent));
250        strcpy(entry->d_name, ndir->d_name);
251        *result = entry;
252     } else {
253        *result = NULL;
254     }
255     V(mutex);
256     return stat;
257
258 }
259 #endif
260 #endif /* HAVE_READDIR_R */
261
262
263 int bstrerror(int errnum, char *buf, size_t bufsiz)
264 {
265     static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
266     int stat = 0;
267     const char *msg;
268
269     P(mutex);
270
271     msg = strerror(errnum);
272     if (!msg) {
273        msg = _("Bad errno");
274        stat = -1;
275     }
276     bstrncpy(buf, msg, bufsiz);
277     V(mutex);
278     return stat;
279 }
280
281 /*
282  * These are mutex routines that do error checking
283  *  for deadlock and such.  Normally not turned on.
284  */
285 #ifdef DEBUG_MUTEX
286 void _p(char *file, int line, pthread_mutex_t *m)
287 {
288    int errstat;
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))) {
293          berrno be;
294          e_msg(file, line, M_ABORT, 0, _("Mutex lock failure. ERR=%s\n"),
295                be.strerror(errstat));
296       } else {
297          e_msg(file, line, M_ERROR, 0, _("Possible mutex deadlock resolved.\n"));
298       }
299
300    }
301 }
302
303 void _v(char *file, int line, pthread_mutex_t *m)
304 {
305    int errstat;
306
307    if ((errstat=pthread_mutex_trylock(m)) == 0) {
308       berrno be;
309       e_msg(file, line, M_ERROR, 0, _("Mutex unlock not locked. ERR=%s\n"),
310            be.strerror(errstat));
311     }
312     if ((errstat=pthread_mutex_unlock(m))) {
313        berrno be;
314        e_msg(file, line, M_ABORT, 0, _("Mutex unlock failure. ERR=%s\n"),
315               be.strerror(errstat));
316     }
317 }
318
319 #else
320
321 void _p(pthread_mutex_t *m)
322 {
323    int errstat;
324    if ((errstat=pthread_mutex_lock(m))) {
325       berrno be;
326       e_msg(__FILE__, __LINE__, M_ABORT, 0, _("Mutex lock failure. ERR=%s\n"),
327             be.strerror(errstat));
328    }
329 }
330
331 void _v(pthread_mutex_t *m)
332 {
333    int errstat;
334    if ((errstat=pthread_mutex_unlock(m))) {
335       berrno be;
336       e_msg(__FILE__, __LINE__, M_ABORT, 0, _("Mutex unlock failure. ERR=%s\n"),
337             be.strerror(errstat));
338    }
339 }
340
341 #endif /* DEBUG_MUTEX */
342
343 #ifdef DEBUG_MEMSET
344 /* These routines are not normally turned on */
345 #undef memset
346 void b_memset(const char *file, int line, void *mem, int val, size_t num)
347 {
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);
351    }
352    memset(mem, val, num);
353 }
354 #endif
355
356 #if !defined(HAVE_CYGWIN) && !defined(HAVE_WIN32)
357 static int del_pid_file_ok = FALSE;
358 #endif
359
360 /*
361  * Create a standard "Unix" pid file.
362  */
363 void create_pid_file(char *dir, const char *progname, int port)
364 {
365 #if !defined(HAVE_CYGWIN) && !defined(HAVE_WIN32)
366    int pidfd, len;
367    int oldpid;
368    char  pidbuf[20];
369    POOLMEM *fname = get_pool_memory(PM_FNAME);
370    struct stat statp;
371
372    Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
373    if (stat(fname, &statp) == 0) {
374       /* File exists, see what we have */
375       *pidbuf = 0;
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));
380       }
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);
385       }
386       /* He is not alive, so take over file ownership */
387       unlink(fname);                  /* remove stale pid file */
388    }
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);
393       close(pidfd);
394       del_pid_file_ok = TRUE;         /* we created it so we can delete it */
395    } else {
396       Emsg2(M_ERROR_TERM, 0, _("Could not open pid file. %s ERR=%s\n"), fname, strerror(errno));
397    }
398    free_pool_memory(fname);
399 #endif
400 }
401
402
403 /*
404  * Delete the pid file if we created it
405  */
406 int delete_pid_file(char *dir, const char *progname, int port)
407 {
408 #if !defined(HAVE_CYGWIN)  && !defined(HAVE_WIN32)
409    POOLMEM *fname = get_pool_memory(PM_FNAME);
410
411    if (!del_pid_file_ok) {
412       free_pool_memory(fname);
413       return 0;
414    }
415    del_pid_file_ok = FALSE;
416    Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
417    unlink(fname);
418    free_pool_memory(fname);
419 #endif
420    return 1;
421 }
422
423 struct s_state_hdr {
424    char id[14];
425    int32_t version;
426    uint64_t last_jobs_addr;
427    uint64_t reserved[20];
428 };
429
430 static struct s_state_hdr state_hdr = {
431    "Bacula State\n",
432    3,
433    0
434 };
435
436 /*
437  * Open and read the state file for the daemon
438  */
439 void read_state_file(char *dir, const char *progname, int port)
440 {
441    int sfd;
442    ssize_t stat;
443    POOLMEM *fname = get_pool_memory(PM_FNAME);
444    struct s_state_hdr hdr;
445    int hdr_size = sizeof(hdr);
446
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));
453            goto bail_out;
454    }
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));
458       goto bail_out;
459    }
460    if (hdr.version != state_hdr.version) {
461       Dmsg2(010, "Bad hdr version. Wanted %d got %d\n",
462          state_hdr.version, hdr.version);
463    }
464    hdr.id[13] = 0;
465    if (strcmp(hdr.id, state_hdr.id) != 0) {
466       Dmsg0(000, "State file header id invalid.\n");
467       goto bail_out;
468    }
469 // Dmsg1(010, "Read header of %d bytes.\n", sizeof(hdr));
470    read_last_jobs_list(sfd, hdr.last_jobs_addr);
471 bail_out:
472    if (sfd >= 0) {
473       close(sfd);
474    }
475    free_pool_memory(fname);
476 }
477
478 /*
479  * Write the state file
480  */
481 void write_state_file(char *dir, const char *progname, int port)
482 {
483    int sfd;
484    POOLMEM *fname = get_pool_memory(PM_FNAME);
485
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));
491       goto bail_out;
492    }
493    if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
494       Dmsg1(000, "Write hdr error: ERR=%s\n", strerror(errno));
495       goto bail_out;
496    }
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));
503       goto bail_out;
504    }
505    if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
506       Pmsg1(000, "Write final hdr error: ERR=%s\n", strerror(errno));
507    }
508 // Dmsg1(010, "rewrote header = %d\n", sizeof(state_hdr));
509 bail_out:
510    if (sfd >= 0) {
511       close(sfd);
512    }
513    free_pool_memory(fname);
514 }
515
516
517 /*
518  * Drop to privilege new userid and new gid if non-NULL
519  */
520 void drop(char *uid, char *gid)
521 {
522 #ifdef HAVE_GRP_H
523    if (gid) {
524       struct group *group;
525       gid_t gr_list[1];
526
527       if ((group = getgrnam(gid)) == NULL) {
528          Emsg1(M_ERROR_TERM, 0, _("Could not find specified group: %s\n"), gid);
529       }
530       if (setgid(group->gr_gid)) {
531          Emsg1(M_ERROR_TERM, 0, _("Could not set specified group: %s\n"), gid);
532       }
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);
536       }
537    }
538 #endif
539
540 #ifdef HAVE_PWD_H
541    if (uid) {
542       struct passwd *passw;
543       if ((passw = getpwnam(uid)) == NULL) {
544          Emsg1(M_ERROR_TERM, 0, _("Could not find specified userid: %s\n"), uid);
545       }
546       if (setuid(passw->pw_uid)) {
547          Emsg1(M_ERROR_TERM, 0, _("Could not set specified userid: %s\n"), uid);
548       }
549    }
550 #endif
551
552 }
553
554
555 /* BSDI does not have this.  This is a *poor* simulation */
556 #ifndef HAVE_STRTOLL
557 long long int
558 strtoll(const char *ptr, char **endptr, int base)
559 {
560    return (long long int)strtod(ptr, endptr);
561 }
562 #endif
563
564 /*
565  * Bacula's implementation of fgets(). The difference is that it handles
566  *   being interrupted by a signal (e.g. a SIGCHLD).
567  */
568 #undef fgetc
569 char *bfgets(char *s, int size, FILE *fd)
570 {
571    char *p = s;
572    int ch;
573    *p = 0;
574    for (int i=0; i < size-1; i++) {
575       do {
576          errno = 0;
577          ch = fgetc(fd);
578       } while (ch == -1 && (errno == EINTR || errno == EAGAIN));
579       if (ch == -1) {
580          if (i == 0) {
581             return NULL;
582          } else {
583             return s;
584          }
585       }
586       *p++ = ch;
587       *p = 0;
588       if (ch == '\r') { /* Support for Mac/Windows file format */
589          ch = fgetc(fd);
590          if (ch == '\n') { /* Windows (\r\n) */
591             *p++ = ch;
592             *p = 0;
593          }
594          else { /* Mac (\r only) */
595             ungetc(ch, fd); /* Push next character back to fd */
596          }
597          break;
598       }
599       if (ch == '\n') {
600          break;
601       }
602    }
603    return s;
604 }
605
606 /*
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.
612  */
613 void make_unique_filename(POOLMEM **name, int Id, char *what)
614 {
615    Mmsg(name, "%s/%s.%s.%d.tmp", working_directory, my_name, what, Id);
616 }