forked from logrotate/logrotate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logrotate.c
3083 lines (2676 loc) · 96.9 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 */
#if !defined(__NetBSD__) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
#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/file.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>
#include <libgen.h>
#if !defined(PATH_MAX) && defined(__FreeBSD__)
#include <sys/param.h>
#endif
#include "log.h"
#include "logrotate.h"
static char *prev_context;
#ifdef WITH_SELINUX
#include <selinux/selinux.h>
static int selinux_enabled = 0;
static int selinux_enforce = 0;
#endif
#ifdef WITH_ACL
#include "sys/acl.h"
#define acl_type acl_t
#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
/* 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 {
size_t prefix_len;
const char *dformat;
};
static struct logStateList {
LIST_HEAD(stateSet, logState) head;
} **states;
int numLogs = 0;
int debug = 0;
static unsigned int hashSize;
static const char *mailCommand = DEFAULT_MAIL_COMMAND;
static time_t nowSecs = 0;
static uid_t save_euid;
static gid_t save_egid;
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 abort on error, so return 1 */
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_tmp;
time_t t1, t2;
const char *r1 = *(char * const*)(result1);
const char *r2 = *(char * const*)(result2);
memset(&time_tmp, 0, sizeof(struct tm));
strptime(r1 + _compData.prefix_len, _compData.dformat, &time_tmp);
t1 = mktime(&time_tmp);
memset(&time_tmp, 0, sizeof(struct tm));
strptime(r2 + _compData.prefix_len, _compData.dformat, &time_tmp);
t2 = mktime(&time_tmp);
if (t1 < t2) return -1;
if (t1 > t2) return 1;
return 0;
}
static void sortGlobResult(glob_t *result, size_t 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, size_t 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 from %u to %u and egid from %u to %u (pid %d)\n",
(unsigned) save_euid, (unsigned) user, (unsigned) save_egid, (unsigned) group, getpid());
if (setegid(group) || seteuid(user)) {
message(MESS_ERROR, "error switching euid from %u to %u and egid from %u to %u (pid %d): %s\n",
(unsigned) save_euid, (unsigned) user, (unsigned) save_egid, (unsigned) group, getpid(),
strerror(errno));
return 1;
}
return 0;
}
static int switch_user_permanently(const struct logInfo *log) {
const gid_t group = getegid();
const uid_t user = geteuid();
if (!(log->flags & LOG_FLAG_SU)) {
return 0;
}
if (user != log->suUid) {
message(MESS_ERROR, "current euid (%u) does not match uid of log configuration (%u) (pid %d)\n",
(unsigned) user, (unsigned) log->suUid, getpid());
return 1;
}
if (group != log->suGid) {
message(MESS_ERROR, "current egid (%u) does not match gid of log configuration (%u) (pid %d)\n",
(unsigned) group, (unsigned) log->suGid, getpid());
return 1;
}
/* we are already the final configuration specified user/group */
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 (pid %d): %s\n",
getpid(), strerror(errno));
return 1;
}
message(MESS_DEBUG, "switching uid to %u and gid to %u permanently (pid %d)\n",
(unsigned) user, (unsigned) group, getpid());
if (setgid(group) || setuid(user)) {
message(MESS_ERROR, "error switching uid to %u and gid to %u (pid %d): %s\n",
(unsigned) user, (unsigned) group, getpid(), strerror(errno));
return 1;
}
if (user != ROOT_UID && setuid(ROOT_UID) != -1) {
message(MESS_ERROR, "failed to switch user permanently, able to switch back (pid %d)\n",
getpid());
return 1;
}
return 0;
}
int switch_user_back(void) {
return switch_user(save_euid, save_egid);
}
static int switch_user_back_permanently(void) {
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
#define HASH_SIZE_MAX 8192
static int allocateHash(unsigned long hs)
{
unsigned int i;
/* Enforce some reasonable minimum hash size */
if (hs < HASH_SIZE_MIN)
hs = HASH_SIZE_MIN;
/* Enforce some reasonable maximum hash size */
if (hs > HASH_SIZE_MAX)
hs = HASH_SIZE_MAX;
message(MESS_DEBUG, "Allocating hash table for state file, size %lu entries\n",
hs);
states = calloc(hs, sizeof(struct logStateList *));
if (states == NULL) {
message_OOM();
return 1;
}
for (i = 0; i < hs; i++) {
states[i] = malloc(sizeof *states[0]);
if (states[i] == NULL) {
message_OOM();
return 1;
}
LIST_INIT(&(states[i]->head));
}
hashSize = (unsigned)hs;
return 0;
}
#define HASH_CONST 13
#if defined(__clang__) && defined(__clang_major__) && (__clang_major__ >= 4)
__attribute__((no_sanitize("unsigned-integer-overflow")))
#endif
static int hashIndex(const char *fn)
{
unsigned hash = 0;
if (!hashSize)
/* hash table not yet allocated */
return -1;
while (*fn) {
hash *= HASH_CONST;
hash += (unsigned char)*fn++;
}
return (int)(hash % hashSize);
}
/* safe implementation of dup2(oldfd, nefd) followed by close(oldfd) */
static int movefd(int oldfd, int newfd)
{
int rc;
if (oldfd == newfd)
/* avoid accidental close of newfd in case it is equal to oldfd */
return 0;
rc = dup2(oldfd, newfd);
if (rc == 0)
close(oldfd);
return rc;
}
static int setSecCtx(int fdSrc, const char *src, char **pPrevCtx)
{
#ifdef WITH_SELINUX
char *srcCtx;
*pPrevCtx = NULL;
if (!selinux_enabled)
/* pretend success */
return 0;
/* read security context of fdSrc */
if (fgetfilecon_raw(fdSrc, &srcCtx) < 0) {
if (errno == ENOTSUP)
/* pretend success */
return 0;
message(MESS_ERROR, "getting file context %s: %s\n", src,
strerror(errno));
return selinux_enforce;
}
/* save default security context for restoreSecCtx() */
if (getfscreatecon_raw(pPrevCtx) < 0) {
message(MESS_ERROR, "getting default context: %s\n", strerror(errno));
return selinux_enforce;
}
/* set default security context to match fdSrc */
if (setfscreatecon_raw(srcCtx) < 0) {
message(MESS_ERROR, "setting default context to %s: %s\n", srcCtx,
strerror(errno));
freecon(srcCtx);
return selinux_enforce;
}
message(MESS_DEBUG, "set default create context to %s\n", srcCtx);
freecon(srcCtx);
#else
(void) fdSrc;
(void) src;
(void) pPrevCtx;
#endif
return 0;
}
static int setSecCtxByName(const char *src, char **pPrevCtx)
{
int hasErrors = 0;
#ifdef WITH_SELINUX
int fd = open(src, O_RDONLY | O_NOFOLLOW);
if (fd < 0) {
message(MESS_ERROR, "error opening %s: %s\n", src, strerror(errno));
return 1;
}
hasErrors = setSecCtx(fd, src, pPrevCtx);
close(fd);
#else
(void) src;
(void) pPrevCtx;
#endif
return hasErrors;
}
static void restoreSecCtx(char **pPrevCtx)
{
#ifdef WITH_SELINUX
if (!*pPrevCtx)
/* no security context saved for restoration */
return;
/* set default security context to the previously stored one */
if (selinux_enabled && setfscreatecon_raw(*pPrevCtx) < 0)
message(MESS_ERROR, "setting default context to %s: %s\n", *pPrevCtx,
strerror(errno));
/* free the memory allocated to save the security context */
freecon(*pPrevCtx);
*pPrevCtx = NULL;
#else
(void) pPrevCtx;
#endif
}
static struct logState *newState(const char *fn)
{
struct tm now;
struct logState *new;
time_t lr_time;
message(MESS_DEBUG, "Creating new state\n");
localtime_r(&nowSecs, &now);
new = malloc(sizeof(*new));
if (new == NULL) {
message_OOM();
return NULL;
}
new->fn = strdup(fn);
if (new->fn == NULL) {
message_OOM();
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);
localtime_r(&lr_time, &new->lastRotated);
return new;
}
static struct logState *findState(const char *fn)
{
const int i = hashIndex(fn);
struct logState *p;
if (i < 0)
/* hash table not yet allocated */
return NULL;
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(const struct logInfo *log, const char *logfn, const char *logrotfn, const char *script)
{
int rc;
pid_t pid;
if (debug) {
message(MESS_DEBUG, "running script with args %s %s: \"%s\"\n",
logfn, logrotfn ? logrotfn : "", script);
return 0;
}
pid = fork();
if (pid == -1) {
message(MESS_ERROR, "cannot fork: %s\n", strerror(errno));
return 1;
}
if (pid == 0) {
if (log->flags & LOG_FLAG_SU) {
if (switch_user_back_permanently() != 0) {
exit(1);
}
}
execl("/bin/sh", "sh", "-c", (char *) script, "logrotate_script", (char *) logfn, (char *) logrotfn, (char *) NULL);
message(MESS_ERROR, "cannot execute sub-shell: %s\n", strerror(errno));
exit(1);
}
wait(&rc);
return rc;
}
#ifdef WITH_ACL
static int is_acl_well_supported(int err)
{
switch (err) {
case ENOTSUP: /* no file system support */
case EINVAL: /* acl does not point to a valid ACL */
case ENOSYS: /* compatibility - acl_(g|s)et_fd(3) should never return this */
case EBUSY: /* compatibility - acl_(g|s)et_fd(3) should never return this */
return 0;
default:
return 1;
}
}
#endif /* WITH_ACL */
static int createOutputFile(const char *fileName, int flags, const struct stat *sb,
acl_type acl, int force_mode)
{
int fd = -1;
struct stat sb_create;
int acl_set = 0;
int i;
for (i = 0; i < 2; ++i) {
struct tm now;
size_t fileName_size, buf_size;
char *backupName, *ptr;
fd = open(fileName, (flags | O_EXCL | O_NOFOLLOW),
(S_IRUSR | S_IWUSR) & sb->st_mode);
if ((fd >= 0) || (errno != EEXIST))
break;
/* the destination file already exists, while it should not */
localtime_r(&nowSecs, &now);
fileName_size = strlen(fileName);
buf_size = fileName_size + sizeof("-YYYYMMDDHH.backup");
backupName = alloca(buf_size);
ptr = backupName;
/* construct backupName starting with fileName */
strcpy(ptr, fileName);
ptr += fileName_size;
buf_size -= fileName_size;
/* append the -YYYYMMDDHH time stamp and the .backup suffix */
ptr += strftime(ptr, buf_size, "-%Y%m%d%H", &now);
strcpy(ptr, ".backup");
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;
}
/* existing file renamed, try it once again */
}
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 %u and gid %u: %s\n",
fileName, (unsigned) sb->st_uid, (unsigned) sb->st_gid, strerror(errno));
close(fd);
return -1;
}
#ifdef WITH_ACL
if (!force_mode && acl) {
if (acl_set_fd(fd, acl) == -1) {
if (is_acl_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;
}
}
#else
(void) acl;
#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 12
/* unlink, but try to call shred from GNU coreutils if LOG_FLAG_SHRED
* is enabled (in that case fd needs to be a valid file descriptor) */
static int shred_file(int fd, const char *filename, const struct logInfo *log)
{
char count[DIGITS]; /* that's a lot of shredding :) */
const char **fullCommand;
int id = 0;
int status;
pid_t pid;
if (log->preremove) {
message(MESS_DEBUG, "running preremove script\n");
if (runScript(log, filename, NULL, 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)) {
goto unlink_file;
}
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;
pid = fork();
if (pid == -1) {
message(MESS_ERROR, "cannot fork: %s\n", strerror(errno));
return 1;
}
if (pid == 0) {
movefd(fd, STDOUT_FILENO);
if (switch_user_permanently(log) != 0) {
exit(1);
}
execvp(fullCommand[0], (void *) fullCommand);
message(MESS_ERROR, "cannot execute shred command: %s\n", strerror(errno));
exit(1);
}
wait(&status);
if (!WIFEXITED(status) || WEXITSTATUS(status)) {
message(MESS_ERROR, "Failed to shred %s, trying unlink\n", filename);
return unlink(filename);
}
/* We have to unlink it after shred anyway,
* because it doesn't remove the file itself */
unlink_file:
if (unlink(filename) == 0)
return 0;
if (errno != ENOENT)
return 1;
/* unlink of log file that no longer exists is not a fatal error */
message(MESS_ERROR, "error unlinking log file %s: %s\n", filename,
strerror(errno));
return 0;
}
static int removeLogFile(const char *name, const struct logInfo *log)
{
int fd = -1;
int result = 0;
message(MESS_DEBUG, "removing old log %s\n", name);
if (log->flags & LOG_FLAG_SHRED) {
fd = open(name, O_RDWR | O_NOFOLLOW);
if (fd < 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));
result = 1;
}
if (fd != -1)
close(fd);
return result;
}
static void setAtimeMtime(const char *filename, const struct stat *sb)
{
/* If we can't change atime/mtime, it's not a disaster. It might
possibly fail under SELinux. But do try to preserve the
fractional part if we have utimensat(). */
#if defined HAVE_UTIMENSAT && !defined(__APPLE__)
struct timespec ts[2];
ts[0] = sb->st_atim;
ts[1] = sb->st_mtim;
utimensat(AT_FDCWD, filename, ts, 0);
#else
struct utimbuf utim;
utim.actime = sb->st_atime;
utim.modtime = sb->st_mtime;
utime(filename, &utim);
#endif
}
static int compressLogFile(const char *name, const struct logInfo *log, const struct stat *sb)
{
char *compressedName;
const char **fullCommand;
int inFile;
int outFile;
int i;
int status;
int compressPipe[2];
char buff[4092];
ssize_t n_read;
int error_printed = 0;
char *prevCtx;
pid_t pid;
message(MESS_DEBUG, "compressing log with: %s\n", log->compress_prog);
if (debug)
return 0;
fullCommand = alloca(sizeof(*fullCommand) *
((unsigned)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: %s\n", name, strerror(errno));
return 1;
}
if (setSecCtx(inFile, name, &prevCtx) != 0) {
/* error msg already printed */
close(inFile);
return 1;
}
#ifdef WITH_ACL
if ((prev_acl = acl_get_fd(inFile)) == NULL) {
if (is_acl_well_supported(errno)) {
message(MESS_ERROR, "getting file ACL %s: %s\n",
name, strerror(errno));
restoreSecCtx(&prevCtx);
close(inFile);
return 1;
}
}
#endif
outFile =
createOutputFile(compressedName, O_RDWR | O_CREAT, sb, prev_acl, 0);
restoreSecCtx(&prevCtx);
#ifdef WITH_ACL
if (prev_acl) {
acl_free(prev_acl);
prev_acl = NULL;
}
#endif
if (outFile < 0) {
close(inFile);
return 1;
}
/* pipe used to capture stderr of the compress process */
if (pipe(compressPipe) < 0) {
message(MESS_ERROR, "error opening pipe for compress: %s\n",
strerror(errno));
close(inFile);
close(outFile);
return 1;
}
pid = fork();
if (pid == -1) {
message(MESS_ERROR, "cannot fork: %s\n", strerror(errno));
close(inFile);
close(outFile);
close(compressPipe[1]);
close(compressPipe[0]);
return 1;
}
if (pid == 0) {
char *envInFilename;
/* close read end of pipe in the child process */
close(compressPipe[0]);
movefd(inFile, STDIN_FILENO);
movefd(outFile, STDOUT_FILENO);
if (switch_user_permanently(log) != 0) {
exit(1);
}
movefd(compressPipe[1], STDERR_FILENO);
envInFilename = alloca(strlen("LOGROTATE_COMPRESSED_FILENAME=") + strlen(name) + 2);
sprintf(envInFilename, "LOGROTATE_COMPRESSED_FILENAME=%s", name);
putenv(envInFilename);
execvp(fullCommand[0], (void *) fullCommand);
message(MESS_ERROR, "cannot execute compress command: %s\n", strerror(errno));
exit(1);
}
/* close write end of pipe in the parent process */
close(compressPipe[1]);
while ((n_read = 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[n_read] = '\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;
}
setAtimeMtime(compressedName, sb);
if (shred_file(inFile, name, log)) {
close(inFile);
return 1;
}
close(inFile);
return 0;
}
static int mailLog(const struct logInfo *log, const char *logFile, const char *mailComm,
const char *uncompressCommand, const char *address, const char *subject)
{
int mailInput;
pid_t mailChild, uncompressChild = 0;
int mailStatus, uncompressStatus;
int uncompressPipe[2];
char * const mailArgv[] = { (char *) mailComm, (char *) "-s", (char *) subject, (char *) 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) {
/* pipe used to capture output of the uncompress process */
if (pipe(uncompressPipe) < 0) {
message(MESS_ERROR, "error opening pipe for uncompress: %s\n",
strerror(errno));
close(mailInput);
return 1;
}
uncompressChild = fork();
if (uncompressChild == -1) {
message(MESS_ERROR, "cannot fork: %s\n", strerror(errno));
close(mailInput);
close(uncompressPipe[1]);
close(uncompressPipe[0]);
return 1;
}
if (uncompressChild == 0) {
/* uncompress child */
/* close read end of pipe in the child process */
close(uncompressPipe[0]);
movefd(mailInput, STDIN_FILENO);
movefd(uncompressPipe[1], STDOUT_FILENO);
if (switch_user_permanently(log) != 0) {
exit(1);
}
execlp(uncompressCommand, uncompressCommand, (char *) NULL);
message(MESS_ERROR, "cannot execute uncompress command: %s\n", strerror(errno));
exit(1);
}
close(mailInput);
mailInput = uncompressPipe[0];
close(uncompressPipe[1]);
}
mailChild = fork();
if (mailChild == -1) {
message(MESS_ERROR, "cannot fork: %s\n", strerror(errno));
close(mailInput);
return 1;
}
if (mailChild == 0) {
movefd(mailInput, STDIN_FILENO);
close(STDOUT_FILENO);
/* mail command runs as root */
if (log->flags & LOG_FLAG_SU) {
if (switch_user_back_permanently() != 0) {
exit(1);
}
}
execvp(mailArgv[0], mailArgv);
message(MESS_ERROR, "cannot execute mail command: %s\n", strerror(errno));
exit(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",