]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/bsys.c
916357493b21ca7517c9c8caf7b116a4621af3a5
[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
1033 /* For Windows must have statvfs */
1034 #if defined(HAVE_WIN32)
1035    #if !defined(HAVE_SYS_STATVFS_H)
1036       *totalval = *freeval = 0;
1037       return -1;
1038    #endif
1039 #endif
1040
1041    struct statvfs st;
1042
1043    if (statvfs(path, &st) == 0) {
1044       *freeval  = (uint64_t)st.f_bavail * (uint64_t)st.f_frsize;
1045       *totalval = (uint64_t)st.f_blocks * (uint64_t)st.f_frsize;
1046       return 0;
1047    }
1048
1049    *totalval = *freeval = 0;
1050    return -1;
1051 }
1052
1053 /* This function is used after a fork, the memory manager is not be initialized
1054  * properly, so we must stay simple.
1055  */
1056 void setup_env(char *envp[])
1057 {
1058    if (envp) {
1059 #if defined(HAVE_SETENV)
1060       char *p;
1061       for (int i=0; envp[i] ; i++) {
1062          p = strchr(envp[i], '='); /* HOME=/tmp */
1063          if (p) {
1064             *p=0;                       /* HOME\0tmp\0 */
1065             setenv(envp[i], p+1, true);
1066             *p='=';
1067          }
1068       }
1069 #elif defined(HAVE_PUTENV)
1070       for (int i=0; envp[i] ; i++) {
1071          putenv(envp[i]);
1072       }
1073 #else
1074 #error "putenv() and setenv() are not available on this system"
1075 #endif
1076    }
1077 }
1078
1079 /* Small function to copy a file somewhere else, 
1080  * for debug purpose.
1081  */
1082 int copyfile(const char *src, const char *dst)
1083 {
1084    int     fd_src=-1, fd_dst=-1;
1085    ssize_t len, lenw;
1086    char    buf[4096];
1087    berrno  be;
1088    fd_src = open(src, O_RDONLY);
1089    if (fd_src < 0) {
1090       Dmsg2(0, "Unable to open %s ERR=%s\n", src, be.bstrerror(errno));
1091       goto bail_out;
1092    }
1093    fd_dst = open(dst, O_WRONLY | O_CREAT | O_EXCL, 0600);
1094    if (fd_dst < 0) {
1095       Dmsg2(0, "Unable to open %s ERR=%s\n", dst, be.bstrerror(errno));
1096       goto bail_out;
1097    }
1098
1099    while ((len = read(fd_src, buf, sizeof(buf))) > 0)
1100     {
1101         char *out_ptr = buf;
1102         do {
1103             lenw = write(fd_dst, out_ptr, len);
1104             if (lenw >= 0) {
1105                 len -= lenw;
1106                 out_ptr += lenw;
1107             } else if (errno != EINTR) {
1108                Dmsg3(0, "Unable to write %d bytes in %s. ERR=%s\n", len, dst, be.bstrerror(errno));
1109                goto bail_out;
1110             }
1111         } while (len > 0);
1112     }
1113
1114     if (len == 0) {
1115        close(fd_src);
1116        if (close(fd_dst) < 0) {
1117           Dmsg2(0, "Unable to close %s properly. ERR=%s\n", dst, be.bstrerror(errno));
1118           return -1;
1119        }
1120        /* Success! */
1121        return 0;
1122     }
1123 bail_out:
1124     close(fd_src);
1125     close(fd_dst);
1126     return -1;
1127 }
1128
1129 /* The poll() code is currently disabled */
1130 #ifdef HAVE_POLL
1131
1132 #include <poll.h>
1133 #define NB_EVENT 1
1134
1135 int fd_wait_data(int fd, fd_wait_mode mode, int sec, int msec)
1136 {
1137    int ret;
1138    struct pollfd fds[NB_EVENT]; /* The structure for one event */
1139
1140    fds[0].fd = fd;
1141    fds[0].events = (mode == WAIT_READ) ? POLLIN : POLLOUT;
1142
1143    ret = poll(fds, NB_EVENT, sec * 1000 + msec);
1144
1145    /* Check if poll actually succeed */
1146    switch(ret) {
1147    case 0:                      /* timeout; no event detected */
1148       return 0;
1149
1150    case -1:                     /* report error and abort */
1151       return -1;
1152
1153    default:
1154       if (fds[0].revents & POLLIN || fds[0].revents & POLLOUT) {
1155          return 1;
1156
1157       } else {
1158          return -1;             /* unexpected... */
1159       }
1160    }
1161    return -1;                   /* unexpected... */
1162 }
1163 #else
1164
1165 /* The select() code with a bigger fd_set was tested on Linux, FreeBSD and SunOS */
1166 #if defined(HAVE_LINUX_OS) || defined(HAVE_FREEBSD_OS) || defined(HAVE_SUN_OS) || defined(HAVE_WIN32)
1167  #define SELECT_MAX_FD 7990
1168 #else
1169  #define SELECT_MAX_FD 1023     /* For others, we keep it low */
1170 #endif
1171
1172 int fd_wait_data(int fd, fd_wait_mode mode, int sec, int msec)
1173 {
1174
1175    /* TODO: Allocate the fd_set when fd > SELECT_MAX_FD */
1176    union {
1177       fd_set fdset;
1178       char bfd_buf[1000];
1179    };
1180    struct timeval tv;
1181    int ret;
1182
1183    if (fd > SELECT_MAX_FD) {
1184       Pmsg1(0, "Too many open files for the current system fd=%d\n", fd);
1185       return -1;
1186    }
1187
1188    memset(&bfd_buf, 0, sizeof(bfd_buf)); /* FD_ZERO(&fdset) */
1189    FD_SET((unsigned)fd, &fdset);
1190
1191    tv.tv_sec = sec;
1192    tv.tv_usec = msec * 1000;
1193
1194    if (mode == WAIT_READ) {
1195       ret = select(fd + 1, &fdset, NULL, NULL, &tv);
1196
1197    } else { /* WAIT_WRITE */
1198       ret = select(fd + 1, NULL, &fdset, NULL, &tv);
1199    }
1200
1201    switch (ret) {
1202    case 0:                      /* timeout */
1203       return 0;
1204    case -1:
1205       return -1;                /* error return */
1206    default:
1207       break;
1208    }
1209    return 1;
1210 }
1211 #endif
1212
1213 /* Use SOCK_CLOEXEC option when calling accept(). If not available,
1214  * do it ourself (but with a race condition...)
1215  */
1216 int baccept(int sockfd, struct sockaddr *addr, socklen_t *addrlen)
1217 {
1218    int fd;
1219 #ifdef HAVE_ACCEPT4
1220    fd = accept4(sockfd, addr, addrlen, SOCK_CLOEXEC);
1221 #else
1222    fd = accept(sockfd, addr, addrlen);
1223
1224 # ifdef HAVE_DECL_FD_CLOEXEC
1225    if (fd >= 0) {
1226       int tmp_errno = errno;
1227       if (fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC) < 0) {
1228          berrno be;
1229          Dmsg2(0, "Unable to set the CLOEXEC flag on fd=%d ERR=%s\n", fd, be.bstrerror());
1230       }
1231       errno = tmp_errno;
1232    }
1233
1234 # endif  /* HAVE_DECL_FD_CLOEXEC */
1235 #endif   /* HAVE_ACCEPT4 */
1236    return fd;
1237 }
1238
1239 #undef fopen
1240 FILE *bfopen(const char *path, const char *mode)
1241 {
1242    char options[50];
1243    FILE *fp;
1244
1245    bstrncpy(options, mode, sizeof(options));
1246
1247 #if defined(HAVE_STREAM_CLOEXEC)
1248    bstrncat(options, STREAM_CLOEXEC, sizeof(options));
1249 #endif
1250
1251    fp = fopen(path, options);
1252
1253 #if !defined(HAVE_STREAM_CLOEXEC) && defined(HAVE_DECL_FD_CLOEXEC)
1254    if (fp) {
1255       int fd = fileno(fp);
1256       if (fd >= 0) {
1257          int tmp_errno = errno;
1258          if (fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC) < 0) {
1259             berrno be;
1260             Dmsg2(0, "Unable to set the CLOEXEC flag on fd=%d ERR=%s\n", fd, be.bstrerror());
1261          }
1262          errno = tmp_errno;
1263       }
1264    }
1265 #endif
1266    return fp;
1267 }
1268
1269
1270 #ifdef TEST_PROGRAM
1271 /* The main idea of the test is pretty simple, we have a writer and a reader, and
1272  * they wait a little bit to read or send data over the fifo.
1273  * So, for the first packets, the writer will wait, then the reader will wait
1274  * read/write requests should always be fast. Only the time of the fd_wait_data()
1275  * should be long.
1276  */
1277 #include "findlib/namedpipe.h"
1278 #define PIPENAME "/tmp/wait.pipe.%d"
1279
1280 #define NBPACKETS 10
1281 #define BUFSIZE   128*512       /* The pipe size looks to be 65K */
1282
1283 typedef struct {
1284    int       nb;
1285    pthread_t writer;
1286    pthread_t reader;
1287 } job;
1288
1289 pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
1290 pthread_mutex_t cond_mutex = PTHREAD_MUTEX_INITIALIZER;
1291 int nb_ready=0;
1292
1293 void *th1(void *a)
1294 {
1295    NamedPipe p;
1296    int fd, r;
1297    btime_t s, e;
1298    ssize_t nb;
1299    char buf[BUFSIZE];
1300    job *j = (job *)a;
1301
1302    namedpipe_init(&p);
1303    bsnprintf(buf, sizeof(buf), PIPENAME, j->nb);
1304    if (namedpipe_create(&p, buf, 0600) < 0) {
1305       berrno be;
1306       Dmsg2(0, "R: Unable to create the fifo %s. ERR=%s\n", buf, be.bstrerror());
1307       namedpipe_free(&p);
1308       exit(2);
1309    }
1310    fd = namedpipe_open(&p, buf, O_RDONLY);
1311    if (fd < 0) {
1312       berrno be;
1313       Dmsg2(0, "R: Unable to open the fifo %s. ERR=%s\n", buf, be.bstrerror());
1314       return NULL;
1315    }
1316    P(cond_mutex);
1317    nb_ready++;
1318    pthread_cond_wait(&cond, &cond_mutex);
1319    V(cond_mutex);
1320    for (int i = 0; i < NBPACKETS; i++) {
1321       if (i < (NBPACKETS/2)) {
1322          bmicrosleep(5, 0);
1323       }
1324       s = get_current_btime();
1325       r = fd_wait_data(fd, WAIT_READ, 10, 0);
1326       if (r > 0) {
1327          e = get_current_btime();
1328          Dmsg2(0, "Wait to read pkt %d %lldms\n",i, (int64_t) (e - s));
1329
1330          if (i <= NBPACKETS/2) {
1331             ASSERT2((e-s) < 10000, "In the 1st phase, we are blocking the process");
1332          } else {
1333             ASSERT2((e-s) > 10000, "In the 2nd phase, the writer is slowing down things");
1334          }
1335
1336          s = get_current_btime();
1337          nb = read(fd, buf, sizeof(buf));
1338          e = get_current_btime();
1339          Dmsg3(0, "Read pkt %d %d bytes in %lldms\n",i, (int)nb, (int64_t) (e - s));
1340          ASSERT2((e-s) < 10000, "The read operation should be FAST");
1341       }
1342    }
1343    namedpipe_free(&p);
1344    return NULL;
1345 }
1346
1347 void *th2(void *a)
1348 {
1349    NamedPipe p;
1350    btime_t s, e;
1351    job *j = (job *)a;
1352    char buf[BUFSIZE];
1353    int fd;
1354    ssize_t nb;
1355
1356    bsnprintf(buf, sizeof(buf), PIPENAME, j->nb);
1357    namedpipe_init(&p);
1358    if (namedpipe_create(&p, buf, 0600) < 0) {
1359       berrno be;
1360       Dmsg2(0, "W: Unable to create the fifo %s. ERR=%s\n", buf, be.bstrerror());
1361       namedpipe_free(&p);
1362       exit(2);
1363    }
1364
1365    fd = namedpipe_open(&p, buf, O_WRONLY);
1366    if (fd < 0) {
1367       berrno be;
1368       Dmsg2(0, "W: Unable to open the fifo %s. ERR=%s\n", buf, be.bstrerror());
1369       namedpipe_free(&p);
1370       exit(2);
1371    }
1372
1373    P(cond_mutex);
1374    nb_ready++;
1375    pthread_cond_wait(&cond, &cond_mutex);
1376    V(cond_mutex);
1377
1378    unlink(buf);
1379
1380    for (int i=0; i < NBPACKETS; i++) {
1381       if (i > (NBPACKETS/2)) {
1382          bmicrosleep(5, 0);
1383       }
1384       s = get_current_btime();
1385       if (fd_wait_data(fd, WAIT_WRITE, 10, 0) > 0) {
1386          e = get_current_btime();
1387          Dmsg2(0, "Wait to write pkt %d %lldms\n",i, (int64_t) (e - s));
1388
1389          if (i == 0 || i > NBPACKETS/2) { /* The first packet doesn't count */
1390             ASSERT2((e-s) < 100000, "In the 2nd phase, it's fast to send, we are the blocker");
1391          } else {
1392             ASSERT2((e-s) > 100000, "In the 1st phase, we wait for the reader");
1393          }
1394
1395          s = get_current_btime();
1396          nb = write(fd, buf, sizeof(buf));
1397          e = get_current_btime();
1398          Dmsg3(0, "Wrote pkt %d %d bytes in %lldms\n", i, (int)nb, (int64_t) (e - s));
1399          ASSERT2((e-s) < 100000, "The write operation should never block");
1400       }
1401    }
1402    namedpipe_free(&p);
1403    return NULL;
1404 }
1405
1406 int main(int argc, char **argv)
1407 {
1408    job pthread_list[10000];
1409    int j = (argc >= 2) ? atoi(argv[1]) : 1;
1410    int maxfd = (argc == 3) ? atoi(argv[2]) : 0;
1411
1412    j = MIN(10000, j);
1413    
1414    lmgr_init_thread();
1415    set_debug_flags((char *)"h");
1416
1417    for (int i=3; i < maxfd; i++) {
1418       open("/dev/null", O_RDONLY);
1419    }
1420
1421    for (int i=0; i < j; i++) {
1422       pthread_list[i].nb=i;
1423       pthread_create(&pthread_list[i].writer, NULL, th2, &pthread_list[i]);
1424       pthread_create(&pthread_list[i].reader, NULL, th1, &pthread_list[i]);
1425    }
1426
1427    while (nb_ready < j*2) {
1428       bmicrosleep(1, 0);
1429    }
1430
1431    Dmsg0(0, "All threads are started\n");
1432    P(cond_mutex);
1433    pthread_cond_broadcast(&cond);
1434    V(cond_mutex);
1435
1436    for (int i=0; i < j; i++) {
1437       pthread_join(pthread_list[i].writer, NULL);
1438       pthread_join(pthread_list[i].reader, NULL);
1439    }
1440
1441    for (int i=3; i < maxfd; i++) {
1442       close(i);
1443    }
1444    return 0;
1445 }
1446 #endif