]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/bsys.c
54add7bb3ffabdd5ebc4e43cdb82458236accfa6
[bacula/bacula] / bacula / src / lib / bsys.c
1 /*
2    Bacula(R) - The Network Backup Solution
3
4    Copyright (C) 2000-2016 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 static int pid_fd = -1;
537 #endif
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)
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)
618 {
619    int len;
620    int oldpid;
621    char pidbuf[20];
622
623    /* Open the pidfile for writing */
624    if ((pid_fd = open(fname, O_CREAT|O_RDWR, 0640)) >= 0) {
625       if (fcntl_lock(pid_fd, F_WRLCK) == -1) {
626          berrno be;
627          /* already locked by someone else, try to read the pid */
628          if (read(pid_fd, &pidbuf, sizeof(pidbuf)) > 0 &&
629              sscanf(pidbuf, "%d", &oldpid) == 1) {
630             Mmsg(errmsg, _("%s is already running. pid=%d\nCheck 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(pid_fd);
636          pid_fd=-1;
637          return 0;
638       }
639       /* write the pid */
640       len = sprintf(pidbuf, "%d\n", (int)getpid());
641       write(pid_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) == 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 #include <cxxabi.h>
962 #include <execinfo.h>
963 void stack_trace()
964 {
965    const size_t max_depth = 100;
966    size_t stack_depth;
967    void *stack_addrs[max_depth];
968    char **stack_strings;
969
970    stack_depth = backtrace(stack_addrs, max_depth);
971    stack_strings = backtrace_symbols(stack_addrs, stack_depth);
972
973    for (size_t i = 3; i < stack_depth; i++) {
974       size_t sz = 200; /* just a guess, template names will go much wider */
975       char *function = (char *)actuallymalloc(sz);
976       char *begin = 0, *end = 0;
977       /* find the parentheses and address offset surrounding the mangled name */
978       for (char *j = stack_strings[i]; *j; ++j) {
979          if (*j == '(') {
980             begin = j;
981          } else if (*j == '+') {
982             end = j;
983          }
984       }
985       if (begin && end) {
986          *begin++ = '\0';
987          *end = '\0';
988          /* found our mangled name, now in [begin, end] */
989
990          int status;
991          char *ret = abi::__cxa_demangle(begin, function, &sz, &status);
992          if (ret) {
993             /* return value may be a realloc() of the input */
994             function = ret;
995          } else {
996             /* demangling failed, just pretend it's a C function with no args */
997             strncpy(function, begin, sz);
998             strncat(function, "()", sz);
999             function[sz-1] = '\0';
1000          }
1001          Pmsg2(000, "    %s:%s\n", stack_strings[i], function);
1002
1003       } else {
1004          /* didn't find the mangled name, just print the whole line */
1005          Pmsg1(000, "    %s\n", stack_strings[i]);
1006       }
1007       actuallyfree(function);
1008    }
1009    actuallyfree(stack_strings); /* malloc()ed by backtrace_symbols */
1010 }
1011 #else /* HAVE_BACKTRACE && HAVE_GCC */
1012 void stack_trace() {}
1013 #endif /* HAVE_BACKTRACE && HAVE_GCC */
1014
1015 #ifdef HAVE_SYS_STATVFS_H
1016 #include <sys/statvfs.h>
1017 #else
1018 #define statvfs statfs
1019 #endif
1020 /* statvfs.h defines ST_APPEND, which is also used by Bacula */
1021 #undef ST_APPEND
1022
1023
1024 int fs_get_free_space(const char *path, int64_t *freeval, int64_t *totalval)
1025 {
1026 #ifndef HAVE_WIN32
1027    struct statvfs st;
1028
1029    if (statvfs(path, &st) == 0) {
1030       *freeval = (uint64_t)st.f_bsize * (uint64_t)st.f_bavail;
1031       *totalval = (uint64_t)st.f_blocks * (uint64_t)st.f_frsize;
1032       return 0;
1033    }
1034 #endif
1035    *totalval = *freeval = 0;
1036    return -1;
1037 }
1038
1039 void setup_env(char *envp[])
1040 {
1041    if (envp) {
1042 #if defined(HAVE_SETENV)
1043       char *p;
1044       POOLMEM *tmp = get_pool_memory(PM_FNAME);
1045       for (int i=0; envp[i] ; i++) {
1046          pm_strcpy(tmp, envp[i]);
1047          p = strchr(tmp, '='); /* HOME=/tmp */
1048          if (p) {
1049             *p=0;                       /* HOME\0tmp\0 */
1050             setenv(tmp, p+1, true);
1051          }
1052       }
1053       free_pool_memory(tmp);
1054 #elif defined(HAVE_PUTENV)
1055       for (int i=0; envp[i] ; i++) {
1056          putenv(envp[i]);
1057       }
1058 #else
1059 #error "putenv() and setenv() are not available on this system"
1060 #endif
1061    }
1062 }
1063
1064 /* Small function to copy a file somewhere else, 
1065  * for debug purpose.
1066  */
1067 int copyfile(const char *src, const char *dst)
1068 {
1069    int     fd_src=-1, fd_dst=-1;
1070    ssize_t len, lenw;
1071    char    buf[4096];
1072    berrno  be;
1073    fd_src = open(src, O_RDONLY);
1074    if (fd_src < 0) {
1075       Dmsg2(0, "Unable to open %s ERR=%s\n", src, be.bstrerror(errno));
1076       goto bail_out;
1077    }
1078    fd_dst = open(dst, O_WRONLY | O_CREAT | O_EXCL, 0600);
1079    if (fd_dst < 0) {
1080       Dmsg2(0, "Unable to open %s ERR=%s\n", dst, be.bstrerror(errno));
1081       goto bail_out;
1082    }
1083
1084    while ((len = read(fd_src, buf, sizeof(buf))) > 0)
1085     {
1086         char *out_ptr = buf;
1087         do {
1088             lenw = write(fd_dst, out_ptr, len);
1089             if (lenw >= 0) {
1090                 len -= lenw;
1091                 out_ptr += lenw;
1092             } else if (errno != EINTR) {
1093                Dmsg3(0, "Unable to write %d bytes in %s. ERR=%s\n", len, dst, be.bstrerror(errno));
1094                goto bail_out;
1095             }
1096         } while (len > 0);
1097     }
1098
1099     if (len == 0) {
1100        close(fd_src);
1101        if (close(fd_dst) < 0) {
1102           Dmsg2(0, "Unable to close %s properly. ERR=%s\n", dst, be.bstrerror(errno));
1103           return -1;
1104        }
1105        /* Success! */
1106        return 0;
1107     }
1108 bail_out:
1109     close(fd_src);
1110     close(fd_dst);
1111     return -1;
1112 }