forked from logrotate/logrotate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logrotate.c
2605 lines (2303 loc) · 67 KB
/
logrotate.c
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
#include "queue.h"
/* alloca() is defined in stdlib.h in NetBSD */
#ifndef __NetBSD__
#include <alloca.h>
#endif
#include <limits.h>
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <popt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <glob.h>
#include <locale.h>
#include <sys/types.h>
#include <utime.h>
#include <stdint.h>
#if defined(SunOS)
#include <limits.h>
#endif
#include "basenames.h"
#include "log.h"
#include "logrotate.h"
#ifdef WITH_SELINUX
#include <selinux/selinux.h>
static security_context_t prev_context = NULL;
int selinux_enabled = 0;
int selinux_enforce = 0;
#endif
#ifdef WITH_ACL
#include "sys/acl.h"
#define acl_type acl_t
#define ACL_NOT_WELL_SUPPORTED(Err) \
((Err) == ENOTSUP || (Err) == ENOSYS || (Err) == EINVAL || (Err) == EBUSY)
#else
#define acl_type void *
#endif
static acl_type prev_acl = NULL;
#if !defined(GLOB_ABORTED) && defined(GLOB_ABEND)
#define GLOB_ABORTED GLOB_ABEND
#endif
#ifdef PATH_MAX
#define STATEFILE_BUFFER_SIZE 2 * PATH_MAX + 16
#else
#define STATEFILE_BUFFER_SIZE 4096
#endif
#ifdef __hpux
extern int asprintf(char **str, const char *fmt, ...);
#endif
#if defined(HAVE_FORK)
#define FORK_OR_VFORK fork
#define DOEXIT exit
#elif defined(HAVE_VFORK)
#define FORK_OR_VFORK vfork
#define DOEXIT _exit
#else
#define FORK_OR_VFORK fork
#define DOEXIT exit
#endif
// Number of seconds in a day
#define DAY_SECONDS 86400
struct logState {
char *fn;
struct tm lastRotated; /* only tm_hour, tm_mday, tm_mon, tm_year are good! */
struct stat sb;
int doRotate;
int isUsed; /* True if there is real log file in system for this state. */
LIST_ENTRY(logState) list;
};
struct logNames {
char *firstRotated;
char *disposeName;
char *finalName;
char *dirName;
char *baseName;
};
struct compData {
int prefix_len;
const char *dformat;
};
struct logStates {
LIST_HEAD(stateSet, logState) head;
} **states;
unsigned int hashSize;
int numLogs = 0;
int debug = 0;
char *mailCommand = DEFAULT_MAIL_COMMAND;
time_t nowSecs = 0;
static uid_t save_euid;
static gid_t save_egid;
static int shred_file(int fd, char *filename, struct logInfo *log);
static int globerr(const char *pathname, int theerr)
{
message(MESS_ERROR, "error accessing %s: %s\n", pathname,
strerror(theerr));
/* We want the glob operation to continue, so return 0 */
return 1;
}
#if defined(HAVE_STRPTIME) && defined(HAVE_QSORT)
/* We could switch to qsort_r to get rid of this global variable,
* but qsort_r is not portable enough (Linux vs. *BSD vs ...)... */
static struct compData _compData;
static int compGlobResult(const void *result1, const void *result2) {
struct tm time;
time_t t1, t2;
const char *r1 = *(const char **)(result1);
const char *r2 = *(const char **)(result2);
memset(&time, 0, sizeof(struct tm));
strptime(r1 + _compData.prefix_len, _compData.dformat, &time);
t1 = mktime(&time);
memset(&time, 0, sizeof(struct tm));
strptime(r2 + _compData.prefix_len, _compData.dformat, &time);
t2 = mktime(&time);
if (t1 < t2) return -1;
if (t1 > t2) return 1;
return 0;
}
static void sortGlobResult(glob_t *result, int prefix_len, const char *dformat) {
if (!dformat || *dformat == '\0') {
return;
}
_compData.prefix_len = prefix_len;
_compData.dformat = dformat;
qsort(result->gl_pathv, result->gl_pathc, sizeof(char *), compGlobResult);
}
#else
static void sortGlobResult(glob_t *result, int prefix_len, const char *dformat) {
/* TODO */
}
#endif
int switch_user(uid_t user, gid_t group) {
save_egid = getegid();
save_euid = geteuid();
if (save_euid == user && save_egid == group)
return 0;
message(MESS_DEBUG, "switching euid to %d and egid to %d\n",
user, group);
if (setegid(group) || seteuid(user)) {
message(MESS_ERROR, "error switching euid to %d and egid to %d: %s\n",
user, group, strerror(errno));
return 1;
}
return 0;
}
int switch_user_permanently(const struct logInfo *log) {
gid_t group = getegid();
uid_t user = geteuid();
if (!(log->flags & LOG_FLAG_SU)) {
return 0;
}
if (getuid() == user && getgid() == group)
return 0;
// switch to full root first
if (setgid(getgid()) || setuid(getuid())) {
message(MESS_ERROR, "error getting rid of euid != uid\n");
return 1;
}
message(MESS_DEBUG, "switching uid to %d and gid to %d\n",
user, group);
if (setgid(group) || setuid(user)) {
message(MESS_ERROR, "error switching euid to %d and egid to %d: %s\n",
user, group, strerror(errno));
return 1;
}
return 0;
}
int switch_user_back() {
return switch_user(save_euid, save_egid);
}
int switch_user_back_permanently() {
gid_t tmp_egid = save_egid;
uid_t tmp_euid = save_euid;
int ret = switch_user(save_euid, save_egid);
save_euid = tmp_euid;
save_egid = tmp_egid;
return ret;
}
static void unescape(char *arg)
{
char *p = arg;
char *next;
char escaped;
while ((next = strchr(p, '\\')) != NULL) {
p = next;
switch (p[1]) {
case 'n':
escaped = '\n';
break;
case '\\':
escaped = '\\';
break;
default:
++p;
continue;
}
/* Overwrite the backslash with the intended character,
* and shift everything down one */
*p++ = escaped;
memmove(p, p+1, 1 + strlen(p+1));
}
}
#define HASH_SIZE_MIN 64
static int allocateHash(unsigned int hs)
{
int i;
/* Enforce some reasonable minimum hash size */
if (hs < HASH_SIZE_MIN)
hs = HASH_SIZE_MIN;
message(MESS_DEBUG, "Allocating hash table for state file, size %d entries\n",
hs);
states = calloc(hs, sizeof(struct logStates *));
if (states == NULL) {
message(MESS_ERROR, "could not allocate memory for "
"hash table\n");
return 1;
}
for (i = 0; i < hs; i++) {
states[i] = malloc(sizeof(struct logState));
if (states[i] == NULL) {
message(MESS_ERROR, "could not allocate memory for "
"hash element\n");
return 1;
}
LIST_INIT(&(states[i]->head));
}
hashSize = hs;
return 0;
}
#define HASH_CONST 13
static unsigned hashIndex(const char *fn)
{
unsigned hash = 0;
while (*fn) {
hash *= HASH_CONST;
hash += *fn++;
}
return hash % hashSize;
}
static struct logState *newState(const char *fn)
{
struct tm now = *localtime(&nowSecs);
struct logState *new;
time_t lr_time;
message(MESS_DEBUG, "Creating new state\n");
if ((new = malloc(sizeof(*new))) == NULL)
return NULL;
if ((new->fn = strdup(fn)) == NULL) {
free(new);
return NULL;
}
new->doRotate = 0;
new->isUsed = 0;
memset(&new->lastRotated, 0, sizeof(new->lastRotated));
new->lastRotated.tm_hour = now.tm_hour;
new->lastRotated.tm_mday = now.tm_mday;
new->lastRotated.tm_mon = now.tm_mon;
new->lastRotated.tm_year = now.tm_year;
new->lastRotated.tm_isdst = now.tm_isdst;
/* fill in the rest of the new->lastRotated fields */
lr_time = mktime(&new->lastRotated);
new->lastRotated = *localtime(&lr_time);
return new;
}
static struct logState *findState(const char *fn)
{
unsigned int i = hashIndex(fn);
struct logState *p;
for (p = states[i]->head.lh_first; p != NULL; p = p->list.le_next)
if (!strcmp(fn, p->fn))
break;
/* new state */
if (p == NULL) {
if ((p = newState(fn)) == NULL)
return NULL;
LIST_INSERT_HEAD(&(states[i]->head), p, list);
}
return p;
}
static int runScript(struct logInfo *log, char *logfn, char *script)
{
int rc;
if (debug) {
message(MESS_DEBUG, "running script with arg %s: \"%s\"\n",
logfn, script);
return 0;
}
if (!FORK_OR_VFORK()) {
if (log->flags & LOG_FLAG_SU) {
if (switch_user_back_permanently() != 0) {
DOEXIT(1);
}
}
execl("/bin/sh", "sh", "-c", script, "logrotate_script", logfn, NULL);
DOEXIT(1);
}
wait(&rc);
return rc;
}
int createOutputFile(char *fileName, int flags, struct stat *sb, acl_type acl, int force_mode)
{
int fd;
struct stat sb_create;
int acl_set = 0;
if (stat(fileName, &sb_create) == 0) {
/* the destination file already exists, while it should not */
struct tm now = *localtime(&nowSecs);
size_t fileName_size = strlen(fileName);
char* backupName = alloca(fileName_size + sizeof("-YYYYMMDDHH.backup"));
strncpy(backupName, fileName, fileName_size);
size_t date_size=strftime(backupName+fileName_size, 12, "-%Y%m%d%H", &now);
strncpy(backupName+fileName_size+date_size, ".backup\0", 8);
message(MESS_ERROR, "destination %s already exists, renaming to %s\n", fileName, backupName);
if (rename(fileName, backupName) != 0) {
message(MESS_ERROR, "error renaming already existing output file %s to %s: %s\n",
fileName, backupName, strerror(errno));
return -1;
}
}
fd = open(fileName, (flags | O_EXCL | O_NOFOLLOW),
(S_IRUSR | S_IWUSR) & sb->st_mode);
if (fd < 0) {
message(MESS_ERROR, "error creating output file %s: %s\n",
fileName, strerror(errno));
return -1;
}
if (fchmod(fd, (S_IRUSR | S_IWUSR) & sb->st_mode)) {
message(MESS_ERROR, "error setting mode of %s: %s\n",
fileName, strerror(errno));
close(fd);
return -1;
}
if (fstat(fd, &sb_create)) {
message(MESS_ERROR, "fstat of %s failed: %s\n", fileName,
strerror(errno));
close(fd);
return -1;
}
if ((sb_create.st_uid != sb->st_uid || sb_create.st_gid != sb->st_gid) &&
fchown(fd, sb->st_uid, sb->st_gid)) {
message(MESS_ERROR, "error setting owner of %s to uid %d and gid %d: %s\n",
fileName, sb->st_uid, sb->st_gid, strerror(errno));
close(fd);
return -1;
}
#ifdef WITH_ACL
if (!force_mode && acl) {
if (acl_set_fd(fd, acl) == -1) {
if (!ACL_NOT_WELL_SUPPORTED(errno)) {
message(MESS_ERROR, "setting ACL for %s: %s\n",
fileName, strerror(errno));
close(fd);
return -1;
}
acl_set = 0;
}
else {
acl_set = 1;
}
}
#endif
if (!acl_set || force_mode) {
if (fchmod(fd, sb->st_mode)) {
message(MESS_ERROR, "error setting mode of %s: %s\n",
fileName, strerror(errno));
close(fd);
return -1;
}
}
return fd;
}
#define DIGITS 10
/* unlink, but try to call shred from GNU fileutils */
static int shred_file(int fd, char *filename, struct logInfo *log)
{
char count[DIGITS]; /* that's a lot of shredding :) */
const char **fullCommand;
int id = 0;
int status;
if (log->preremove) {
message(MESS_DEBUG, "running preremove script\n");
if (runScript(log, filename, log->preremove)) {
message(MESS_ERROR,
"error running preremove script "
"for %s of '%s'. Not removing this file.\n",
filename, log->pattern);
/* What ever was supposed to happen did not happen,
* therefore do not unlink the file yet. */
return 1;
}
}
if (!(log->flags & LOG_FLAG_SHRED)) {
return unlink(filename);
}
message(MESS_DEBUG, "Using shred to remove the file %s\n", filename);
if (log->shred_cycles != 0) {
fullCommand = alloca(sizeof(*fullCommand) * 6);
}
else {
fullCommand = alloca(sizeof(*fullCommand) * 4);
}
fullCommand[id++] = "shred";
fullCommand[id++] = "-u";
if (log->shred_cycles != 0) {
fullCommand[id++] = "-n";
snprintf(count, DIGITS - 1, "%d", log->shred_cycles);
fullCommand[id++] = count;
}
fullCommand[id++] = "-";
fullCommand[id++] = NULL;
if (!FORK_OR_VFORK()) {
dup2(fd, 1);
close(fd);
if (switch_user_permanently(log) != 0) {
DOEXIT(1);
}
execvp(fullCommand[0], (void *) fullCommand);
DOEXIT(1);
}
wait(&status);
if (!WIFEXITED(status) || WEXITSTATUS(status)) {
message(MESS_ERROR, "Failed to shred %s\n, trying unlink", filename);
return unlink(filename);
}
/* We have to unlink it after shred anyway,
* because it doesn't remove the file itself */
return unlink(filename);
}
static int removeLogFile(char *name, struct logInfo *log)
{
int fd;
message(MESS_DEBUG, "removing old log %s\n", name);
if ((fd = open(name, O_RDWR | O_NOFOLLOW)) < 0) {
message(MESS_ERROR, "error opening %s: %s\n",
name, strerror(errno));
return 1;
}
if (!debug && shred_file(fd, name, log)) {
message(MESS_ERROR, "Failed to remove old log %s: %s\n",
name, strerror(errno));
close(fd);
return 1;
}
close(fd);
return 0;
}
static int compressLogFile(char *name, struct logInfo *log, struct stat *sb)
{
char *compressedName;
char *envInFilename;
const char **fullCommand;
struct utimbuf utim;
int inFile;
int outFile;
int i;
int status;
int compressPipe[2];
char buff[4092];
int error_printed = 0;
message(MESS_DEBUG, "compressing log with: %s\n", log->compress_prog);
if (debug)
return 0;
fullCommand = alloca(sizeof(*fullCommand) *
(log->compress_options_count + 2));
fullCommand[0] = log->compress_prog;
for (i = 0; i < log->compress_options_count; i++)
fullCommand[i + 1] = log->compress_options_list[i];
fullCommand[log->compress_options_count + 1] = NULL;
compressedName = alloca(strlen(name) + strlen(log->compress_ext) + 2);
sprintf(compressedName, "%s%s", name, log->compress_ext);
if ((inFile = open(name, O_RDWR | O_NOFOLLOW)) < 0) {
message(MESS_ERROR, "unable to open %s for compression\n", name);
return 1;
}
#ifdef WITH_ACL
if ((prev_acl = acl_get_fd(inFile)) == NULL) {
if (!ACL_NOT_WELL_SUPPORTED(errno)) {
message(MESS_ERROR, "getting file ACL %s: %s\n",
name, strerror(errno));
close(inFile);
return 1;
}
}
#endif
outFile =
createOutputFile(compressedName, O_RDWR | O_CREAT, sb, prev_acl, 0);
#ifdef WITH_ACL
if (prev_acl) {
acl_free(prev_acl);
prev_acl = NULL;
}
#endif
if (outFile < 0) {
close(inFile);
return 1;
}
if (pipe(compressPipe) < 0) {
message(MESS_ERROR, "error opening pipe for compress: %s",
strerror(errno));
close(inFile);
close(outFile);
return 1;
}
if (!FORK_OR_VFORK()) {
dup2(inFile, 0);
close(inFile);
dup2(outFile, 1);
close(outFile);
dup2(compressPipe[1], 2);
close(compressPipe[0]);
close(compressPipe[1]);
if (switch_user_permanently(log) != 0) {
DOEXIT(1);
}
envInFilename = alloca(strlen("LOGROTATE_COMPRESSED_FILENAME=") + strlen(name) + 2);
sprintf(envInFilename, "LOGROTATE_COMPRESSED_FILENAME=%s", name);
putenv(envInFilename);
execvp(fullCommand[0], (void *) fullCommand);
DOEXIT(1);
}
close(compressPipe[1]);
while ((i = read(compressPipe[0], buff, sizeof(buff) - 1)) > 0) {
if (!error_printed) {
error_printed = 1;
message(MESS_ERROR, "Compressing program wrote following message "
"to stderr when compressing log %s:\n", name);
}
buff[i] = '\0';
fprintf(stderr, "%s", buff);
}
close(compressPipe[0]);
wait(&status);
fsync(outFile);
close(outFile);
if (!WIFEXITED(status) || WEXITSTATUS(status)) {
message(MESS_ERROR, "failed to compress log %s\n", name);
close(inFile);
unlink(compressedName);
return 1;
}
utim.actime = sb->st_atime;
utim.modtime = sb->st_mtime;
utime(compressedName,&utim);
/* If we can't change atime/mtime, it's not a disaster.
It might possibly fail under SELinux. */
shred_file(inFile, name, log);
close(inFile);
return 0;
}
static int mailLog(struct logInfo *log, char *logFile, char *mailCommand,
char *uncompressCommand, char *address, char *subject)
{
int mailInput;
pid_t mailChild, uncompressChild = 0;
int mailStatus, uncompressStatus;
int uncompressPipe[2];
char *mailArgv[] = { mailCommand, "-s", subject, address, NULL };
int rc = 0;
if ((mailInput = open(logFile, O_RDONLY | O_NOFOLLOW)) < 0) {
message(MESS_ERROR, "failed to open %s for mailing: %s\n", logFile,
strerror(errno));
return 1;
}
if (uncompressCommand) {
if (pipe(uncompressPipe) < 0) {
message(MESS_ERROR, "error opening pipe for uncompress: %s",
strerror(errno));
close(mailInput);
return 1;
}
if (!(uncompressChild = FORK_OR_VFORK())) {
/* uncompress child */
dup2(mailInput, 0);
close(mailInput);
dup2(uncompressPipe[1], 1);
close(uncompressPipe[0]);
close(uncompressPipe[1]);
if (switch_user_permanently(log) != 0) {
DOEXIT(1);
}
execlp(uncompressCommand, uncompressCommand, NULL);
DOEXIT(1);
}
close(mailInput);
mailInput = uncompressPipe[0];
close(uncompressPipe[1]);
}
if (!(mailChild = FORK_OR_VFORK())) {
dup2(mailInput, 0);
close(mailInput);
close(1);
// mail command runs as root
if (log->flags & LOG_FLAG_SU) {
if (switch_user_back_permanently() != 0) {
DOEXIT(1);
}
}
execvp(mailArgv[0], mailArgv);
DOEXIT(1);
}
close(mailInput);
waitpid(mailChild, &mailStatus, 0);
if (!WIFEXITED(mailStatus) || WEXITSTATUS(mailStatus)) {
message(MESS_ERROR, "mail command failed for %s\n", logFile);
rc = 1;
}
if (uncompressCommand) {
waitpid(uncompressChild, &uncompressStatus, 0);
if (!WIFEXITED(uncompressStatus) || WEXITSTATUS(uncompressStatus)) {
message(MESS_ERROR, "uncompress command failed mailing %s\n",
logFile);
rc = 1;
}
}
return rc;
}
static int mailLogWrapper(char *mailFilename, char *mailCommand,
int logNum, struct logInfo *log)
{
/* if the log is compressed (and we're not mailing a
* file whose compression has been delayed), we need
* to uncompress it */
if ((log->flags & LOG_FLAG_COMPRESS) && !(log->flags & LOG_FLAG_DELAYCOMPRESS)) {
if (mailLog(log, mailFilename, mailCommand,
log->uncompress_prog, log->logAddress,
(log->flags & LOG_FLAG_MAILFIRST) ? log->files[logNum] : mailFilename))
return 1;
} else {
if (mailLog(log, mailFilename, mailCommand, NULL,
log->logAddress, mailFilename))
return 1;
}
return 0;
}
/* Use a heuristic to determine whether stat buffer SB comes from a file
with sparse blocks. If the file has fewer blocks than would normally
be needed for a file of its size, then at least one of the blocks in
the file is a hole. In that case, return true. */
static int is_probably_sparse(struct stat const *sb)
{
#if defined(HAVE_STRUCT_STAT_ST_BLOCKS) && defined(HAVE_STRUCT_STAT_ST_BLKSIZE)
return (S_ISREG (sb->st_mode)
&& sb->st_blocks < sb->st_size / sb->st_blksize);
#else
return 0;
#endif
}
#define MIN(a,b) ((a) < (b) ? (a) : (b))
/* Return whether the buffer consists entirely of NULs.
Note the word after the buffer must be non NUL. */
static inline int is_nul (void const *buf, size_t bufsize)
{
char const *cbuf = buf;
char const *cp = buf;
/* Find the first nonzero *byte*, or the sentinel. */
while (*cp++ == 0)
continue;
return cbuf + bufsize < cp;
}
static size_t full_write(int fd, const void *buf, size_t count)
{
size_t total = 0;
const char *ptr = (const char *) buf;
while (count > 0)
{
size_t n_rw;
for (;;)
{
n_rw = write (fd, buf, count);
if (errno == EINTR)
continue;
else
break;
}
if (n_rw == (size_t) -1)
break;
if (n_rw == 0)
break;
total += n_rw;
ptr += n_rw;
count -= n_rw;
}
return total;
}
static int sparse_copy(int src_fd, int dest_fd, struct stat *sb,
const char *saveLog, const char *currLog)
{
int make_holes = is_probably_sparse(sb);
size_t max_n_read = SIZE_MAX;
int last_write_made_hole = 0;
off_t total_n_read = 0;
char buf[BUFSIZ + 1];
while (max_n_read) {
int make_hole = 0;
ssize_t n_read = read (src_fd, buf, MIN (max_n_read, BUFSIZ));
if (n_read < 0) {
if (errno == EINTR) {
continue;
}
message(MESS_ERROR, "error reading %s: %s\n",
currLog, strerror(errno));
return 0;
}
if (n_read == 0)
break;
max_n_read -= n_read;
total_n_read += n_read;
if (make_holes) {
/* Sentinel required by is_nul(). */
buf[n_read] = '\1';
if ((make_hole = is_nul(buf, n_read))) {
if (lseek (dest_fd, n_read, SEEK_CUR) < 0) {
message(MESS_ERROR, "error seeking %s: %s\n",
saveLog, strerror(errno));
return 0;
}
}
}
if (!make_hole) {
size_t n = n_read;
if (full_write (dest_fd, buf, n) != n) {
message(MESS_ERROR, "error writing to %s: %s\n",
saveLog, strerror(errno));
return 0;
}
}
last_write_made_hole = make_hole;
}
if (last_write_made_hole) {
if (ftruncate(dest_fd, total_n_read) < 0) {
message(MESS_ERROR, "error ftruncate %s: %s\n",
saveLog, strerror(errno));
return 0;
}
}
return 1;
}
static int copyTruncate(char *currLog, char *saveLog, struct stat *sb,
int flags)
{
int fdcurr = -1, fdsave = -1;
message(MESS_DEBUG, "copying %s to %s\n", currLog, saveLog);
if (!debug) {
if ((fdcurr = open(currLog, ((flags & LOG_FLAG_COPY) ? O_RDONLY : O_RDWR) | O_NOFOLLOW)) < 0) {
message(MESS_ERROR, "error opening %s: %s\n", currLog,
strerror(errno));
return 1;
}
#ifdef WITH_SELINUX
if (selinux_enabled) {
security_context_t oldContext;
if (fgetfilecon_raw(fdcurr, &oldContext) >= 0) {
if (getfscreatecon_raw(&prev_context) < 0) {
message(MESS_ERROR,
"getting default context: %s\n",
strerror(errno));
if (selinux_enforce) {
freecon(oldContext);
close(fdcurr);
return 1;
}
}
if (setfscreatecon_raw(oldContext) < 0) {
message(MESS_ERROR,
"setting file context %s to %s: %s\n",
saveLog, oldContext, strerror(errno));
if (selinux_enforce) {
freecon(oldContext);
close(fdcurr);
return 1;
}
}
message(MESS_DEBUG, "set default create context\n");
freecon(oldContext);
} else {
if (errno != ENOTSUP) {
message(MESS_ERROR, "getting file context %s: %s\n",
currLog, strerror(errno));
if (selinux_enforce) {
return 1;
}
}
}
}
#endif
#ifdef WITH_ACL
if ((prev_acl = acl_get_fd(fdcurr)) == NULL) {
if (!ACL_NOT_WELL_SUPPORTED(errno)) {
message(MESS_ERROR, "getting file ACL %s: %s\n",
currLog, strerror(errno));
close(fdcurr);
return 1;
}
}
#endif /* WITH_ACL */
fdsave =
createOutputFile(saveLog, O_WRONLY | O_CREAT, sb, prev_acl, 0);
#ifdef WITH_SELINUX
if (selinux_enabled) {
setfscreatecon_raw(prev_context);
freecon(prev_context);
prev_context = NULL;
}
#endif
#ifdef WITH_ACL
if (prev_acl) {
acl_free(prev_acl);
prev_acl = NULL;
}
#endif
if (fdsave < 0) {
close(fdcurr);
return 1;
}
if (sparse_copy(fdcurr, fdsave, sb, saveLog, currLog) != 1) {
close(fdcurr);
close(fdsave);
message(MESS_ERROR, "error copying %s to %s: %s\n", currLog,
saveLog, strerror(errno));
unlink(saveLog);
return 1;
}
}
if (flags & LOG_FLAG_COPYTRUNCATE) {
message(MESS_DEBUG, "truncating %s\n", currLog);
if (!debug) {
fsync(fdsave);
if (ftruncate(fdcurr, 0)) {
message(MESS_ERROR, "error truncating %s: %s\n", currLog,
strerror(errno));
close(fdcurr);
close(fdsave);
return 1;
}
}
} else
message(MESS_DEBUG, "Not truncating %s\n", currLog);
if (fdcurr >= 0) {
close(fdcurr);
}
if (fdsave >= 0) {
close(fdsave);
}
return 0;
}
int findNeedRotating(struct logInfo *log, int logNum, int force)
{