]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/bsys.c
ab5ebe50ae44f0420a50a194e89a10448144b28f
[bacula/bacula] / bacula / src / lib / bsys.c
1 /*
2    Bacula(R) - The Network Backup Solution
3
4    Copyright (C) 2000-2017 Kern Sibbald
5
6    The original author of Bacula is Kern Sibbald, with contributions
7    from many others, a complete list can be found in the file AUTHORS.
8
9    You may use this file and others of this release according to the
10    license defined in the LICENSE file, which includes the Affero General
11    Public License, v3.0 ("AGPLv3") and some additional permissions and
12    terms pursuant to its AGPLv3 Section 7.
13
14    This notice must be preserved when any source code is 
15    conveyed and/or propagated.
16
17    Bacula(R) is a registered trademark of Kern Sibbald.
18 */
19 /*
20  * Miscellaneous Bacula memory and thread safe routines
21  *   Generally, these are interfaces to system or standard
22  *   library routines.
23  *
24  *  Bacula utility functions are in util.c
25  *
26  */
27
28 #include "bacula.h"
29 #ifndef HAVE_REGEX_H
30 #include "lib/bregex.h"
31 #else
32 #include <regex.h>
33 #endif
34
35 static pthread_mutex_t timer_mutex = PTHREAD_MUTEX_INITIALIZER;
36 static pthread_cond_t timer = PTHREAD_COND_INITIALIZER;
37
38 /*
39  * Quote a string
40  */
41 POOLMEM *quote_string(POOLMEM *snew, const char *old)
42 {
43    char *n;
44    int i;
45
46    if (!old) {
47       strcpy(snew, "null");
48       return snew;
49    }
50    n = snew;
51    *n++ = '"';
52    for (i=0; old[i]; i++) {
53       switch (old[i]) {
54       case '"':
55          *n++ = '\\';
56          *n++ = '"';
57          break;
58       case '\\':
59          *n++ = '\\';
60          *n++ = '\\';
61          break;
62       case '\r':
63          *n++ = '\\';
64          *n++ = 'r';
65          break;
66       case '\n':
67          *n++ = '\\';
68          *n++ = 'n';
69          break;
70       default:
71          *n++ = old[i];
72          break;
73       }
74    }
75    *n++ = '"';
76    *n = 0;
77    return snew;
78 }
79
80 /*
81  * Quote a where (list of addresses separated by spaces)
82  */
83 POOLMEM *quote_where(POOLMEM *snew, const char *old)
84 {
85    char *n;
86    int i;
87
88    if (!old) {
89       strcpy(snew, "null");
90       return snew;
91    }
92    n = snew;
93    *n++ = '"';
94    for (i=0; old[i]; i++) {
95       switch (old[i]) {
96       case ' ':
97          *n++ = '"';
98          *n++ = ',';
99          *n++ = '"';
100          break;
101       case '"':
102          *n++ = '\\';
103          *n++ = '"';
104          break;
105       case '\\':
106          *n++ = '\\';
107          *n++ = '\\';
108          break;
109       default:
110          *n++ = old[i];
111          break;
112       }
113    }
114    *n++ = '"';
115    *n = 0;
116    return snew;
117 }
118
119 /*
120  * This routine is a somewhat safer unlink in that it
121  *   allows you to run a regex on the filename before
122  *   excepting it. It also requires the file to be in
123  *   the working directory.
124  */
125 int safer_unlink(const char *pathname, const char *regx)
126 {
127    int rc;
128    regex_t preg1;
129    char prbuf[500];
130    const int nmatch = 30;
131    regmatch_t pmatch[nmatch];
132    int rtn;
133
134    /* Name must start with working directory */
135    if (strncmp(pathname, working_directory, strlen(working_directory)) != 0) {
136       Pmsg1(000, "Safe_unlink excluded: %s\n", pathname);
137       return EROFS;
138    }
139
140    /* Compile regex expression */
141    rc = regcomp(&preg1, regx, REG_EXTENDED);
142    if (rc != 0) {
143       regerror(rc, &preg1, prbuf, sizeof(prbuf));
144       Pmsg2(000,  _("safe_unlink could not compile regex pattern \"%s\" ERR=%s\n"),
145            regx, prbuf);
146       return ENOENT;
147    }
148
149    /* Unlink files that match regexes */
150    if (regexec(&preg1, pathname, nmatch, pmatch,  0) == 0) {
151       Dmsg1(100, "safe_unlink unlinking: %s\n", pathname);
152       rtn = unlink(pathname);
153    } else {
154       Pmsg2(000, "safe_unlink regex failed: regex=%s file=%s\n", regx, pathname);
155       rtn = EROFS;
156    }
157    regfree(&preg1);
158    return rtn;
159 }
160
161 /*
162  * This routine will sleep (sec, microsec).  Note, however, that if a
163  *   signal occurs, it will return early.  It is up to the caller
164  *   to recall this routine if he/she REALLY wants to sleep the
165  *   requested time.
166  */
167 int bmicrosleep(int32_t sec, int32_t usec)
168 {
169    struct timespec timeout;
170    struct timeval tv;
171    struct timezone tz;
172    int stat;
173
174    timeout.tv_sec = sec;
175    timeout.tv_nsec = usec * 1000;
176
177 #ifdef HAVE_NANOSLEEP
178    stat = nanosleep(&timeout, NULL);
179    if (!(stat < 0 && errno == ENOSYS)) {
180       return stat;
181    }
182    /* If we reach here it is because nanosleep is not supported by the OS */
183 #endif
184
185    /* Do it the old way */
186    gettimeofday(&tv, &tz);
187    timeout.tv_nsec += tv.tv_usec * 1000;
188    timeout.tv_sec += tv.tv_sec;
189    while (timeout.tv_nsec >= 1000000000) {
190       timeout.tv_nsec -= 1000000000;
191       timeout.tv_sec++;
192    }
193
194    Dmsg2(200, "pthread_cond_timedwait sec=%d usec=%d\n", sec, usec);
195    /* Note, this unlocks mutex during the sleep */
196    P(timer_mutex);
197    stat = pthread_cond_timedwait(&timer, &timer_mutex, &timeout);
198    if (stat != 0) {
199       berrno be;
200       Dmsg2(200, "pthread_cond_timedwait stat=%d ERR=%s\n", stat,
201          be.bstrerror(stat));
202    }
203    V(timer_mutex);
204    return stat;
205 }
206
207 /*
208  * Guarantee that the string is properly terminated */
209 char *bstrncpy(char *dest, const char *src, int maxlen)
210 {
211    strncpy(dest, src, maxlen-1);
212    dest[maxlen-1] = 0;
213    return dest;
214 }
215
216 /*
217  * Guarantee that the string is properly terminated */
218 char *bstrncpy(char *dest, POOL_MEM &src, int maxlen)
219 {
220    strncpy(dest, src.c_str(), maxlen-1);
221    dest[maxlen-1] = 0;
222    return dest;
223 }
224
225 /*
226  * Note: Here the maxlen is the maximum length permitted
227  *  stored in dest, while on Unix systems, it is the maximum characters
228  *  that may be copied from src.
229  */
230 char *bstrncat(char *dest, const char *src, int maxlen)
231 {
232    int len = strlen(dest);
233    if (len < maxlen-1) {
234       strncpy(dest+len, src, maxlen-len-1);
235    }
236    dest[maxlen-1] = 0;
237    return dest;
238 }
239
240 /*
241  * Note: Here the maxlen is the maximum length permitted
242  *  stored in dest, while on Unix systems, it is the maximum characters
243  *  that may be copied from src.
244  */
245 char *bstrncat(char *dest, POOL_MEM &src, int maxlen)
246 {
247    int len = strlen(dest);
248    if (len < maxlen-1) {
249       strncpy(dest+len, src.c_str(), maxlen-len-1);
250    }
251    dest[maxlen-1] = 0;
252    return dest;
253 }
254
255 /*
256  * Allows one or both pointers to be NULL
257  */
258 bool bstrcmp(const char *s1, const char *s2)
259 {
260    if (s1 == s2) return true;
261    if (s1 == NULL || s2 == NULL) return false;
262    return strcmp(s1, s2) == 0;
263 }
264
265 /*
266  * Allows one or both pointers to be NULL
267  */
268 bool bstrcasecmp(const char *s1, const char *s2)
269 {
270    if (s1 == s2) return true;
271    if (s1 == NULL || s2 == NULL) return false;
272    return strcasecmp(s1, s2) == 0;
273 }
274
275
276 /*
277  * Get character length of UTF-8 string
278  *
279  * Valid UTF-8 codes
280  * U-00000000 - U-0000007F: 0xxxxxxx
281  * U-00000080 - U-000007FF: 110xxxxx 10xxxxxx
282  * U-00000800 - U-0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx
283  * U-00010000 - U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
284  * U-00200000 - U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
285  * U-04000000 - U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
286  */
287 int cstrlen(const char *str)
288 {
289    uint8_t *p = (uint8_t *)str;
290    int len = 0;
291    if (str == NULL) {
292       return 0;
293    }
294    while (*p) {
295       if ((*p & 0xC0) != 0xC0) {
296          p++;
297          len++;
298          continue;
299       }
300       if ((*p & 0xD0) == 0xC0) {
301          p += 2;
302          len++;
303          continue;
304       }
305       if ((*p & 0xF0) == 0xD0) {
306          p += 3;
307          len++;
308          continue;
309       }
310       if ((*p & 0xF8) == 0xF0) {
311          p += 4;
312          len++;
313          continue;
314       }
315       if ((*p & 0xFC) == 0xF8) {
316          p += 5;
317          len++;
318          continue;
319       }
320       if ((*p & 0xFE) == 0xFC) {
321          p += 6;
322          len++;
323          continue;
324       }
325       p++;                      /* Shouln't get here but must advance */
326    }
327    return len;
328 }
329
330 /* We need to disable the malloc() macro if SMARTALLOC is not used,
331  * else, it points to b_malloc() and causes problems.
332  */
333 #ifndef SMARTALLOC
334  #ifdef malloc
335   #undef malloc
336  #endif
337 #endif
338
339 #ifndef bmalloc
340 void *bmalloc(size_t size)
341 {
342   void *buf;
343
344 #ifdef SMARTALLOC
345   buf = sm_malloc(file, line, size);
346 #else
347   buf = malloc(size);
348 #endif
349   if (buf == NULL) {
350      berrno be;
351      Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.bstrerror());
352   }
353   return buf;
354 }
355 #endif
356
357 void *b_malloc(const char *file, int line, size_t size)
358 {
359   void *buf;
360
361 #ifdef SMARTALLOC
362   buf = sm_malloc(file, line, size);
363 #else
364   buf = malloc(size);
365 #endif
366   if (buf == NULL) {
367      berrno be;
368      e_msg(file, line, M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.bstrerror());
369   }
370   return buf;
371 }
372
373
374 void bfree(void *buf)
375 {
376 #ifdef SMARTALLOC
377   sm_free(__FILE__, __LINE__, buf);
378 #else
379   free(buf);
380 #endif
381 }
382
383 void *brealloc (void *buf, size_t size)
384 {
385 #ifdef SMARTALOC
386    buf = sm_realloc(__FILE__, __LINE__, buf, size);
387 #else
388    buf = realloc(buf, size);
389 #endif
390    if (buf == NULL) {
391       berrno be;
392       Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.bstrerror());
393    }
394    return buf;
395 }
396
397
398 void *bcalloc(size_t size1, size_t size2)
399 {
400   void *buf;
401
402    buf = calloc(size1, size2);
403    if (buf == NULL) {
404       berrno be;
405       Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.bstrerror());
406    }
407    return buf;
408 }
409
410 /* Code now in src/lib/bsnprintf.c */
411 #ifndef USE_BSNPRINTF
412
413 #define BIG_BUF 5000
414 /*
415  * Implement snprintf
416  */
417 int bsnprintf(char *str, int32_t size, const char *fmt,  ...)
418 {
419    va_list   arg_ptr;
420    int len;
421
422    va_start(arg_ptr, fmt);
423    len = bvsnprintf(str, size, fmt, arg_ptr);
424    va_end(arg_ptr);
425    return len;
426 }
427
428 /*
429  * Implement vsnprintf()
430  */
431 int bvsnprintf(char *str, int32_t size, const char  *format, va_list ap)
432 {
433 #ifdef HAVE_VSNPRINTF
434    int len;
435    len = vsnprintf(str, size, format, ap);
436    str[size-1] = 0;
437    return len;
438
439 #else
440
441    int len, buflen;
442    char *buf;
443    buflen = size > BIG_BUF ? size : BIG_BUF;
444    buf = get_memory(buflen);
445    len = vsprintf(buf, format, ap);
446    if (len >= buflen) {
447       Emsg0(M_ABORT, 0, _("Buffer overflow.\n"));
448    }
449    memcpy(str, buf, len);
450    str[len] = 0;                /* len excludes the null */
451    free_memory(buf);
452    return len;
453 #endif
454 }
455 #endif /* USE_BSNPRINTF */
456
457 #ifndef HAVE_LOCALTIME_R
458
459 struct tm *localtime_r(const time_t *timep, struct tm *tm)
460 {
461     static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
462     struct tm *ltm,
463
464     P(mutex);
465     ltm = localtime(timep);
466     if (ltm) {
467        memcpy(tm, ltm, sizeof(struct tm));
468     }
469     V(mutex);
470     return ltm ? tm : NULL;
471 }
472 #endif /* HAVE_LOCALTIME_R */
473
474 #ifndef HAVE_READDIR_R
475 #ifndef HAVE_WIN32
476 #include <dirent.h>
477
478 int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
479 {
480     static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
481     struct dirent *ndir;
482     int stat;
483
484     P(mutex);
485     errno = 0;
486     ndir = readdir(dirp);
487     stat = errno;
488     if (ndir) {
489        memcpy(entry, ndir, sizeof(struct dirent));
490        strcpy(entry->d_name, ndir->d_name);
491        *result = entry;
492     } else {
493        *result = NULL;
494     }
495     V(mutex);
496     return stat;
497
498 }
499 #endif
500 #endif /* HAVE_READDIR_R */
501
502
503 int b_strerror(int errnum, char *buf, size_t bufsiz)
504 {
505     static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
506     int stat = 0;
507     const char *msg;
508
509     P(mutex);
510
511     msg = strerror(errnum);
512     if (!msg) {
513        msg = _("Bad errno");
514        stat = -1;
515     }
516     bstrncpy(buf, msg, bufsiz);
517     V(mutex);
518     return stat;
519 }
520
521 #ifdef DEBUG_MEMSET
522 /* These routines are not normally turned on */
523 #undef memset
524 void b_memset(const char *file, int line, void *mem, int val, size_t num)
525 {
526    /* Testing for 2000 byte zero at beginning of Volume block */
527    if (num > 1900 && num < 3000) {
528       Pmsg3(000, _("Memset for %d bytes at %s:%d\n"), (int)num, file, line);
529    }
530    memset(mem, val, num);
531 }
532 #endif
533
534 #if !defined(HAVE_WIN32)
535 static int del_pid_file_ok = FALSE;
536 #endif
537 static int pid_fd = -1;
538
539 #ifdef HAVE_FCNTL_LOCK
540 /* a convenient function [un]lock file using fnctl()
541  * code must be in F_UNLCK, F_RDLCK, F_WRLCK
542  * return -1 for error and errno is set
543  */
544 int fcntl_lock(int fd, int code)
545 {
546    struct flock l;
547    l.l_type = code;
548    l.l_whence = l.l_start = l.l_len = 0;
549    l.l_len = 1;
550    return fcntl(fd, F_SETLK, &l);
551 }
552 #endif
553
554 /* Create a disk pid "lock" file
555  *  returns
556  *    0: Error with the error message in errmsg
557  *    1: Succcess
558  *    2: Successs, but a previous file was found
559  */
560 #if !defined(HAVE_FCNTL_LOCK) || defined(HAVE_WIN32)
561 int create_lock_file(char *fname, const char *progname, const char *filetype, POOLMEM **errmsg, int *fd)
562 {
563    int ret = 1;
564 #if !defined(HAVE_WIN32)
565    int pidfd, len;
566    int oldpid;
567    char  pidbuf[20];
568    struct stat statp;
569
570    if (stat(fname, &statp) == 0) {
571       /* File exists, see what we have */
572       *pidbuf = 0;
573       if ((pidfd = open(fname, O_RDONLY|O_BINARY, 0)) < 0 ||
574            read(pidfd, &pidbuf, sizeof(pidbuf)) < 0 ||
575            sscanf(pidbuf, "%d", &oldpid) != 1) {
576          berrno be;
577          Mmsg(errmsg, _("Cannot open %s file. %s ERR=%s\n"), filetype, fname,
578               be.bstrerror());
579          close(pidfd); /* if it was successfully opened */
580          return 0;
581       }
582       /* Some OSes (IRIX) don't bother to clean out the old pid files after a crash, and
583        * since they use a deterministic algorithm for assigning PIDs, we can have
584        * pid conflicts with the old PID file after a reboot.
585        * The intent the following code is to check if the oldpid read from the pid
586        * file is the same as the currently executing process's pid,
587        * and if oldpid == getpid(), skip the attempt to
588        * kill(oldpid,0), since the attempt is guaranteed to succeed,
589        * but the success won't actually mean that there is an
590        * another Bacula process already running.
591        * For more details see bug #797.
592        */
593        if ((oldpid != (int)getpid()) && (kill(oldpid, 0) != -1 || errno != ESRCH)) {
594           Mmsg(errmsg, _("%s is already running. pid=%d\nCheck file %s\n"),
595                progname, oldpid, fname);
596           return 0;
597       }
598       /* He is not alive, so take over file ownership */
599       unlink(fname);                  /* remove stale pid file */
600       ret = 2;
601    }
602    /* Create new pid file */
603    if ((pidfd = open(fname, O_CREAT|O_TRUNC|O_WRONLY|O_BINARY, 0640)) >= 0) {
604       len = sprintf(pidbuf, "%d\n", (int)getpid());
605       write(pidfd, pidbuf, len);
606       close(pidfd);
607       /* ret is already 1 */
608    } else {
609       berrno be;
610       Mmsg(errmsg, _("Could not open %s file. %s ERR=%s\n"), filetype, fname, be.bstrerror());
611       return 0;
612    }
613 #endif
614    return ret;
615 }
616 #else /* defined(HAVE_FCNTL_LOCK) */
617 int create_lock_file(char *fname, const char *progname, const char *filetype, POOLMEM **errmsg, int *fd)
618 {
619    int len;
620    int oldpid;
621    char pidbuf[20];
622
623    /* Open the pidfile for writing */
624    if ((*fd = open(fname, O_CREAT|O_RDWR, 0640)) >= 0) {
625       if (fcntl_lock(*fd, F_WRLCK) == -1) {
626          berrno be;
627          /* already locked by someone else, try to read the pid */
628          if (read(*fd, &pidbuf, sizeof(pidbuf)) > 0 &&
629              sscanf(pidbuf, "%d", &oldpid) == 1) {
630             Mmsg(errmsg, _("%s is already running. pid=%d, check file %s\n"),
631                  progname, oldpid, fname);
632          } else {
633             Mmsg(errmsg, _("Cannot lock %s file. %s ERR=%s\n"), filetype, fname, be.bstrerror());
634          }
635          close(*fd);
636          *fd=-1;
637          return 0;
638       }
639       /* write the pid */
640       len = sprintf(pidbuf, "%d\n", (int)getpid());
641       write(*fd, pidbuf, len);
642       /* KEEP THE FILE OPEN TO KEEP THE LOCK !!! */
643       return 1;
644    } else {
645       berrno be;
646       Mmsg(errmsg, _("Cannot not open %s file. %s ERR=%s\n"), filetype, fname, be.bstrerror());
647       return 0;
648    }
649 }
650 #endif
651
652 /*
653  * Create a standard "Unix" pid file.
654  */
655 void create_pid_file(char *dir, const char *progname, int port)
656 {
657    POOLMEM *errmsg = get_pool_memory(PM_MESSAGE);
658    POOLMEM *fname = get_pool_memory(PM_FNAME);
659
660    Mmsg(fname, "%s/%s.%d.pid", dir, progname, port);
661    if (create_lock_file(fname, progname, "pid", &errmsg, &pid_fd) == 0) {
662       Emsg1(M_ERROR_TERM, 0, "%s", errmsg);
663       /* never return */
664    }
665 #if !defined(HAVE_WIN32)
666    del_pid_file_ok = TRUE;         /* we created it so we can delete it */
667 #endif
668
669    free_pool_memory(fname);
670    free_pool_memory(errmsg);
671 }
672
673 /*
674  * Delete the pid file if we created it
675  */
676 int delete_pid_file(char *dir, const char *progname, int port)
677 {
678 #if !defined(HAVE_WIN32)
679    POOLMEM *fname = get_pool_memory(PM_FNAME);
680    if (pid_fd!=-1) {
681       close(pid_fd);
682    }
683    if (!del_pid_file_ok) {
684       free_pool_memory(fname);
685       return 0;
686    }
687    del_pid_file_ok = FALSE;
688    Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
689    unlink(fname);
690    free_pool_memory(fname);
691 #endif
692    return 1;
693 }
694
695 struct s_state_hdr {
696    char id[14];
697    int32_t version;
698    uint64_t last_jobs_addr;
699    uint64_t reserved[20];
700 };
701
702 static struct s_state_hdr state_hdr = {
703    "Bacula State\n",
704    4,
705    0
706 };
707
708 /*
709  * Open and read the state file for the daemon
710  */
711 void read_state_file(char *dir, const char *progname, int port)
712 {
713    int sfd;
714    ssize_t stat;
715    bool ok = false;
716    POOLMEM *fname = get_pool_memory(PM_FNAME);
717    struct s_state_hdr hdr;
718    int hdr_size = sizeof(hdr);
719
720    Mmsg(&fname, "%s/%s.%d.state", dir, progname, port);
721    /* If file exists, see what we have */
722 // Dmsg1(10, "O_BINARY=%d\n", O_BINARY);
723    if ((sfd = open(fname, O_RDONLY|O_BINARY)) < 0) {
724       berrno be;
725       Dmsg3(010, "Could not open state file. sfd=%d size=%d: ERR=%s\n",
726             sfd, (int)sizeof(hdr), be.bstrerror());
727       goto bail_out;
728    }
729    if ((stat=read(sfd, &hdr, hdr_size)) != hdr_size) {
730       berrno be;
731       Dmsg4(010, "Could not read state file. sfd=%d stat=%d size=%d: ERR=%s\n",
732                     sfd, (int)stat, hdr_size, be.bstrerror());
733       goto bail_out;
734    }
735    if (hdr.version != state_hdr.version) {
736       Dmsg2(010, "Bad hdr version. Wanted %d got %d\n",
737          state_hdr.version, hdr.version);
738       goto bail_out;
739    }
740    hdr.id[13] = 0;
741    if (strcmp(hdr.id, state_hdr.id) != 0) {
742       Dmsg0(000, "State file header id invalid.\n");
743       goto bail_out;
744    }
745 // Dmsg1(010, "Read header of %d bytes.\n", sizeof(hdr));
746    if (!read_last_jobs_list(sfd, hdr.last_jobs_addr)) {
747       goto bail_out;
748    }
749    ok = true;
750 bail_out:
751    if (sfd >= 0) {
752       close(sfd);
753    }
754    if (!ok) {
755       unlink(fname);
756     }
757    free_pool_memory(fname);
758 }
759
760 /*
761  * Write the state file
762  */
763 static pthread_mutex_t state_mutex = PTHREAD_MUTEX_INITIALIZER;
764
765 void write_state_file(char *dir, const char *progname, int port)
766 {
767    int sfd;
768    bool ok = false;
769    POOLMEM *fname = get_pool_memory(PM_FNAME);
770
771    P(state_mutex);                    /* Only one job at a time can call here */
772    Mmsg(&fname, "%s/%s.%d.state", dir, progname, port);
773    /* Create new state file */
774    unlink(fname);
775    if ((sfd = open(fname, O_CREAT|O_WRONLY|O_BINARY, 0640)) < 0) {
776       berrno be;
777       Dmsg2(000, "Could not create state file. %s ERR=%s\n", fname, be.bstrerror());
778       Emsg2(M_ERROR, 0, _("Could not create state file. %s ERR=%s\n"), fname, be.bstrerror());
779       goto bail_out;
780    }
781    if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
782       berrno be;
783       Dmsg1(000, "Write hdr error: ERR=%s\n", be.bstrerror());
784       goto bail_out;
785    }
786 // Dmsg1(010, "Wrote header of %d bytes\n", sizeof(state_hdr));
787    state_hdr.last_jobs_addr = sizeof(state_hdr);
788    state_hdr.reserved[0] = write_last_jobs_list(sfd, state_hdr.last_jobs_addr);
789 // Dmsg1(010, "write last job end = %d\n", (int)state_hdr.reserved[0]);
790    if (lseek(sfd, 0, SEEK_SET) < 0) {
791       berrno be;
792       Dmsg1(000, "lseek error: ERR=%s\n", be.bstrerror());
793       goto bail_out;
794    }
795    if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
796       berrno be;
797       Pmsg1(000, _("Write final hdr error: ERR=%s\n"), be.bstrerror());
798       goto bail_out;
799    }
800    ok = true;
801 // Dmsg1(010, "rewrote header = %d\n", sizeof(state_hdr));
802 bail_out:
803    if (sfd >= 0) {
804       close(sfd);
805    }
806    if (!ok) {
807       unlink(fname);
808    }
809    V(state_mutex);
810    free_pool_memory(fname);
811 }
812
813
814 /* BSDI does not have this.  This is a *poor* simulation */
815 #ifndef HAVE_STRTOLL
816 long long int
817 strtoll(const char *ptr, char **endptr, int base)
818 {
819    return (long long int)strtod(ptr, endptr);
820 }
821 #endif
822
823 /*
824  * Bacula's implementation of fgets(). The difference is that it handles
825  *   being interrupted by a signal (e.g. a SIGCHLD).
826  */
827 #undef fgetc
828 char *bfgets(char *s, int size, FILE *fd)
829 {
830    char *p = s;
831    int ch;
832    *p = 0;
833    for (int i=0; i < size-1; i++) {
834       do {
835          errno = 0;
836          ch = fgetc(fd);
837       } while (ch == EOF && ferror(fd) && (errno == EINTR || errno == EAGAIN));
838       if (ch == EOF) {
839          if (i == 0) {
840             return NULL;
841          } else {
842             return s;
843          }
844       }
845       *p++ = ch;
846       *p = 0;
847       if (ch == '\r') { /* Support for Mac/Windows file format */
848          ch = fgetc(fd);
849          if (ch != '\n') { /* Mac (\r only) */
850             (void)ungetc(ch, fd); /* Push next character back to fd */
851          }
852          p[-1] = '\n';
853          break;
854       }
855       if (ch == '\n') {
856          break;
857       }
858    }
859    return s;
860 }
861
862 /*
863  * Bacula's implementation of fgets(). The difference is that it handles
864  *   being interrupted by a signal (e.g. a SIGCHLD) and it has a
865  *   different calling sequence which implements input lines of
866  *   up to a million characters.
867  */
868 char *bfgets(POOLMEM *&s, FILE *fd)
869 {
870    int ch;
871    int soft_max;
872    int i = 0;
873
874    s[0] = 0;
875    soft_max = sizeof_pool_memory(s) - 10;
876    for ( ;; ) {
877       do {
878          errno = 0;
879          ch = fgetc(fd);
880       } while (ch == EOF && ferror(fd) && (errno == EINTR || errno == EAGAIN));
881       if (ch == EOF) {
882          if (i == 0) {
883             return NULL;
884          } else {
885             return s;
886          }
887       }
888       if (i > soft_max) {
889          /* Insanity check */
890          if (soft_max > 1000000) {
891             return s;
892          }
893          s = check_pool_memory_size(s, soft_max+10000);
894          soft_max = sizeof_pool_memory(s) - 10;
895       }
896       s[i++] = ch;
897       s[i] = 0;
898       if (ch == '\r') { /* Support for Mac/Windows file format */
899          ch = fgetc(fd);
900          if (ch != '\n') { /* Mac (\r only) */
901             (void)ungetc(ch, fd); /* Push next character back to fd */
902          }
903          s[i-1] = '\n';
904          break;
905       }
906       if (ch == '\n') {
907          break;
908       }
909    }
910    return s;
911 }
912
913 /*
914  * Make a "unique" filename.  It is important that if
915  *   called again with the same "what" that the result
916  *   will be identical. This allows us to use the file
917  *   without saving its name, and re-generate the name
918  *   so that it can be deleted.
919  */
920 void make_unique_filename(POOLMEM **name, int Id, char *what)
921 {
922    Mmsg(name, "%s/%s.%s.%d.tmp", working_directory, my_name, what, Id);
923 }
924
925 char *escape_filename(const char *file_path)
926 {
927    if (file_path == NULL || strpbrk(file_path, "\"\\") == NULL) {
928       return NULL;
929    }
930
931    char *escaped_path = (char *)bmalloc(2 * (strlen(file_path) + 1));
932    char *cur_char = escaped_path;
933
934    while (*file_path) {
935       if (*file_path == '\\' || *file_path == '"') {
936          *cur_char++ = '\\';
937       }
938
939       *cur_char++ = *file_path++;
940    }
941
942    *cur_char = '\0';
943
944    return escaped_path;
945 }
946
947 /*
948  * For the moment preventing suspensions is only
949  *  implemented on Windows.
950  */
951 #ifndef HAVE_WIN32
952 void prevent_os_suspensions()
953 { }
954
955 void allow_os_suspensions()
956 { }
957 #endif
958
959
960 #if HAVE_BACKTRACE && HAVE_GCC
961 /* if some names are not resolved you can try using : addr2line, like this
962  * $ addr2line -e bin/bacula-sd -a 0x43cd11
963  * OR
964  * use the the -rdynamic option in the linker, like this
965  * $ LDFLAGS="-rdynamic" make setup
966  */
967 #include <cxxabi.h>
968 #include <execinfo.h>
969 void stack_trace()
970 {
971    const size_t max_depth = 100;
972    size_t stack_depth;
973    void *stack_addrs[max_depth];
974    char **stack_strings;
975
976    stack_depth = backtrace(stack_addrs, max_depth);
977    stack_strings = backtrace_symbols(stack_addrs, stack_depth);
978
979    for (size_t i = 3; i < stack_depth; i++) {
980       size_t sz = 200; /* just a guess, template names will go much wider */
981       char *function = (char *)actuallymalloc(sz);
982       char *begin = 0, *end = 0;
983       /* find the parentheses and address offset surrounding the mangled name */
984       for (char *j = stack_strings[i]; *j; ++j) {
985          if (*j == '(') {
986             begin = j;
987          } else if (*j == '+') {
988             end = j;
989          }
990       }
991       if (begin && end) {
992          *begin++ = '\0';
993          *end = '\0';
994          /* found our mangled name, now in [begin, end] */
995
996          int status;
997          char *ret = abi::__cxa_demangle(begin, function, &sz, &status);
998          if (ret) {
999             /* return value may be a realloc() of the input */
1000             function = ret;
1001          } else {
1002             /* demangling failed, just pretend it's a C function with no args */
1003             strncpy(function, begin, sz);
1004             strncat(function, "()", sz);
1005             function[sz-1] = '\0';
1006          }
1007          Pmsg2(000, "    %s:%s\n", stack_strings[i], function);
1008
1009       } else {
1010          /* didn't find the mangled name, just print the whole line */
1011          Pmsg1(000, "    %s\n", stack_strings[i]);
1012       }
1013       actuallyfree(function);
1014    }
1015    actuallyfree(stack_strings); /* malloc()ed by backtrace_symbols */
1016 }
1017 #else /* HAVE_BACKTRACE && HAVE_GCC */
1018 void stack_trace() {}
1019 #endif /* HAVE_BACKTRACE && HAVE_GCC */
1020
1021 #ifdef HAVE_SYS_STATVFS_H
1022 #include <sys/statvfs.h>
1023 #else
1024 #define statvfs statfs
1025 #endif
1026 /* statvfs.h defines ST_APPEND, which is also used by Bacula */
1027 #undef ST_APPEND
1028
1029
1030 int fs_get_free_space(const char *path, int64_t *freeval, int64_t *totalval)
1031 {
1032 #ifndef HAVE_WIN32
1033    struct statvfs st;
1034
1035    if (statvfs(path, &st) == 0) {
1036       *freeval = (uint64_t)st.f_bsize * (uint64_t)st.f_bavail;
1037       *totalval = (uint64_t)st.f_blocks * (uint64_t)st.f_frsize;
1038       return 0;
1039    }
1040 #endif
1041    *totalval = *freeval = 0;
1042    return -1;
1043 }
1044
1045 /* This function is used after a fork, the memory manager is not be initialized
1046  * properly, so we must stay simple.
1047  */
1048 void setup_env(char *envp[])
1049 {
1050    if (envp) {
1051 #if defined(HAVE_SETENV)
1052       char *p;
1053       for (int i=0; envp[i] ; i++) {
1054          p = strchr(envp[i], '='); /* HOME=/tmp */
1055          if (p) {
1056             *p=0;                       /* HOME\0tmp\0 */
1057             setenv(envp[i], p+1, true);
1058             *p='=';
1059          }
1060       }
1061 #elif defined(HAVE_PUTENV)
1062       for (int i=0; envp[i] ; i++) {
1063          putenv(envp[i]);
1064       }
1065 #else
1066 #error "putenv() and setenv() are not available on this system"
1067 #endif
1068    }
1069 }
1070
1071 /* Small function to copy a file somewhere else, 
1072  * for debug purpose.
1073  */
1074 int copyfile(const char *src, const char *dst)
1075 {
1076    int     fd_src=-1, fd_dst=-1;
1077    ssize_t len, lenw;
1078    char    buf[4096];
1079    berrno  be;
1080    fd_src = open(src, O_RDONLY);
1081    if (fd_src < 0) {
1082       Dmsg2(0, "Unable to open %s ERR=%s\n", src, be.bstrerror(errno));
1083       goto bail_out;
1084    }
1085    fd_dst = open(dst, O_WRONLY | O_CREAT | O_EXCL, 0600);
1086    if (fd_dst < 0) {
1087       Dmsg2(0, "Unable to open %s ERR=%s\n", dst, be.bstrerror(errno));
1088       goto bail_out;
1089    }
1090
1091    while ((len = read(fd_src, buf, sizeof(buf))) > 0)
1092     {
1093         char *out_ptr = buf;
1094         do {
1095             lenw = write(fd_dst, out_ptr, len);
1096             if (lenw >= 0) {
1097                 len -= lenw;
1098                 out_ptr += lenw;
1099             } else if (errno != EINTR) {
1100                Dmsg3(0, "Unable to write %d bytes in %s. ERR=%s\n", len, dst, be.bstrerror(errno));
1101                goto bail_out;
1102             }
1103         } while (len > 0);
1104     }
1105
1106     if (len == 0) {
1107        close(fd_src);
1108        if (close(fd_dst) < 0) {
1109           Dmsg2(0, "Unable to close %s properly. ERR=%s\n", dst, be.bstrerror(errno));
1110           return -1;
1111        }
1112        /* Success! */
1113        return 0;
1114     }
1115 bail_out:
1116     close(fd_src);
1117     close(fd_dst);
1118     return -1;
1119 }
1120
1121 /* The poll() code is currently disabled */
1122 #ifdef HAVE_POLL
1123
1124 #include <poll.h>
1125 #define NB_EVENT 1
1126
1127 int fd_wait_data(int fd, fd_wait_mode mode, int sec, int msec)
1128 {
1129    int ret;
1130    struct pollfd fds[NB_EVENT]; /* The structure for one event */
1131
1132    fds[0].fd = fd;
1133    fds[0].events = (mode == WAIT_READ) ? POLLIN : POLLOUT;
1134
1135    ret = poll(fds, NB_EVENT, sec * 1000 + msec);
1136
1137    /* Check if poll actually succeed */
1138    switch(ret) {
1139    case 0:                      /* timeout; no event detected */
1140       return 0;
1141
1142    case -1:                     /* report error and abort */
1143       return -1;
1144
1145    default:
1146       if (fds[0].revents & POLLIN || fds[0].revents & POLLOUT) {
1147          return 1;
1148
1149       } else {
1150          return -1;             /* unexpected... */
1151       }
1152    }
1153    return -1;                   /* unexpected... */
1154 }
1155 #else
1156
1157 /* The select() code with a bigger fd_set was tested on Linux, FreeBSD and SunOS */
1158 #if defined(HAVE_LINUX_OS) || defined(HAVE_FREEBSD_OS) || defined(HAVE_SUN_OS) || defined(HAVE_WIN32)
1159  #define SELECT_MAX_FD 7990
1160 #else
1161  #define SELECT_MAX_FD 1023     /* For others, we keep it low */
1162 #endif
1163
1164 int fd_wait_data(int fd, fd_wait_mode mode, int sec, int msec)
1165 {
1166
1167    /* TODO: Allocate the fd_set when fd > SELECT_MAX_FD */
1168    union {
1169       fd_set fdset;
1170       char bfd_buf[1000];
1171    };
1172    struct timeval tv;
1173    int ret;
1174
1175    if (fd > SELECT_MAX_FD) {
1176       Pmsg1(0, "Too many open files for the current system fd=%d\n", fd);
1177       return -1;
1178    }
1179
1180    memset(&bfd_buf, 0, sizeof(bfd_buf)); /* FD_ZERO(&fdset) */
1181    FD_SET((unsigned)fd, &fdset);
1182
1183    tv.tv_sec = sec;
1184    tv.tv_usec = msec * 1000;
1185
1186    if (mode == WAIT_READ) {
1187       ret = select(fd + 1, &fdset, NULL, NULL, &tv);
1188
1189    } else { /* WAIT_WRITE */
1190       ret = select(fd + 1, NULL, &fdset, NULL, &tv);
1191    }
1192
1193    switch (ret) {
1194    case 0:                      /* timeout */
1195       return 0;
1196    case -1:
1197       return -1;                /* error return */
1198    default:
1199       break;
1200    }
1201    return 1;
1202 }
1203 #endif
1204
1205 /* Use SOCK_CLOEXEC option when calling accept(). If not available,
1206  * do it ourself (but with a race condition...)
1207  */
1208 int baccept(int sockfd, struct sockaddr *addr, socklen_t *addrlen)
1209 {
1210    int fd;
1211 #ifdef HAVE_ACCEPT4
1212    fd = accept4(sockfd, addr, addrlen, SOCK_CLOEXEC);
1213 #else
1214    fd = accept(sockfd, addr, addrlen);
1215
1216 # ifdef HAVE_DECL_FD_CLOEXEC
1217    if (fd >= 0) {
1218       int tmp_errno = errno;
1219       if (fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC) < 0) {
1220          berrno be;
1221          Dmsg2(0, "Unable to set the CLOEXEC flag on fd=%d ERR=%s\n", fd, be.bstrerror());
1222       }
1223       errno = tmp_errno;
1224    }
1225
1226 # endif  /* HAVE_DECL_FD_CLOEXEC */
1227 #endif   /* HAVE_ACCEPT4 */
1228    return fd;
1229 }
1230
1231 #undef fopen
1232 FILE *bfopen(const char *path, const char *mode)
1233 {
1234    char options[50];
1235    FILE *fp;
1236
1237    bstrncpy(options, mode, sizeof(options));
1238
1239 #if defined(HAVE_STREAM_CLOEXEC)
1240    bstrncat(options, STREAM_CLOEXEC, sizeof(options));
1241 #endif
1242
1243    fp = fopen(path, options);
1244
1245 #if !defined(HAVE_STREAM_CLOEXEC) && defined(HAVE_DECL_FD_CLOEXEC)
1246    if (fp) {
1247       int fd = fileno(fp);
1248       if (fd >= 0) {
1249          int tmp_errno = errno;
1250          if (fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC) < 0) {
1251             berrno be;
1252             Dmsg2(0, "Unable to set the CLOEXEC flag on fd=%d ERR=%s\n", fd, be.bstrerror());
1253          }
1254          errno = tmp_errno;
1255       }
1256    }
1257 #endif
1258    return fp;
1259 }
1260
1261
1262 #ifdef TEST_PROGRAM
1263 /* The main idea of the test is pretty simple, we have a writer and a reader, and
1264  * they wait a little bit to read or send data over the fifo.
1265  * So, for the first packets, the writer will wait, then the reader will wait
1266  * read/write requests should always be fast. Only the time of the fd_wait_data()
1267  * should be long.
1268  */
1269 #include "findlib/namedpipe.h"
1270 #define PIPENAME "/tmp/wait.pipe.%d"
1271
1272 #define NBPACKETS 10
1273 #define BUFSIZE   128*512       /* The pipe size looks to be 65K */
1274
1275 typedef struct {
1276    int       nb;
1277    pthread_t writer;
1278    pthread_t reader;
1279 } job;
1280
1281 pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
1282 pthread_mutex_t cond_mutex = PTHREAD_MUTEX_INITIALIZER;
1283 int nb_ready=0;
1284
1285 void *th1(void *a)
1286 {
1287    NamedPipe p;
1288    int fd, r;
1289    btime_t s, e;
1290    ssize_t nb;
1291    char buf[BUFSIZE];
1292    job *j = (job *)a;
1293
1294    namedpipe_init(&p);
1295    bsnprintf(buf, sizeof(buf), PIPENAME, j->nb);
1296    if (namedpipe_create(&p, buf, 0600) < 0) {
1297       berrno be;
1298       Dmsg2(0, "R: Unable to create the fifo %s. ERR=%s\n", buf, be.bstrerror());
1299       namedpipe_free(&p);
1300       exit(2);
1301    }
1302    fd = namedpipe_open(&p, buf, O_RDONLY);
1303    if (fd < 0) {
1304       berrno be;
1305       Dmsg2(0, "R: Unable to open the fifo %s. ERR=%s\n", buf, be.bstrerror());
1306       return NULL;
1307    }
1308    P(cond_mutex);
1309    nb_ready++;
1310    pthread_cond_wait(&cond, &cond_mutex);
1311    V(cond_mutex);
1312    for (int i = 0; i < NBPACKETS; i++) {
1313       if (i < (NBPACKETS/2)) {
1314          bmicrosleep(5, 0);
1315       }
1316       s = get_current_btime();
1317       r = fd_wait_data(fd, WAIT_READ, 10, 0);
1318       if (r > 0) {
1319          e = get_current_btime();
1320          Dmsg2(0, "Wait to read pkt %d %lldms\n",i, (int64_t) (e - s));
1321
1322          if (i <= NBPACKETS/2) {
1323             ASSERT2((e-s) < 10000, "In the 1st phase, we are blocking the process");
1324          } else {
1325             ASSERT2((e-s) > 10000, "In the 2nd phase, the writer is slowing down things");
1326          }
1327
1328          s = get_current_btime();
1329          nb = read(fd, buf, sizeof(buf));
1330          e = get_current_btime();
1331          Dmsg3(0, "Read pkt %d %d bytes in %lldms\n",i, (int)nb, (int64_t) (e - s));
1332          ASSERT2((e-s) < 10000, "The read operation should be FAST");
1333       }
1334    }
1335    namedpipe_free(&p);
1336    return NULL;
1337 }
1338
1339 void *th2(void *a)
1340 {
1341    NamedPipe p;
1342    btime_t s, e;
1343    job *j = (job *)a;
1344    char buf[BUFSIZE];
1345    int fd;
1346    ssize_t nb;
1347
1348    bsnprintf(buf, sizeof(buf), PIPENAME, j->nb);
1349    namedpipe_init(&p);
1350    if (namedpipe_create(&p, buf, 0600) < 0) {
1351       berrno be;
1352       Dmsg2(0, "W: Unable to create the fifo %s. ERR=%s\n", buf, be.bstrerror());
1353       namedpipe_free(&p);
1354       exit(2);
1355    }
1356
1357    fd = namedpipe_open(&p, buf, O_WRONLY);
1358    if (fd < 0) {
1359       berrno be;
1360       Dmsg2(0, "W: Unable to open the fifo %s. ERR=%s\n", buf, be.bstrerror());
1361       namedpipe_free(&p);
1362       exit(2);
1363    }
1364
1365    P(cond_mutex);
1366    nb_ready++;
1367    pthread_cond_wait(&cond, &cond_mutex);
1368    V(cond_mutex);
1369
1370    unlink(buf);
1371
1372    for (int i=0; i < NBPACKETS; i++) {
1373       if (i > (NBPACKETS/2)) {
1374          bmicrosleep(5, 0);
1375       }
1376       s = get_current_btime();
1377       if (fd_wait_data(fd, WAIT_WRITE, 10, 0) > 0) {
1378          e = get_current_btime();
1379          Dmsg2(0, "Wait to write pkt %d %lldms\n",i, (int64_t) (e - s));
1380
1381          if (i == 0 || i > NBPACKETS/2) { /* The first packet doesn't count */
1382             ASSERT2((e-s) < 100000, "In the 2nd phase, it's fast to send, we are the blocker");
1383          } else {
1384             ASSERT2((e-s) > 100000, "In the 1st phase, we wait for the reader");
1385          }
1386
1387          s = get_current_btime();
1388          nb = write(fd, buf, sizeof(buf));
1389          e = get_current_btime();
1390          Dmsg3(0, "Wrote pkt %d %d bytes in %lldms\n", i, (int)nb, (int64_t) (e - s));
1391          ASSERT2((e-s) < 100000, "The write operation should never block");
1392       }
1393    }
1394    namedpipe_free(&p);
1395    return NULL;
1396 }
1397
1398 int main(int argc, char **argv)
1399 {
1400    job pthread_list[10000];
1401    int j = (argc >= 2) ? atoi(argv[1]) : 1;
1402    int maxfd = (argc == 3) ? atoi(argv[2]) : 0;
1403
1404    j = MIN(10000, j);
1405    
1406    lmgr_init_thread();
1407    set_debug_flags((char *)"h");
1408
1409    for (int i=3; i < maxfd; i++) {
1410       open("/dev/null", O_RDONLY);
1411    }
1412
1413    for (int i=0; i < j; i++) {
1414       pthread_list[i].nb=i;
1415       pthread_create(&pthread_list[i].writer, NULL, th2, &pthread_list[i]);
1416       pthread_create(&pthread_list[i].reader, NULL, th1, &pthread_list[i]);
1417    }
1418
1419    while (nb_ready < j*2) {
1420       bmicrosleep(1, 0);
1421    }
1422
1423    Dmsg0(0, "All threads are started\n");
1424    P(cond_mutex);
1425    pthread_cond_broadcast(&cond);
1426    V(cond_mutex);
1427
1428    for (int i=0; i < j; i++) {
1429       pthread_join(pthread_list[i].writer, NULL);
1430       pthread_join(pthread_list[i].reader, NULL);
1431    }
1432
1433    for (int i=3; i < maxfd; i++) {
1434       close(i);
1435    }
1436    return 0;
1437 }
1438 #endif