-
Notifications
You must be signed in to change notification settings - Fork 256
/
bsys.cc
1282 lines (1077 loc) · 31.7 KB
/
bsys.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
BAREOS® - Backup Archiving REcovery Open Sourced
Copyright (C) 2000-2012 Free Software Foundation Europe e.V.
Copyright (C) 2011-2012 Planets Communications B.V.
Copyright (C) 2013-2022 Bareos GmbH & Co. KG
This program is Free Software; you can redistribute it and/or
modify it under the terms of version three of the GNU Affero General Public
License as published by the Free Software Foundation and included
in the file LICENSE.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
/*
* Miscellaneous BAREOS memory and thread safe routines
* Generally, these are interfaces to system or standard
* library routines.
*
* BAREOS utility functions are in util.c
*/
#include "include/bareos.h"
#include "lib/berrno.h"
#include "lib/recent_job_results_list.h"
#ifndef HAVE_REGEX_H
# include "lib/bregex.h"
#else
# include <regex.h>
#endif
#include <fstream>
#include <type_traits>
#include <sys/file.h>
static pthread_mutex_t timer_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t timer = PTHREAD_COND_INITIALIZER;
static const char* secure_erase_cmdline = NULL;
/*
* This routine is a somewhat safer unlink in that it
* allows you to run a regex on the filename before
* excepting it. It also requires the file to be in
* the working directory.
*/
int SaferUnlink(const char* pathname, const char* regx)
{
int rc;
regex_t preg1{};
char prbuf[500];
int rtn;
// Name must start with working directory
if (strncmp(pathname, working_directory, strlen(working_directory)) != 0) {
Pmsg1(000, "Safe_unlink excluded: %s\n", pathname);
return EROFS;
}
// Compile regex expression
rc = regcomp(&preg1, regx, REG_EXTENDED);
if (rc != 0) {
regerror(rc, &preg1, prbuf, sizeof(prbuf));
Pmsg2(000, _("safe_unlink could not compile regex pattern \"%s\" ERR=%s\n"),
regx, prbuf);
return ENOENT;
}
// Unlink files that match regexes
if (regexec(&preg1, pathname, 0, NULL, 0) == 0) {
Dmsg1(100, "safe_unlink unlinking: %s\n", pathname);
rtn = SecureErase(NULL, pathname);
} else {
Pmsg2(000, "safe_unlink regex failed: regex=%s file=%s\n", regx, pathname);
rtn = EROFS;
}
regfree(&preg1);
return rtn;
}
// This routine will use an external secure erase program to delete a file.
int SecureErase(JobControlRecord* jcr, const char* pathname)
{
int retval = -1;
if (secure_erase_cmdline) {
int status;
Bpipe* bpipe;
PoolMem line(PM_NAME), cmdline(PM_MESSAGE);
Mmsg(cmdline, "%s \"%s\"", secure_erase_cmdline, pathname);
if (jcr) {
Jmsg(jcr, M_INFO, 0, _("SecureErase: executing %s\n"), cmdline.c_str());
}
bpipe = OpenBpipe(cmdline.c_str(), 0, "r");
if (bpipe == NULL) {
BErrNo be;
if (jcr) {
Jmsg(jcr, M_FATAL, 0, _("SecureErase: %s could not execute. ERR=%s\n"),
secure_erase_cmdline, be.bstrerror());
}
goto bail_out;
}
while (fgets(line.c_str(), line.size(), bpipe->rfd)) {
StripTrailingJunk(line.c_str());
if (jcr) { Jmsg(jcr, M_INFO, 0, _("SecureErase: %s\n"), line.c_str()); }
}
status = CloseBpipe(bpipe);
if (status != 0) {
BErrNo be;
if (jcr) {
Jmsg(jcr, M_FATAL, 0,
_("SecureErase: %s returned non-zero status=%d. ERR=%s\n"),
secure_erase_cmdline, be.code(status), be.bstrerror(status));
}
goto bail_out;
}
Dmsg0(100, "wpipe_command OK\n");
retval = 0;
} else {
retval = unlink(pathname);
}
return retval;
bail_out:
errno = EROFS;
return retval;
}
void SetSecureEraseCmdline(const char* cmdline)
{
secure_erase_cmdline = cmdline;
}
/*
* This routine will sleep (sec, microsec). Note, however, that if a
* signal occurs, it will return early. It is up to the caller
* to recall this routine if he/she REALLY wants to sleep the
* requested time.
*/
int Bmicrosleep(int32_t sec, int32_t usec)
{
struct timespec timeout;
struct timeval tv;
struct timezone tz;
int status;
timeout.tv_sec = sec;
timeout.tv_nsec = usec * 1000;
#ifdef HAVE_NANOSLEEP
status = nanosleep(&timeout, NULL);
if (!(status < 0 && errno == ENOSYS)) { return status; }
// If we reach here it is because nanosleep is not supported by the OS
#endif
// Do it the old way
gettimeofday(&tv, &tz);
timeout.tv_nsec += tv.tv_usec * 1000;
timeout.tv_sec += tv.tv_sec;
while (timeout.tv_nsec >= 1000000000) {
timeout.tv_nsec -= 1000000000;
timeout.tv_sec++;
}
Dmsg2(200, "pthread_cond_timedwait sec=%lld usec=%d\n", sec, usec);
// Note, this unlocks mutex during the sleep
P(timer_mutex);
status = pthread_cond_timedwait(&timer, &timer_mutex, &timeout);
V(timer_mutex);
return status;
}
/*
* Copy a string inline from one point in the same string
* to another.
*/
char* bstrinlinecpy(char* dest, const char* src)
{
int len;
/*
* Sanity check. We can only inline copy if the src > dest
* otherwise the resulting copy will overwrite the end of
* the string.
*/
if (src <= dest) { return NULL; }
len = strlen(src);
/*
* Cannot use strcpy or memcpy as those functions are not
* allowed on overlapping data and this is inline replacement
* for sure is. So we use memmove which is allowed on
* overlapping data.
*/
memmove(dest, src, len + 1);
return dest;
}
/*
* Guarantee that the string is properly terminated.
* maxlen is the maximum of the string pointed to by src,
* including the terminating null byte ('\0').
*/
char* bstrncpy(char* dest, const char* src, int maxlen)
{
std::string tmp;
if ((src == nullptr) || (maxlen <= 1)) {
dest[0] = 0;
return dest;
}
if ((dest <= src) && ((dest + (maxlen - 1) * sizeof(char)) >= src)) {
Dmsg0(100, "Overlapping strings found, using copy.\n");
tmp.assign(src);
src = tmp.c_str();
}
strncpy(dest, src, maxlen - 1);
dest[maxlen - 1] = 0;
return dest;
}
// Guarantee that the string is properly terminated
char* bstrncpy(char* dest, PoolMem& src, int maxlen)
{
return bstrncpy(dest, src.c_str(), maxlen);
}
/*
* Note: Here the maxlen is the maximum length permitted
* stored in dest, while on Unix systems, it is the maximum characters
* that may be copied from src.
*/
char* bstrncat(char* dest, const char* src, int maxlen)
{
std::string tmp;
int len = strlen(dest);
if ((dest <= src) && ((dest + (maxlen - 1) * sizeof(char)) >= src)) {
Dmsg0(100, "Overlapping strings found, using copy.\n");
tmp.assign(src);
src = tmp.c_str();
}
if (len < maxlen - 1) { bstrncpy(dest + len, src, maxlen - len); }
return dest;
}
/*
* Note: Here the maxlen is the maximum length permitted
* stored in dest, while on Unix systems, it is the maximum characters
* that may be copied from src.
*/
char* bstrncat(char* dest, PoolMem& src, int maxlen)
{
return bstrncat(dest, src.c_str(), maxlen);
}
// Allows one or both pointers to be NULL
bool bstrcmp(const char* s1, const char* s2)
{
if (s1 == s2) return true;
if (s1 == NULL || s2 == NULL) return false;
return strcmp(s1, s2) == 0;
}
bool bstrncmp(const char* s1, const char* s2, int n)
{
if (s1 == s2) return true;
if (s1 == NULL || s2 == NULL) return false;
return strncmp(s1, s2, n) == 0;
}
bool Bstrcasecmp(const char* s1, const char* s2)
{
if (s1 == s2) return true;
if (s1 == NULL || s2 == NULL) return false;
return strcasecmp(s1, s2) == 0;
}
bool bstrncasecmp(const char* s1, const char* s2, int n)
{
if (s1 == s2) return true;
if (s1 == NULL || s2 == NULL) return false;
return strncasecmp(s1, s2, n) == 0;
}
/*
* Get character length of UTF-8 string
*
* Valid UTF-8 codes
* U-00000000 - U-0000007F: 0xxxxxxx
* U-00000080 - U-000007FF: 110xxxxx 10xxxxxx
* U-00000800 - U-0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx
* U-00010000 - U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
* U-00200000 - U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
* U-04000000 - U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
* 10xxxxxx
*/
int cstrlen(const char* str)
{
uint8_t* p = (uint8_t*)str;
int len = 0;
if (str == NULL) { return 0; }
while (*p) {
if ((*p & 0xC0) != 0xC0) {
p++;
len++;
continue;
}
if ((*p & 0xD0) == 0xC0) {
p += 2;
len++;
continue;
}
if ((*p & 0xF0) == 0xD0) {
p += 3;
len++;
continue;
}
if ((*p & 0xF8) == 0xF0) {
p += 4;
len++;
continue;
}
if ((*p & 0xFC) == 0xF8) {
p += 5;
len++;
continue;
}
if ((*p & 0xFE) == 0xFC) {
p += 6;
len++;
continue;
}
p++; /* Shouln't get here but must advance */
}
return len;
}
#ifndef HAVE_LOCALTIME_R
struct tm* localtime_r(const time_t* timep, struct tm* tm)
{
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
struct tm *ltm,
P(mutex);
ltm = localtime(timep);
if (ltm) { memcpy(tm, ltm, sizeof(struct tm)); }
V(mutex);
return ltm ? tm : NULL;
}
#endif /* HAVE_LOCALTIME_R */
#ifndef HAVE_READDIR_R
# ifndef HAVE_WIN32
# include <dirent.h>
int Readdir_r(DIR* dirp, struct dirent* entry, struct dirent** result)
{
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
struct dirent* ndir;
int status;
P(mutex);
errno = 0;
ndir = readdir(dirp);
status = errno;
if (ndir) {
memcpy(entry, ndir, sizeof(struct dirent));
strcpy(entry->d_name, ndir->d_name);
*result = entry;
} else {
*result = NULL;
}
V(mutex);
return status;
}
# endif
#endif /* HAVE_READDIR_R */
int b_strerror(int errnum, char* buf, size_t bufsiz)
{
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int status = 0;
const char* msg;
P(mutex);
msg = strerror(errnum);
if (!msg) {
msg = _("Bad errno");
status = -1;
}
bstrncpy(buf, msg, bufsiz);
V(mutex);
return status;
}
#if !defined(HAVE_WIN32)
static void LockPidFile(const char* progname,
int pidfile_fd,
const char* pidfile_path)
{
struct flock fl;
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 0;
if (fcntl(pidfile_fd, F_SETLK, &fl)) {
if (errno == EAGAIN || errno == EACCES) {
BErrNo be;
Emsg2(M_ERROR_TERM, 0,
_("PID file '%s' is locked; probably '%s' is already running. "),
pidfile_path, progname);
} else {
BErrNo be;
Emsg2(M_ERROR_TERM, 0, _("Unable to lock PID file '%s'. ERR=%s\n"),
pidfile_path, be.bstrerror());
}
}
}
static void UnlockPidFile(int pidfile_fd, const char* pidfile_path)
{
struct flock fl;
fl.l_type = F_UNLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 0;
if (fcntl(pidfile_fd, F_SETLK, &fl)) {
BErrNo be;
Emsg2(M_ERROR_TERM, 0, _("Unable to unlock PID file '%s'. ERR=%s\n"),
pidfile_path, be.bstrerror());
}
}
#endif // HAVE_WIN32
/*
The content of this function (CreatePidFile) was inspired and modified to fit
current needs from filelock/create_pid_file.c (Listing 55-4, page 1143), an
example to accompany the book, The Linux Programming Interface.
The original source code file of filelock/create_pid_file.c is copyright
2010, Michael Kerrisk, and is licensed under the GNU Lesser General Public
License, version 3.
*/
#define CPF_CLOEXEC 1
#if !defined(HAVE_WIN32)
int CreatePidFile(const char* progname, const char* pidfile_path)
{
int pidfd;
pidfd = open(pidfile_path, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
if (pidfd == -1) {
BErrNo be;
Emsg2(M_ERROR_TERM, 0, _("Cannot open pid file. %s ERR=%s\n"), pidfile_path,
be.bstrerror());
}
int flags;
if (CPF_CLOEXEC) {
/* Set the close-on-exec file descriptor flag */
/* Instead of the following steps, we could (on Linux) have opened the
file with O_CLOEXEC flag. However, not all systems support open()
O_CLOEXEC (which was standardized only in SUSv4), so instead we use
fcntl() to set the close-on-exec flag after opening the file */
flags = fcntl(pidfd, F_GETFD); /* Fetch flags */
if (flags == -1) {
BErrNo be;
Emsg2(M_ERROR_TERM, 0, _("Could not get flags for PID file %s. ERR=%s\n"),
pidfile_path, be.bstrerror());
}
flags |= FD_CLOEXEC; /* Turn on FD_CLOEXEC */
if (fcntl(pidfd, F_SETFD, flags) == -1) /* Update flags */ {
BErrNo be;
Emsg2(M_ERROR_TERM, 0, _("Could not get flags for PID file %s. ERR=%s\n"),
pidfile_path, be.bstrerror());
}
}
// Locking and unlocking only to check if there is already an instance of
// bareos running
LockPidFile(progname, pidfd, pidfile_path);
UnlockPidFile(pidfd, pidfile_path);
return pidfd;
}
#endif
/*
The content of this function (WritePidFile) was inspired and modified to fit
current needs from filelock/create_pid_file.c (Listing 55-4, page 1143), an
example to accompany the book, The Linux Programming Interface.
The original source code file of filelock/create_pid_file.c is copyright
2010, Michael Kerrisk, and is licensed under the GNU Lesser General Public
License, version 3.
*/
#if !defined(HAVE_WIN32)
void WritePidFile(int pidfile_fd,
const char* pidfile_path,
const char* progname)
{
const int buf_size = 100;
char buf[buf_size];
LockPidFile(progname, pidfile_fd, pidfile_path);
if (ftruncate(pidfile_fd, 0) == -1) {
BErrNo be;
Emsg2(M_ERROR_TERM, 0, _("Could not truncate PID file '%s'. ERR=%s\n"),
pidfile_path, be.bstrerror());
}
snprintf(buf, buf_size, "%d\n", getpid());
if (write(pidfile_fd, buf, strlen(buf))
!= static_cast<ssize_t>(strlen(buf))) {
BErrNo be;
Emsg2(M_ERROR_TERM, 0, _("Writing to PID file '%s'. ERR=%s\n"),
pidfile_path, be.bstrerror());
}
}
#endif
// Delete the pid file if we created it
int DeletePidFile(const char* pidfile_path)
{
#if !defined(HAVE_WIN32)
if (pidfile_path) { unlink(pidfile_path); }
#endif
return 1;
}
static struct StateFileHeader state_hdr = {{"Bareos State\n"}, 4, 0, 0, {0}};
static bool CheckHeader(const StateFileHeader& hdr)
{
if (hdr.version != state_hdr.version) {
Dmsg2(100, "Bad hdr version. Wanted %d got %d\n", state_hdr.version,
hdr.version);
return false;
}
if (strncmp(hdr.id, state_hdr.id, sizeof(hdr.id))) {
Dmsg0(100, "State file header id invalid.\n");
return false;
}
return true;
}
class SecureEraseGuard {
std::string filename;
bool cleanup = true;
public:
SecureEraseGuard(const std::string& fname_in) : filename(fname_in) {}
~SecureEraseGuard()
{
if (cleanup) { SecureErase(nullptr, filename.c_str()); }
}
void Release() { cleanup = false; }
};
static std::string CreateFileNameFrom(const char* dir,
const char* progname,
int port)
{
int amount = snprintf(nullptr, 0, "%s/%s.%d.state", dir, progname, port) + 1;
std::vector<char> filename(amount);
snprintf(filename.data(), amount, "%s/%s.%d.state", dir, progname, port);
return std::string(filename.data());
}
void ReadStateFile(const char* dir, const char* progname, int port)
{
std::string filename = CreateFileNameFrom(dir, progname, port);
SecureEraseGuard secure_erase_guard(filename.data());
#if defined HAVE_IS_TRIVIALLY_COPYABLE
static_assert(std::is_trivially_copyable<StateFileHeader>::value,
"StateFileHeader must be trivially copyable");
#endif
struct StateFileHeader hdr {
{0}, 0, 0, 0, { 0 }
};
std::ifstream file;
file.exceptions(file.exceptions() | std::ios::failbit | std::ios::badbit);
try {
file.open(filename, std::ios::binary);
file.read(reinterpret_cast<char*>(&hdr), sizeof(StateFileHeader));
if (!CheckHeader(hdr)) { return; }
if (hdr.last_jobs_addr) {
Dmsg1(100, "ReadStateFile seek to %d\n", (int)hdr.last_jobs_addr);
file.seekg(hdr.last_jobs_addr);
}
} catch (const std::system_error& e) {
BErrNo be;
Dmsg3(100, "Could not open and read state file. size=%d: ERR=%s - %s\n",
sizeof(StateFileHeader), be.bstrerror(), e.code().message().c_str());
return;
} catch (const std::exception& e) {
Dmsg0(100, "Could not open or read file. Some error occurred: %s\n",
e.what());
}
if (!RecentJobResultsList::ImportFromFile(file)) { return; }
secure_erase_guard.Release();
}
static void SafeTheLastWritePosition(std::ofstream& file, uint64_t pos)
{
std::streampos position_after_export = file.tellp();
pos = (position_after_export == static_cast<std::streampos>(-1))
? static_cast<std::streampos>(0)
: position_after_export;
}
void WriteStateFile(const char* dir, const char* progname, int port)
{
std::string filename = CreateFileNameFrom(dir, progname, port);
#if defined HAVE_IS_TRIVIALLY_COPYABLE
static_assert(std::is_trivially_copyable<StateFileHeader>::value,
"StateFileHeader must be trivially copyable");
#endif
SecureErase(NULL, filename.c_str());
SecureEraseGuard erase_on_scope_exit(filename);
static std::mutex exclusive_write_access_mutex;
std::lock_guard<std::mutex> m(exclusive_write_access_mutex);
std::ofstream file;
file.exceptions(file.exceptions() | std::ios::failbit | std::ios::badbit);
try {
file.open(filename, std::ios::binary);
file.write(reinterpret_cast<char*>(&state_hdr), sizeof(StateFileHeader));
state_hdr.last_jobs_addr = sizeof(StateFileHeader);
Dmsg1(100, "write_last_jobs seek to %d\n", (int)state_hdr.last_jobs_addr);
file.seekp(state_hdr.last_jobs_addr);
if (RecentJobResultsList::ExportToFile(file)) {
SafeTheLastWritePosition(file, state_hdr.end_of_recent_job_results_list);
}
file.seekp(0);
file.write(reinterpret_cast<char*>(&state_hdr), sizeof(StateFileHeader));
} catch (const std::system_error& e) {
BErrNo be;
Dmsg3(100, "Could not seek filepointer. ERR=%s - %s\n", be.bstrerror(),
e.code().message().c_str());
return;
} catch (const std::exception& e) {
Dmsg0(100, "Could not seek filepointer. Some error occurred: %s\n",
e.what());
return;
}
erase_on_scope_exit.Release();
}
/*
* BAREOS's implementation of fgets(). The difference is that it handles
* being interrupted by a signal (e.g. a SIGCHLD).
*/
#undef fgetc
char* bfgets(char* s, int size, FILE* fd)
{
char* p = s;
int ch;
*p = 0;
for (int i = 0; i < size - 1; i++) {
do {
errno = 0;
ch = fgetc(fd);
} while (ch == EOF && ferror(fd) && (errno == EINTR || errno == EAGAIN));
if (ch == EOF) {
if (i == 0) {
return NULL;
} else {
return s;
}
}
*p++ = ch;
*p = 0;
if (ch == '\r') { /* Support for Mac/Windows file format */
ch = fgetc(fd);
if (ch != '\n') { /* Mac (\r only) */
(void)ungetc(ch, fd); /* Push next character back to fd */
}
p[-1] = '\n';
break;
}
if (ch == '\n') { break; }
}
return s;
}
/*
* BAREOS's implementation of fgets(). The difference is that it handles
* being interrupted by a signal (e.g. a SIGCHLD) and it has a
* different calling sequence which implements input lines of
* up to a million characters.
*/
char* bfgets(POOLMEM*& s, FILE* fd)
{
int ch;
int soft_max;
int i = 0;
s[0] = 0;
soft_max = SizeofPoolMemory(s) - 10;
for (;;) {
do {
errno = 0;
ch = fgetc(fd);
} while (ch == EOF && ferror(fd) && (errno == EINTR || errno == EAGAIN));
if (ch == EOF) {
if (i == 0) {
return NULL;
} else {
return s;
}
}
if (i > soft_max) {
/* Insanity check */
if (soft_max > 1000000) { return s; }
s = CheckPoolMemorySize(s, soft_max + 10000);
soft_max = SizeofPoolMemory(s) - 10;
}
s[i++] = ch;
s[i] = 0;
if (ch == '\r') { /* Support for Mac/Windows file format */
ch = fgetc(fd);
if (ch != '\n') { /* Mac (\r only) */
(void)ungetc(ch, fd); /* Push next character back to fd */
}
s[i - 1] = '\n';
break;
}
if (ch == '\n') { break; }
}
return s;
}
/*
* Make a "unique" filename. It is important that if
* called again with the same "what" that the result
* will be identical. This allows us to use the file
* without saving its name, and re-generate the name
* so that it can be deleted.
*/
void MakeUniqueFilename(POOLMEM*& name, int Id, char* what)
{
Mmsg(name, "%s/%s.%s.%d.tmp", working_directory, my_name, what, Id);
}
char* escape_filename(const char* file_path)
{
if (file_path == NULL || strpbrk(file_path, "\"\\") == NULL) { return NULL; }
char* escaped_path = (char*)malloc(2 * (strlen(file_path) + 1));
char* cur_char = escaped_path;
while (*file_path) {
if (*file_path == '\\' || *file_path == '"') { *cur_char++ = '\\'; }
*cur_char++ = *file_path++;
}
*cur_char = '\0';
return escaped_path;
}
bool PathExists(const char* path)
{
struct stat statp;
if (!path || !strlen(path)) { return false; }
return (stat(path, &statp) == 0);
}
bool PathExists(PoolMem& path) { return PathExists(path.c_str()); }
bool PathIsDirectory(const char* path)
{
struct stat statp;
if (!path || !strlen(path)) { return false; }
if (stat(path, &statp) == 0) {
return (S_ISDIR(statp.st_mode));
} else {
return false;
}
}
bool PathIsDirectory(PoolMem& path) { return PathIsDirectory(path.c_str()); }
bool PathIsAbsolute(const char* path)
{
if (!path || !strlen(path)) {
// No path: not an absolute path
return false;
}
// Is path absolute?
if (IsPathSeparator(path[0])) { return true; }
#ifdef HAVE_WIN32
/*
* Windows:
* Does path begin with drive? if yes, it is absolute
*/
if (strlen(path) >= 3) {
if (isalpha(path[0]) && path[1] == ':' && IsPathSeparator(path[2])) {
return true;
}
}
#endif
return false;
}
bool PathIsAbsolute(PoolMem& path) { return PathIsAbsolute(path.c_str()); }
bool PathContainsDirectory(const char* path)
{
int i;
if (!path) { return false; }
i = strlen(path) - 1;
while (i >= 0) {
if (IsPathSeparator(path[i])) { return true; }
i--;
}
return false;
}
bool PathContainsDirectory(PoolMem& path)
{
return PathContainsDirectory(path.c_str());
}
// Get directory from path.
bool PathGetDirectory(PoolMem& directory, PoolMem& path)
{
char* dir = NULL;
int i = path.strlen();
directory.strcpy(path);
if (!PathIsDirectory(directory)) {
dir = directory.addr();
while ((!IsPathSeparator(dir[i])) && (i > 0)) {
dir[i] = 0;
i--;
}
}
if (PathIsDirectory(directory)) {
// Make sure, path ends with path separator
PathAppend(directory, "");
return true;
}
return false;
}
bool PathAppend(char* path, const char* extra, unsigned int max_path)
{
unsigned int path_len;
unsigned int required_length;
if (!path || !extra) { return true; }
path_len = strlen(path);
required_length = path_len + 1 + strlen(extra);
if (required_length > max_path) { return false; }
// Add path separator after original path if missing.
if (!IsPathSeparator(path[path_len - 1])) {
path[path_len] = PathSeparator;
path_len++;
}
memcpy(path + path_len, extra, strlen(extra) + 1);
return true;
}
bool PathAppend(PoolMem& path, const char* extra)
{
unsigned int required_length;
if (!extra) { return true; }
required_length = path.strlen() + 2 + strlen(extra);
if (!path.check_size(required_length)) { return false; }
return PathAppend(path.c_str(), extra, required_length);
}
// Append to paths together.
bool PathAppend(PoolMem& path, PoolMem& extra)
{
return PathAppend(path, extra.c_str());
}
/*
* based on
* src/findlib/mkpath.c:bool makedir(...)
*/
static bool PathMkdir(char* path, mode_t mode)
{
if (PathExists(path)) {
Dmsg1(500, "skipped, path %s already exists.\n", path);
return PathIsDirectory(path);
}
if (mkdir(path, mode) != 0) {
BErrNo be;
Emsg2(M_ERROR, 0, "Falied to create directory %s: ERR=%s\n", path,
be.bstrerror());
return false;
}
return true;
}
/*
* based on
* src/findlib/mkpath.c:bool makepath(Attributes *attr, const char *apath,
* mode_t mode, mode_t parent_mode, ...
*/
bool PathCreate(const char* apath, mode_t mode)
{
char* p;
int len;
bool ok = false;
struct stat statp;
char* path = NULL;
if (stat(apath, &statp) == 0) { /* Does dir exist? */
if (!S_ISDIR(statp.st_mode)) {
Emsg1(M_ERROR, 0, "%s exists but is not a directory.\n", path);
return false;
}
return true;
}
len = strlen(apath);
path = (char*)alloca(len + 1);
bstrncpy(path, apath, len + 1);
StripTrailingSlashes(path);
#if defined(HAVE_WIN32)