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