]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/bsys.c
Backport from BEE
[bacula/bacula] / bacula / src / lib / bsys.c
1 /*
2    Bacula® - The Network Backup Solution
3
4    Copyright (C) 2000-2014 Free Software Foundation Europe e.V.
5
6    The main author of Bacula is Kern Sibbald, with contributions from many
7    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    Bacula® is a registered trademark of Kern Sibbald.
15 */
16 /*
17  * Miscellaneous Bacula memory and thread safe routines
18  *   Generally, these are interfaces to system or standard
19  *   library routines.
20  *
21  *  Bacula utility functions are in util.c
22  *
23  */
24
25 #include "bacula.h"
26 #ifndef HAVE_REGEX_H
27 #include "lib/bregex.h"
28 #else
29 #include <regex.h>
30 #endif
31
32 static pthread_mutex_t timer_mutex = PTHREAD_MUTEX_INITIALIZER;
33 static pthread_cond_t timer = PTHREAD_COND_INITIALIZER;
34
35 /*
36  * Quote a string
37  */
38 POOLMEM *quote_string(POOLMEM *snew, const char *old)
39 {
40    char *n;
41    int i;
42
43    if (!old) {
44       strcpy(snew, "null");
45       return snew;
46    }
47    n = snew;
48    *n++ = '"';
49    for (i=0; old[i]; i++) {
50       switch (old[i]) {
51       case '"':
52          *n++ = '\\';
53          *n++ = '"';
54          break;
55       case '\\':
56          *n++ = '\\';
57          *n++ = '\\';
58          break;
59       default:
60          *n++ = old[i];
61          break;
62       }
63    }
64    *n++ = '"';
65    *n = 0;
66    return snew;
67 }
68
69 /*
70  * Quote a where (list of addresses separated by spaces)
71  */
72 POOLMEM *quote_where(POOLMEM *snew, const char *old)
73 {
74    char *n;
75    int i;
76
77    if (!old) {
78       strcpy(snew, "null");
79       return snew;
80    }
81    n = snew;
82    *n++ = '"';
83    for (i=0; old[i]; i++) {
84       switch (old[i]) {
85       case ' ':
86          *n++ = '"';
87          *n++ = ',';
88          *n++ = '"';
89          break;
90       case '"':
91          *n++ = '\\';
92          *n++ = '"';
93          break;
94       case '\\':
95          *n++ = '\\';
96          *n++ = '\\';
97          break;
98       default:
99          *n++ = old[i];
100          break;
101       }
102    }
103    *n++ = '"';
104    *n = 0;
105    return snew;
106 }
107
108 /*
109  * This routine is a somewhat safer unlink in that it
110  *   allows you to run a regex on the filename before
111  *   excepting it. It also requires the file to be in
112  *   the working directory.
113  */
114 int safer_unlink(const char *pathname, const char *regx)
115 {
116    int rc;
117    regex_t preg1;
118    char prbuf[500];
119    const int nmatch = 30;
120    regmatch_t pmatch[nmatch];
121    int rtn;
122
123    /* Name must start with working directory */
124    if (strncmp(pathname, working_directory, strlen(working_directory)) != 0) {
125       Pmsg1(000, "Safe_unlink excluded: %s\n", pathname);
126       return EROFS;
127    }
128
129    /* Compile regex expression */
130    rc = regcomp(&preg1, regx, REG_EXTENDED);
131    if (rc != 0) {
132       regerror(rc, &preg1, prbuf, sizeof(prbuf));
133       Pmsg2(000,  _("safe_unlink could not compile regex pattern \"%s\" ERR=%s\n"),
134            regx, prbuf);
135       return ENOENT;
136    }
137
138    /* Unlink files that match regexes */
139    if (regexec(&preg1, pathname, nmatch, pmatch,  0) == 0) {
140       Dmsg1(100, "safe_unlink unlinking: %s\n", pathname);
141       rtn = unlink(pathname);
142    } else {
143       Pmsg2(000, "safe_unlink regex failed: regex=%s file=%s\n", regx, pathname);
144       rtn = EROFS;
145    }
146    regfree(&preg1);
147    return rtn;
148 }
149
150 /*
151  * This routine will sleep (sec, microsec).  Note, however, that if a
152  *   signal occurs, it will return early.  It is up to the caller
153  *   to recall this routine if he/she REALLY wants to sleep the
154  *   requested time.
155  */
156 int bmicrosleep(int32_t sec, int32_t usec)
157 {
158    struct timespec timeout;
159    struct timeval tv;
160    struct timezone tz;
161    int stat;
162
163    timeout.tv_sec = sec;
164    timeout.tv_nsec = usec * 1000;
165
166 #ifdef HAVE_NANOSLEEP
167    stat = nanosleep(&timeout, NULL);
168    if (!(stat < 0 && errno == ENOSYS)) {
169       return stat;
170    }
171    /* If we reach here it is because nanosleep is not supported by the OS */
172 #endif
173
174    /* Do it the old way */
175    gettimeofday(&tv, &tz);
176    timeout.tv_nsec += tv.tv_usec * 1000;
177    timeout.tv_sec += tv.tv_sec;
178    while (timeout.tv_nsec >= 1000000000) {
179       timeout.tv_nsec -= 1000000000;
180       timeout.tv_sec++;
181    }
182
183    Dmsg2(200, "pthread_cond_timedwait sec=%d usec=%d\n", sec, usec);
184    /* Note, this unlocks mutex during the sleep */
185    P(timer_mutex);
186    stat = pthread_cond_timedwait(&timer, &timer_mutex, &timeout);
187    if (stat != 0) {
188       berrno be;
189       Dmsg2(200, "pthread_cond_timedwait stat=%d ERR=%s\n", stat,
190          be.bstrerror(stat));
191    }
192    V(timer_mutex);
193    return stat;
194 }
195
196 /*
197  * Guarantee that the string is properly terminated */
198 char *bstrncpy(char *dest, const char *src, int maxlen)
199 {
200    strncpy(dest, src, maxlen-1);
201    dest[maxlen-1] = 0;
202    return dest;
203 }
204
205 /*
206  * Guarantee that the string is properly terminated */
207 char *bstrncpy(char *dest, POOL_MEM &src, int maxlen)
208 {
209    strncpy(dest, src.c_str(), maxlen-1);
210    dest[maxlen-1] = 0;
211    return dest;
212 }
213
214 /*
215  * Note: Here the maxlen is the maximum length permitted
216  *  stored in dest, while on Unix systems, it is the maximum characters
217  *  that may be copied from src.
218  */
219 char *bstrncat(char *dest, const char *src, int maxlen)
220 {
221    int len = strlen(dest);
222    if (len < maxlen-1) {
223       strncpy(dest+len, src, maxlen-len-1);
224    }
225    dest[maxlen-1] = 0;
226    return dest;
227 }
228
229 /*
230  * Note: Here the maxlen is the maximum length permitted
231  *  stored in dest, while on Unix systems, it is the maximum characters
232  *  that may be copied from src.
233  */
234 char *bstrncat(char *dest, POOL_MEM &src, int maxlen)
235 {
236    int len = strlen(dest);
237    if (len < maxlen-1) {
238       strncpy(dest+len, src.c_str(), maxlen-len-1);
239    }
240    dest[maxlen-1] = 0;
241    return dest;
242 }
243
244 /*
245  * Allows one or both pointers to be NULL
246  */
247 bool bstrcmp(const char *s1, const char *s2)
248 {
249    if (s1 == s2) return true;
250    if (s1 == NULL || s2 == NULL) return false;
251    return strcmp(s1, s2) == 0;
252 }
253
254 /*
255  * Allows one or both pointers to be NULL
256  */
257 bool bstrcasecmp(const char *s1, const char *s2)
258 {
259    if (s1 == s2) return true;
260    if (s1 == NULL || s2 == NULL) return false;
261    return strcasecmp(s1, s2) == 0;
262 }
263
264
265 /*
266  * Get character length of UTF-8 string
267  *
268  * Valid UTF-8 codes
269  * U-00000000 - U-0000007F: 0xxxxxxx
270  * U-00000080 - U-000007FF: 110xxxxx 10xxxxxx
271  * U-00000800 - U-0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx
272  * U-00010000 - U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
273  * U-00200000 - U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
274  * U-04000000 - U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
275  */
276 int cstrlen(const char *str)
277 {
278    uint8_t *p = (uint8_t *)str;
279    int len = 0;
280    if (str == NULL) {
281       return 0;
282    }
283    while (*p) {
284       if ((*p & 0xC0) != 0xC0) {
285          p++;
286          len++;
287          continue;
288       }
289       if ((*p & 0xD0) == 0xC0) {
290          p += 2;
291          len++;
292          continue;
293       }
294       if ((*p & 0xF0) == 0xD0) {
295          p += 3;
296          len++;
297          continue;
298       }
299       if ((*p & 0xF8) == 0xF0) {
300          p += 4;
301          len++;
302          continue;
303       }
304       if ((*p & 0xFC) == 0xF8) {
305          p += 5;
306          len++;
307          continue;
308       }
309       if ((*p & 0xFE) == 0xFC) {
310          p += 6;
311          len++;
312          continue;
313       }
314       p++;                      /* Shouln't get here but must advance */
315    }
316    return len;
317 }
318
319
320
321 #ifndef bmalloc
322 void *bmalloc(size_t size)
323 {
324   void *buf;
325
326 #ifdef SMARTALLOC
327   buf = sm_malloc(file, line, size);
328 #else
329   buf = malloc(size);
330 #endif
331   if (buf == NULL) {
332      berrno be;
333      Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.bstrerror());
334   }
335   return buf;
336 }
337 #endif
338
339 void *b_malloc(const char *file, int line, size_t size)
340 {
341   void *buf;
342
343 #ifdef SMARTALLOC
344   buf = sm_malloc(file, line, size);
345 #else
346   buf = malloc(size);
347 #endif
348   if (buf == NULL) {
349      berrno be;
350      e_msg(file, line, M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.bstrerror());
351   }
352   return buf;
353 }
354
355
356 void bfree(void *buf)
357 {
358 #ifdef SMARTALLOC
359   sm_free(__FILE__, __LINE__, buf);
360 #else
361   free(buf);
362 #endif
363 }
364
365 void *brealloc (void *buf, size_t size)
366 {
367 #ifdef SMARTALOC
368    buf = sm_realloc(__FILE__, __LINE__, buf, size);
369 #else
370    buf = realloc(buf, size);
371 #endif
372    if (buf == NULL) {
373       berrno be;
374       Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.bstrerror());
375    }
376    return buf;
377 }
378
379
380 void *bcalloc(size_t size1, size_t size2)
381 {
382   void *buf;
383
384    buf = calloc(size1, size2);
385    if (buf == NULL) {
386       berrno be;
387       Emsg1(M_ABORT, 0, _("Out of memory: ERR=%s\n"), be.bstrerror());
388    }
389    return buf;
390 }
391
392 /* Code now in src/lib/bsnprintf.c */
393 #ifndef USE_BSNPRINTF
394
395 #define BIG_BUF 5000
396 /*
397  * Implement snprintf
398  */
399 int bsnprintf(char *str, int32_t size, const char *fmt,  ...)
400 {
401    va_list   arg_ptr;
402    int len;
403
404    va_start(arg_ptr, fmt);
405    len = bvsnprintf(str, size, fmt, arg_ptr);
406    va_end(arg_ptr);
407    return len;
408 }
409
410 /*
411  * Implement vsnprintf()
412  */
413 int bvsnprintf(char *str, int32_t size, const char  *format, va_list ap)
414 {
415 #ifdef HAVE_VSNPRINTF
416    int len;
417    len = vsnprintf(str, size, format, ap);
418    str[size-1] = 0;
419    return len;
420
421 #else
422
423    int len, buflen;
424    char *buf;
425    buflen = size > BIG_BUF ? size : BIG_BUF;
426    buf = get_memory(buflen);
427    len = vsprintf(buf, format, ap);
428    if (len >= buflen) {
429       Emsg0(M_ABORT, 0, _("Buffer overflow.\n"));
430    }
431    memcpy(str, buf, len);
432    str[len] = 0;                /* len excludes the null */
433    free_memory(buf);
434    return len;
435 #endif
436 }
437 #endif /* USE_BSNPRINTF */
438
439 #ifndef HAVE_LOCALTIME_R
440
441 struct tm *localtime_r(const time_t *timep, struct tm *tm)
442 {
443     static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
444     struct tm *ltm,
445
446     P(mutex);
447     ltm = localtime(timep);
448     if (ltm) {
449        memcpy(tm, ltm, sizeof(struct tm));
450     }
451     V(mutex);
452     return ltm ? tm : NULL;
453 }
454 #endif /* HAVE_LOCALTIME_R */
455
456 #ifndef HAVE_READDIR_R
457 #ifndef HAVE_WIN32
458 #include <dirent.h>
459
460 int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
461 {
462     static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
463     struct dirent *ndir;
464     int stat;
465
466     P(mutex);
467     errno = 0;
468     ndir = readdir(dirp);
469     stat = errno;
470     if (ndir) {
471        memcpy(entry, ndir, sizeof(struct dirent));
472        strcpy(entry->d_name, ndir->d_name);
473        *result = entry;
474     } else {
475        *result = NULL;
476     }
477     V(mutex);
478     return stat;
479
480 }
481 #endif
482 #endif /* HAVE_READDIR_R */
483
484
485 int b_strerror(int errnum, char *buf, size_t bufsiz)
486 {
487     static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
488     int stat = 0;
489     const char *msg;
490
491     P(mutex);
492
493     msg = strerror(errnum);
494     if (!msg) {
495        msg = _("Bad errno");
496        stat = -1;
497     }
498     bstrncpy(buf, msg, bufsiz);
499     V(mutex);
500     return stat;
501 }
502
503 #ifdef DEBUG_MEMSET
504 /* These routines are not normally turned on */
505 #undef memset
506 void b_memset(const char *file, int line, void *mem, int val, size_t num)
507 {
508    /* Testing for 2000 byte zero at beginning of Volume block */
509    if (num > 1900 && num < 3000) {
510       Pmsg3(000, _("Memset for %d bytes at %s:%d\n"), (int)num, file, line);
511    }
512    memset(mem, val, num);
513 }
514 #endif
515
516 #if !defined(HAVE_WIN32)
517 static int del_pid_file_ok = FALSE;
518 #endif
519
520 /*
521  * Create a standard "Unix" pid file.
522  */
523 void create_pid_file(char *dir, const char *progname, int port)
524 {
525 #if !defined(HAVE_WIN32)
526    int pidfd, len;
527    int oldpid;
528    char  pidbuf[20];
529    POOLMEM *fname = get_pool_memory(PM_FNAME);
530    struct stat statp;
531
532    Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
533    if (stat(fname, &statp) == 0) {
534       /* File exists, see what we have */
535       *pidbuf = 0;
536       if ((pidfd = open(fname, O_RDONLY|O_BINARY, 0)) < 0 ||
537            read(pidfd, &pidbuf, sizeof(pidbuf)) < 0 ||
538            sscanf(pidbuf, "%d", &oldpid) != 1) {
539          berrno be;
540          Emsg2(M_ERROR_TERM, 0, _("Cannot open pid file. %s ERR=%s\n"), fname,
541                be.bstrerror());
542       }
543       /* Some OSes (IRIX) don't bother to clean out the old pid files after a crash, and
544        * since they use a deterministic algorithm for assigning PIDs, we can have
545        * pid conflicts with the old PID file after a reboot.
546        * The intent the following code is to check if the oldpid read from the pid
547        * file is the same as the currently executing process's pid,
548        * and if oldpid == getpid(), skip the attempt to
549        * kill(oldpid,0), since the attempt is guaranteed to succeed,
550        * but the success won't actually mean that there is an
551        * another Bacula process already running.
552        * For more details see bug #797.
553        */
554        if ((oldpid != (int)getpid()) && (kill(oldpid, 0) != -1 || errno != ESRCH)) {
555          Emsg3(M_ERROR_TERM, 0, _("%s is already running. pid=%d\nCheck file %s\n"),
556                progname, oldpid, fname);
557       }
558       /* He is not alive, so take over file ownership */
559       unlink(fname);                  /* remove stale pid file */
560    }
561    /* Create new pid file */
562    if ((pidfd = open(fname, O_CREAT|O_TRUNC|O_WRONLY|O_BINARY, 0640)) >= 0) {
563       len = sprintf(pidbuf, "%d\n", (int)getpid());
564       write(pidfd, pidbuf, len);
565       close(pidfd);
566       del_pid_file_ok = TRUE;         /* we created it so we can delete it */
567    } else {
568       berrno be;
569       Emsg2(M_ERROR_TERM, 0, _("Could not open pid file. %s ERR=%s\n"), fname,
570             be.bstrerror());
571    }
572    free_pool_memory(fname);
573 #endif
574 }
575
576
577 /*
578  * Delete the pid file if we created it
579  */
580 int delete_pid_file(char *dir, const char *progname, int port)
581 {
582 #if !defined(HAVE_WIN32)
583    POOLMEM *fname = get_pool_memory(PM_FNAME);
584
585    if (!del_pid_file_ok) {
586       free_pool_memory(fname);
587       return 0;
588    }
589    del_pid_file_ok = FALSE;
590    Mmsg(&fname, "%s/%s.%d.pid", dir, progname, port);
591    unlink(fname);
592    free_pool_memory(fname);
593 #endif
594    return 1;
595 }
596
597 struct s_state_hdr {
598    char id[14];
599    int32_t version;
600    uint64_t last_jobs_addr;
601    uint64_t reserved[20];
602 };
603
604 static struct s_state_hdr state_hdr = {
605    "Bacula State\n",
606    4,
607    0
608 };
609
610 /*
611  * Open and read the state file for the daemon
612  */
613 void read_state_file(char *dir, const char *progname, int port)
614 {
615    int sfd;
616    ssize_t stat;
617    bool ok = false;
618    POOLMEM *fname = get_pool_memory(PM_FNAME);
619    struct s_state_hdr hdr;
620    int hdr_size = sizeof(hdr);
621
622    Mmsg(&fname, "%s/%s.%d.state", dir, progname, port);
623    /* If file exists, see what we have */
624 // Dmsg1(10, "O_BINARY=%d\n", O_BINARY);
625    if ((sfd = open(fname, O_RDONLY|O_BINARY)) < 0) {
626       berrno be;
627       Dmsg3(010, "Could not open state file. sfd=%d size=%d: ERR=%s\n",
628             sfd, (int)sizeof(hdr), be.bstrerror());
629       goto bail_out;
630    }
631    if ((stat=read(sfd, &hdr, hdr_size)) != hdr_size) {
632       berrno be;
633       Dmsg4(010, "Could not read state file. sfd=%d stat=%d size=%d: ERR=%s\n",
634                     sfd, (int)stat, hdr_size, be.bstrerror());
635       goto bail_out;
636    }
637    if (hdr.version != state_hdr.version) {
638       Dmsg2(010, "Bad hdr version. Wanted %d got %d\n",
639          state_hdr.version, hdr.version);
640       goto bail_out;
641    }
642    hdr.id[13] = 0;
643    if (strcmp(hdr.id, state_hdr.id) != 0) {
644       Dmsg0(000, "State file header id invalid.\n");
645       goto bail_out;
646    }
647 // Dmsg1(010, "Read header of %d bytes.\n", sizeof(hdr));
648    if (!read_last_jobs_list(sfd, hdr.last_jobs_addr)) {
649       goto bail_out;
650    }
651    ok = true;
652 bail_out:
653    if (sfd >= 0) {
654       close(sfd);
655    }
656    if (!ok) {
657       unlink(fname);
658     }
659    free_pool_memory(fname);
660 }
661
662 /*
663  * Write the state file
664  */
665 static pthread_mutex_t state_mutex = PTHREAD_MUTEX_INITIALIZER;
666
667 void write_state_file(char *dir, const char *progname, int port)
668 {
669    int sfd;
670    bool ok = false;
671    POOLMEM *fname = get_pool_memory(PM_FNAME);
672
673    P(state_mutex);                    /* Only one job at a time can call here */
674    Mmsg(&fname, "%s/%s.%d.state", dir, progname, port);
675    /* Create new state file */
676    unlink(fname);
677    if ((sfd = open(fname, O_CREAT|O_WRONLY|O_BINARY, 0640)) < 0) {
678       berrno be;
679       Dmsg2(000, "Could not create state file. %s ERR=%s\n", fname, be.bstrerror());
680       Emsg2(M_ERROR, 0, _("Could not create state file. %s ERR=%s\n"), fname, be.bstrerror());
681       goto bail_out;
682    }
683    if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
684       berrno be;
685       Dmsg1(000, "Write hdr error: ERR=%s\n", be.bstrerror());
686       goto bail_out;
687    }
688 // Dmsg1(010, "Wrote header of %d bytes\n", sizeof(state_hdr));
689    state_hdr.last_jobs_addr = sizeof(state_hdr);
690    state_hdr.reserved[0] = write_last_jobs_list(sfd, state_hdr.last_jobs_addr);
691 // Dmsg1(010, "write last job end = %d\n", (int)state_hdr.reserved[0]);
692    if (lseek(sfd, 0, SEEK_SET) < 0) {
693       berrno be;
694       Dmsg1(000, "lseek error: ERR=%s\n", be.bstrerror());
695       goto bail_out;
696    }
697    if (write(sfd, &state_hdr, sizeof(state_hdr)) != sizeof(state_hdr)) {
698       berrno be;
699       Pmsg1(000, _("Write final hdr error: ERR=%s\n"), be.bstrerror());
700       goto bail_out;
701    }
702    ok = true;
703 // Dmsg1(010, "rewrote header = %d\n", sizeof(state_hdr));
704 bail_out:
705    if (sfd >= 0) {
706       close(sfd);
707    }
708    if (!ok) {
709       unlink(fname);
710    }
711    V(state_mutex);
712    free_pool_memory(fname);
713 }
714
715
716 /* BSDI does not have this.  This is a *poor* simulation */
717 #ifndef HAVE_STRTOLL
718 long long int
719 strtoll(const char *ptr, char **endptr, int base)
720 {
721    return (long long int)strtod(ptr, endptr);
722 }
723 #endif
724
725 /*
726  * Bacula's implementation of fgets(). The difference is that it handles
727  *   being interrupted by a signal (e.g. a SIGCHLD).
728  */
729 #undef fgetc
730 char *bfgets(char *s, int size, FILE *fd)
731 {
732    char *p = s;
733    int ch;
734    *p = 0;
735    for (int i=0; i < size-1; i++) {
736       do {
737          errno = 0;
738          ch = fgetc(fd);
739       } while (ch == EOF && ferror(fd) && (errno == EINTR || errno == EAGAIN));
740       if (ch == EOF) {
741          if (i == 0) {
742             return NULL;
743          } else {
744             return s;
745          }
746       }
747       *p++ = ch;
748       *p = 0;
749       if (ch == '\r') { /* Support for Mac/Windows file format */
750          ch = fgetc(fd);
751          if (ch != '\n') { /* Mac (\r only) */
752             (void)ungetc(ch, fd); /* Push next character back to fd */
753          }
754          p[-1] = '\n';
755          break;
756       }
757       if (ch == '\n') {
758          break;
759       }
760    }
761    return s;
762 }
763
764 /*
765  * Bacula's implementation of fgets(). The difference is that it handles
766  *   being interrupted by a signal (e.g. a SIGCHLD) and it has a
767  *   different calling sequence which implements input lines of
768  *   up to a million characters.
769  */
770 char *bfgets(POOLMEM *&s, FILE *fd)
771 {
772    int ch;
773    int soft_max;
774    int i = 0;
775
776    s[0] = 0;
777    soft_max = sizeof_pool_memory(s) - 10;
778    for ( ;; ) {
779       do {
780          errno = 0;
781          ch = fgetc(fd);
782       } while (ch == EOF && ferror(fd) && (errno == EINTR || errno == EAGAIN));
783       if (ch == EOF) {
784          if (i == 0) {
785             return NULL;
786          } else {
787             return s;
788          }
789       }
790       if (i > soft_max) {
791          /* Insanity check */
792          if (soft_max > 1000000) {
793             return s;
794          }
795          s = check_pool_memory_size(s, soft_max+10000);
796          soft_max = sizeof_pool_memory(s) - 10;
797       }
798       s[i++] = ch;
799       s[i] = 0;
800       if (ch == '\r') { /* Support for Mac/Windows file format */
801          ch = fgetc(fd);
802          if (ch != '\n') { /* Mac (\r only) */
803             (void)ungetc(ch, fd); /* Push next character back to fd */
804          }
805          s[i-1] = '\n';
806          break;
807       }
808       if (ch == '\n') {
809          break;
810       }
811    }
812    return s;
813 }
814
815 /*
816  * Make a "unique" filename.  It is important that if
817  *   called again with the same "what" that the result
818  *   will be identical. This allows us to use the file
819  *   without saving its name, and re-generate the name
820  *   so that it can be deleted.
821  */
822 void make_unique_filename(POOLMEM **name, int Id, char *what)
823 {
824    Mmsg(name, "%s/%s.%s.%d.tmp", working_directory, my_name, what, Id);
825 }
826
827 char *escape_filename(const char *file_path)
828 {
829    if (file_path == NULL || strpbrk(file_path, "\"\\") == NULL) {
830       return NULL;
831    }
832
833    char *escaped_path = (char *)bmalloc(2 * (strlen(file_path) + 1));
834    char *cur_char = escaped_path;
835
836    while (*file_path) {
837       if (*file_path == '\\' || *file_path == '"') {
838          *cur_char++ = '\\';
839       }
840
841       *cur_char++ = *file_path++;
842    }
843
844    *cur_char = '\0';
845
846    return escaped_path;
847 }
848
849 /*
850  * For the moment preventing suspensions is only
851  *  implement on Windows.
852  */
853 #ifndef HAVE_WIN32
854 void prevent_os_suspensions()
855 { }
856
857 void allow_os_suspensions()
858 { }
859 #endif
860
861
862 #if HAVE_BACKTRACE && HAVE_GCC
863 #include <cxxabi.h>
864 #include <execinfo.h>
865 void stack_trace()
866 {
867    const size_t max_depth = 100;
868    size_t stack_depth;
869    void *stack_addrs[max_depth];
870    char **stack_strings;
871
872    stack_depth = backtrace(stack_addrs, max_depth);
873    stack_strings = backtrace_symbols(stack_addrs, stack_depth);
874
875    for (size_t i = 3; i < stack_depth; i++) {
876       size_t sz = 200; /* just a guess, template names will go much wider */
877       char *function = (char *)actuallymalloc(sz);
878       char *begin = 0, *end = 0;
879       /* find the parentheses and address offset surrounding the mangled name */
880       for (char *j = stack_strings[i]; *j; ++j) {
881          if (*j == '(') {
882             begin = j;
883          } else if (*j == '+') {
884             end = j;
885          }
886       }
887       if (begin && end) {
888          *begin++ = '\0';
889          *end = '\0';
890          /* found our mangled name, now in [begin, end] */
891
892          int status;
893          char *ret = abi::__cxa_demangle(begin, function, &sz, &status);
894          if (ret) {
895             /* return value may be a realloc() of the input */
896             function = ret;
897          } else {
898             /* demangling failed, just pretend it's a C function with no args */
899             strncpy(function, begin, sz);
900             strncat(function, "()", sz);
901             function[sz-1] = '\0';
902          }
903          Pmsg2(000, "    %s:%s\n", stack_strings[i], function);
904
905       } else {
906          /* didn't find the mangled name, just print the whole line */
907          Pmsg1(000, "    %s\n", stack_strings[i]);
908       }
909       actuallyfree(function);
910    }
911    actuallyfree(stack_strings); /* malloc()ed by backtrace_symbols */
912 }
913 #else /* HAVE_BACKTRACE && HAVE_GCC */
914 void stack_trace() {}
915 #endif /* HAVE_BACKTRACE && HAVE_GCC */