/
newsyslog.c
2781 lines (2516 loc) · 72.5 KB
/
newsyslog.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
/*-
* ------+---------+---------+-------- + --------+---------+---------+---------*
* This file includes significant modifications done by:
* Copyright (c) 2003, 2004 - Garance Alistair Drosehn <gad@FreeBSD.org>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* ------+---------+---------+-------- + --------+---------+---------+---------*
*/
/*
* This file contains changes from the Open Software Foundation.
*/
/*
* Copyright 1988, 1989 by the Massachusetts Institute of Technology
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose and without fee is hereby granted, provided
* that the above copyright notice appear in all copies and that both that
* copyright notice and this permission notice appear in supporting
* documentation, and that the names of M.I.T. and the M.I.T. S.I.P.B. not be
* used in advertising or publicity pertaining to distribution of the
* software without specific, written prior permission. M.I.T. and the M.I.T.
* S.I.P.B. make no representations about the suitability of this software
* for any purpose. It is provided "as is" without express or implied
* warranty.
*
* $FreeBSD: head/usr.sbin/newsyslog/newsyslog.c 327451 2017-12-31 22:01:36Z eadler $
*/
/*
* newsyslog - roll over selected logs at the appropriate time, keeping the a
* specified number of backup files around.
*/
#define OSF
#include <sys/param.h>
#include <sys/queue.h>
#include <sys/stat.h>
#include <sys/user.h>
#include <sys/wait.h>
#include <assert.h>
#include <ctype.h>
#include <err.h>
#include <errno.h>
#include <dirent.h>
#include <fcntl.h>
#include <fnmatch.h>
#include <glob.h>
#include <grp.h>
#include <paths.h>
#include <pwd.h>
#include <signal.h>
#include <stdio.h>
#include <libgen.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <time.h>
#include <unistd.h>
#include "pathnames.h"
#include "extern.h"
/*
* Compression suffixes
*/
#ifndef COMPRESS_SUFFIX_GZ
#define COMPRESS_SUFFIX_GZ ".gz"
#endif
#ifndef COMPRESS_SUFFIX_BZ2
#define COMPRESS_SUFFIX_BZ2 ".bz2"
#endif
#ifndef COMPRESS_SUFFIX_XZ
#define COMPRESS_SUFFIX_XZ ".xz"
#endif
#ifndef COMPRESS_SUFFIX_ZST
#define COMPRESS_SUFFIX_ZST ".zst"
#endif
#define COMPRESS_SUFFIX_MAXLEN MAX(MAX(sizeof(COMPRESS_SUFFIX_GZ),sizeof(COMPRESS_SUFFIX_BZ2)),sizeof(COMPRESS_SUFFIX_XZ))
/*
* Compression types
*/
#define COMPRESS_TYPES 5 /* Number of supported compression types */
#define COMPRESS_NONE 0
#define COMPRESS_GZIP 1
#define COMPRESS_BZIP2 2
#define COMPRESS_XZ 3
#define COMPRESS_ZSTD 4
/*
* Bit-values for the 'flags' parsed from a config-file entry.
*/
#define CE_BINARY 0x0008 /* Logfile is in binary, do not add status */
/* messages to logfile(s) when rotating. */
#define CE_NOSIGNAL 0x0010 /* There is no process to signal when */
/* trimming this file. */
#define CE_TRIMAT 0x0020 /* trim file at a specific time. */
#define CE_GLOB 0x0040 /* name of the log is file name pattern. */
#define CE_SIGNALGROUP 0x0080 /* Signal a process-group instead of a single */
/* process when trimming this file. */
#define CE_CREATE 0x0100 /* Create the log file if it does not exist. */
#define CE_NODUMP 0x0200 /* Set 'nodump' on newly created log file. */
#define CE_PID2CMD 0x0400 /* Replace PID file with a shell command.*/
#define CE_PLAIN0 0x0800 /* Do not compress zero'th history file */
#define CE_RFC5424 0x0800 /* Use RFC5424 format rotation message */
#define MIN_PID 5 /* Don't touch pids lower than this */
#define MAX_PID PID_MAX /* was lower, see /usr/include/sys/proc.h */
#define kbytes(size) (((size) + 1023) >> 10)
#define DEFAULT_MARKER "<default>"
#define DEBUG_MARKER "<debug>"
#define INCLUDE_MARKER "<include>"
#define DEFAULT_TIMEFNAME_FMT "%Y%m%dT%H%M%S"
#define MAX_OLDLOGS 65536 /* Default maximum number of old logfiles */
struct compress_types {
const char *flag; /* Flag in configuration file */
const char *suffix; /* Compression suffix */
const char *path; /* Path to compression program */
char **args; /* Compression program arguments */
};
static char f_arg[] = "-f";
static char q_arg[] = "-q";
static char rm_arg[] = "--rm";
static char *gz_args[] ={ NULL, f_arg, NULL, NULL };
#define bzip2_args gz_args
#define xz_args gz_args
static char *zstd_args[] = { NULL, q_arg, rm_arg, NULL, NULL };
#define ARGS_NUM 4
static const struct compress_types compress_type[COMPRESS_TYPES] = {
{ "", "", "", NULL}, /* none */
{ "Z", COMPRESS_SUFFIX_GZ, _PATH_GZIP, gz_args}, /* gzip */
{ "J", COMPRESS_SUFFIX_BZ2, _PATH_BZIP2, bzip2_args}, /* bzip2 */
{ "X", COMPRESS_SUFFIX_XZ, _PATH_XZ, xz_args }, /* xz */
{ "Y", COMPRESS_SUFFIX_ZST, _PATH_ZSTD, zstd_args } /* zst */
};
struct conf_entry {
STAILQ_ENTRY(conf_entry) cf_nextp;
char *log; /* Name of the log */
char *pid_cmd_file; /* PID or command file */
char *r_reason; /* The reason this file is being rotated */
int firstcreate; /* Creating log for the first time (-C). */
int rotate; /* Non-zero if this file should be rotated */
int fsize; /* size found for the log file */
uid_t uid; /* Owner of log */
gid_t gid; /* Group of log */
int numlogs; /* Number of logs to keep */
int trsize; /* Size cutoff to trigger trimming the log */
int hours; /* Hours between log trimming */
struct ptime_data *trim_at; /* Specific time to do trimming */
unsigned int permissions; /* File permissions on the log */
int flags; /* CE_BINARY */
int compress; /* Compression */
int sig; /* Signal to send */
int def_cfg; /* Using the <default> rule for this file */
};
struct sigwork_entry {
SLIST_ENTRY(sigwork_entry) sw_nextp;
int sw_signum; /* the signal to send */
int sw_pidok; /* true if pid value is valid */
pid_t sw_pid; /* the process id from the PID file */
const char *sw_pidtype; /* "daemon" or "process group" */
int sw_runcmd; /* run command or send PID to signal */
char sw_fname[1]; /* file the PID was read from or shell cmd */
};
struct zipwork_entry {
SLIST_ENTRY(zipwork_entry) zw_nextp;
const struct conf_entry *zw_conf; /* for chown/perm/flag info */
const struct sigwork_entry *zw_swork; /* to know success of signal */
int zw_fsize; /* size of the file to compress */
char zw_fname[1]; /* the file to compress */
};
struct include_entry {
STAILQ_ENTRY(include_entry) inc_nextp;
const char *file; /* Name of file to process */
};
struct oldlog_entry {
char *fname; /* Filename of the log file */
time_t t; /* Parsed timestamp of the logfile */
};
typedef enum {
FREE_ENT, KEEP_ENT
} fk_entry;
STAILQ_HEAD(cflist, conf_entry);
static SLIST_HEAD(swlisthead, sigwork_entry) swhead =
SLIST_HEAD_INITIALIZER(swhead);
static SLIST_HEAD(zwlisthead, zipwork_entry) zwhead =
SLIST_HEAD_INITIALIZER(zwhead);
STAILQ_HEAD(ilist, include_entry);
int dbg_at_times; /* -D Show details of 'trim_at' code */
static int archtodir = 0; /* Archive old logfiles to other directory */
static int createlogs; /* Create (non-GLOB) logfiles which do not */
/* already exist. 1=='for entries with */
/* C flag', 2=='for all entries'. */
int verbose = 0; /* Print out what's going on */
static int needroot = 1; /* Root privs are necessary */
int noaction = 0; /* Don't do anything, just show it */
static int norotate = 0; /* Don't rotate */
static int nosignal; /* Do not send any signals */
static int enforcepid = 0; /* If PID file does not exist or empty, do nothing */
static int force = 0; /* Force the trim no matter what */
static int rotatereq = 0; /* -R = Always rotate the file(s) as given */
/* on the command (this also requires */
/* that a list of files *are* given on */
/* the run command). */
static char *requestor; /* The name given on a -R request */
static char *timefnamefmt = NULL; /* Use time based filenames instead of .0 */
static char *archdirname; /* Directory path to old logfiles archive */
static char *destdir = NULL; /* Directory to treat at root for logs */
static const char *conf; /* Configuration file to use */
struct ptime_data *dbg_timenow; /* A "timenow" value set via -D option */
static struct ptime_data *timenow; /* The time to use for checking at-fields */
#define DAYTIME_LEN 16
static char daytime[DAYTIME_LEN]; /* The current time in human readable form,
* used for rotation-tracking messages. */
/* Another buffer to hold the current time in RFC5424 format. Fractional
* seconds are allowed by the RFC, but are not included in the
* rotation-tracking messages written by newsyslog and so are not accounted for
* in the length below.
*/
#define DAYTIME_RFC5424_LEN sizeof("YYYY-MM-DDTHH:MM:SS+00:00")
static char daytime_rfc5424[DAYTIME_RFC5424_LEN];
static char hostname[MAXHOSTNAMELEN]; /* hostname */
static const char *path_syslogpid = _PATH_SYSLOGPID;
static struct cflist *get_worklist(char **files);
static void parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
struct conf_entry *defconf_p, struct ilist *inclist);
static void add_to_queue(const char *fname, struct ilist *inclist);
static char *sob(char *p);
static char *son(char *p);
static int isnumberstr(const char *);
static int isglobstr(const char *);
static char *missing_field(char *p, char *errline);
static void change_attrs(const char *, const struct conf_entry *);
static const char *get_logfile_suffix(const char *logfile);
static fk_entry do_entry(struct conf_entry *);
static fk_entry do_rotate(const struct conf_entry *);
static void do_sigwork(struct sigwork_entry *);
static void do_zipwork(struct zipwork_entry *);
static struct sigwork_entry *
save_sigwork(const struct conf_entry *);
static struct zipwork_entry *
save_zipwork(const struct conf_entry *, const struct
sigwork_entry *, int, const char *);
static void set_swpid(struct sigwork_entry *, const struct conf_entry *);
static int sizefile(const char *);
static void expand_globs(struct cflist *work_p, struct cflist *glob_p);
static void free_clist(struct cflist *list);
static void free_entry(struct conf_entry *ent);
static struct conf_entry *init_entry(const char *fname,
struct conf_entry *src_entry);
static void parse_args(int argc, char **argv);
static int parse_doption(const char *doption);
static void usage(void) __dead2;
static int log_trim(const char *logname, const struct conf_entry *log_ent);
static int age_old_log(const char *file);
static void savelog(char *from, char *to);
static void createdir(const struct conf_entry *ent, char *dirpart);
static void createlog(const struct conf_entry *ent);
static int parse_signal(const char *str);
/*
* All the following take a parameter of 'int', but expect values in the
* range of unsigned char. Define wrappers which take values of type 'char',
* whether signed or unsigned, and ensure they end up in the right range.
*/
#define isdigitch(Anychar) isdigit((u_char)(Anychar))
#define isprintch(Anychar) isprint((u_char)(Anychar))
#define isspacech(Anychar) isspace((u_char)(Anychar))
#define tolowerch(Anychar) tolower((u_char)(Anychar))
int
main(int argc, char **argv)
{
struct cflist *worklist;
struct conf_entry *p;
struct sigwork_entry *stmp;
struct zipwork_entry *ztmp;
SLIST_INIT(&swhead);
SLIST_INIT(&zwhead);
parse_args(argc, argv);
argc -= optind;
argv += optind;
if (needroot && getuid() && geteuid())
errx(1, "must have root privs");
worklist = get_worklist(argv);
/*
* Rotate all the files which need to be rotated. Note that
* some users have *hundreds* of entries in newsyslog.conf!
*/
while (!STAILQ_EMPTY(worklist)) {
p = STAILQ_FIRST(worklist);
STAILQ_REMOVE_HEAD(worklist, cf_nextp);
if (do_entry(p) == FREE_ENT)
free_entry(p);
}
/*
* Send signals to any processes which need a signal to tell
* them to close and re-open the log file(s) we have rotated.
* Note that zipwork_entries include pointers to these
* sigwork_entry's, so we can not free the entries here.
*/
if (!SLIST_EMPTY(&swhead)) {
if (noaction || verbose)
printf("Signal all daemon process(es)...\n");
SLIST_FOREACH(stmp, &swhead, sw_nextp)
do_sigwork(stmp);
if (!(rotatereq && nosignal)) {
if (noaction)
printf("\tsleep 10\n");
else {
if (verbose)
printf("Pause 10 seconds to allow "
"daemon(s) to close log file(s)\n");
sleep(10);
}
}
}
/*
* Compress all files that we're expected to compress, now
* that all processes should have closed the files which
* have been rotated.
*/
if (!SLIST_EMPTY(&zwhead)) {
if (noaction || verbose)
printf("Compress all rotated log file(s)...\n");
while (!SLIST_EMPTY(&zwhead)) {
ztmp = SLIST_FIRST(&zwhead);
do_zipwork(ztmp);
SLIST_REMOVE_HEAD(&zwhead, zw_nextp);
free(ztmp);
}
}
/* Now free all the sigwork entries. */
while (!SLIST_EMPTY(&swhead)) {
stmp = SLIST_FIRST(&swhead);
SLIST_REMOVE_HEAD(&swhead, sw_nextp);
free(stmp);
}
while (wait(NULL) > 0 || errno == EINTR)
;
return (0);
}
static struct conf_entry *
init_entry(const char *fname, struct conf_entry *src_entry)
{
struct conf_entry *tempwork;
if (verbose > 4)
printf("\t--> [creating entry for %s]\n", fname);
tempwork = malloc(sizeof(struct conf_entry));
if (tempwork == NULL)
err(1, "malloc of conf_entry for %s", fname);
if (destdir == NULL || fname[0] != '/')
tempwork->log = strdup(fname);
else
asprintf(&tempwork->log, "%s%s", destdir, fname);
if (tempwork->log == NULL)
err(1, "strdup for %s", fname);
if (src_entry != NULL) {
tempwork->pid_cmd_file = NULL;
if (src_entry->pid_cmd_file)
tempwork->pid_cmd_file = strdup(src_entry->pid_cmd_file);
tempwork->r_reason = NULL;
tempwork->firstcreate = 0;
tempwork->rotate = 0;
tempwork->fsize = -1;
tempwork->uid = src_entry->uid;
tempwork->gid = src_entry->gid;
tempwork->numlogs = src_entry->numlogs;
tempwork->trsize = src_entry->trsize;
tempwork->hours = src_entry->hours;
tempwork->trim_at = NULL;
if (src_entry->trim_at != NULL)
tempwork->trim_at = ptime_init(src_entry->trim_at);
tempwork->permissions = src_entry->permissions;
tempwork->flags = src_entry->flags;
tempwork->compress = src_entry->compress;
tempwork->sig = src_entry->sig;
tempwork->def_cfg = src_entry->def_cfg;
} else {
/* Initialize as a "do-nothing" entry */
tempwork->pid_cmd_file = NULL;
tempwork->r_reason = NULL;
tempwork->firstcreate = 0;
tempwork->rotate = 0;
tempwork->fsize = -1;
tempwork->uid = (uid_t)-1;
tempwork->gid = (gid_t)-1;
tempwork->numlogs = 1;
tempwork->trsize = -1;
tempwork->hours = -1;
tempwork->trim_at = NULL;
tempwork->permissions = 0;
tempwork->flags = 0;
tempwork->compress = COMPRESS_NONE;
tempwork->sig = SIGHUP;
tempwork->def_cfg = 0;
}
return (tempwork);
}
static void
free_entry(struct conf_entry *ent)
{
if (ent == NULL)
return;
if (ent->log != NULL) {
if (verbose > 4)
printf("\t--> [freeing entry for %s]\n", ent->log);
free(ent->log);
ent->log = NULL;
}
if (ent->pid_cmd_file != NULL) {
free(ent->pid_cmd_file);
ent->pid_cmd_file = NULL;
}
if (ent->r_reason != NULL) {
free(ent->r_reason);
ent->r_reason = NULL;
}
if (ent->trim_at != NULL) {
ptime_free(ent->trim_at);
ent->trim_at = NULL;
}
free(ent);
}
static void
free_clist(struct cflist *list)
{
struct conf_entry *ent;
while (!STAILQ_EMPTY(list)) {
ent = STAILQ_FIRST(list);
STAILQ_REMOVE_HEAD(list, cf_nextp);
free_entry(ent);
}
free(list);
list = NULL;
}
static fk_entry
do_entry(struct conf_entry * ent)
{
#define REASON_MAX 80
int modtime;
fk_entry free_or_keep;
double diffsecs;
char temp_reason[REASON_MAX];
int oversized;
free_or_keep = FREE_ENT;
if (verbose)
printf("%s <%d%s>: ", ent->log, ent->numlogs,
compress_type[ent->compress].flag);
ent->fsize = sizefile(ent->log);
oversized = ((ent->trsize > 0) && (ent->fsize >= ent->trsize));
modtime = age_old_log(ent->log);
ent->rotate = 0;
ent->firstcreate = 0;
if (ent->fsize < 0) {
/*
* If either the C flag or the -C option was specified,
* and if we won't be creating the file, then have the
* verbose message include a hint as to why the file
* will not be created.
*/
temp_reason[0] = '\0';
if (createlogs > 1)
ent->firstcreate = 1;
else if ((ent->flags & CE_CREATE) && createlogs)
ent->firstcreate = 1;
else if (ent->flags & CE_CREATE)
strlcpy(temp_reason, " (no -C option)", REASON_MAX);
else if (createlogs)
strlcpy(temp_reason, " (no C flag)", REASON_MAX);
if (ent->firstcreate) {
if (verbose)
printf("does not exist -> will create.\n");
createlog(ent);
} else if (verbose) {
printf("does not exist, skipped%s.\n", temp_reason);
}
} else {
if (ent->flags & CE_TRIMAT && !force && !rotatereq &&
!oversized) {
diffsecs = ptimeget_diff(timenow, ent->trim_at);
if (diffsecs < 0.0) {
/* trim_at is some time in the future. */
if (verbose) {
ptime_adjust4dst(ent->trim_at,
timenow);
printf("--> will trim at %s",
ptimeget_ctime(ent->trim_at));
}
return (free_or_keep);
} else if (diffsecs >= 3600.0) {
/*
* trim_at is more than an hour in the past,
* so find the next valid trim_at time, and
* tell the user what that will be.
*/
if (verbose && dbg_at_times)
printf("\n\t--> prev trim at %s\t",
ptimeget_ctime(ent->trim_at));
if (verbose) {
ptimeset_nxtime(ent->trim_at);
printf("--> will trim at %s",
ptimeget_ctime(ent->trim_at));
}
return (free_or_keep);
} else if (verbose && noaction && dbg_at_times) {
/*
* If we are just debugging at-times, then
* a detailed message is helpful. Also
* skip "doing" any commands, since they
* would all be turned off by no-action.
*/
printf("\n\t--> timematch at %s",
ptimeget_ctime(ent->trim_at));
return (free_or_keep);
} else if (verbose && ent->hours <= 0) {
printf("--> time is up\n");
}
}
if (verbose && (ent->trsize > 0))
printf("size (Kb): %d [%d] ", ent->fsize, ent->trsize);
if (verbose && (ent->hours > 0))
printf(" age (hr): %d [%d] ", modtime, ent->hours);
/*
* Figure out if this logfile needs to be rotated.
*/
temp_reason[0] = '\0';
if (rotatereq) {
ent->rotate = 1;
snprintf(temp_reason, REASON_MAX, " due to -R from %s",
requestor);
} else if (force) {
ent->rotate = 1;
snprintf(temp_reason, REASON_MAX, " due to -F request");
} else if (oversized) {
ent->rotate = 1;
snprintf(temp_reason, REASON_MAX, " due to size>%dK",
ent->trsize);
} else if (ent->hours <= 0 && (ent->flags & CE_TRIMAT)) {
ent->rotate = 1;
} else if ((ent->hours > 0) && ((modtime >= ent->hours) ||
(modtime < 0))) {
ent->rotate = 1;
}
/*
* If the file needs to be rotated, then rotate it.
*/
if (ent->rotate && !norotate) {
if (temp_reason[0] != '\0')
ent->r_reason = strdup(temp_reason);
if (verbose)
printf("--> trimming log....\n");
if (noaction && !verbose)
printf("%s <%d%s>: trimming\n", ent->log,
ent->numlogs,
compress_type[ent->compress].flag);
free_or_keep = do_rotate(ent);
} else {
if (verbose)
printf("--> skipping\n");
}
}
return (free_or_keep);
#undef REASON_MAX
}
static void
parse_args(int argc, char **argv)
{
int ch;
char *p;
timenow = ptime_init(NULL);
ptimeset_time(timenow, time(NULL));
strlcpy(daytime, ptimeget_ctime(timenow) + 4, DAYTIME_LEN);
ptimeget_ctime_rfc5424(timenow, daytime_rfc5424, DAYTIME_RFC5424_LEN);
/* Let's get our hostname */
gethostname(hostname, sizeof(hostname));
/* Truncate domain */
if ((p = strchr(hostname, '.')) != NULL)
*p = '\0';
/* Parse command line options. */
while ((ch = getopt(argc, argv, "a:d:f:nrst:vCD:FNPR:S:")) != -1)
switch (ch) {
case 'a':
archtodir++;
archdirname = optarg;
break;
case 'd':
destdir = optarg;
break;
case 'f':
conf = optarg;
break;
case 'n':
noaction++;
/* FALLTHROUGH */
case 'r':
needroot = 0;
break;
case 's':
nosignal = 1;
break;
case 't':
if (optarg[0] == '\0' ||
strcmp(optarg, "DEFAULT") == 0)
timefnamefmt = strdup(DEFAULT_TIMEFNAME_FMT);
else
timefnamefmt = strdup(optarg);
break;
case 'v':
verbose++;
break;
case 'C':
/* Useful for things like rc.diskless... */
createlogs++;
break;
case 'D':
/*
* Set some debugging option. The specific option
* depends on the value of optarg. These options
* may come and go without notice or documentation.
*/
if (parse_doption(optarg))
break;
usage();
/* NOTREACHED */
case 'F':
force++;
break;
case 'N':
norotate++;
break;
case 'P':
enforcepid++;
break;
case 'R':
rotatereq++;
requestor = strdup(optarg);
break;
case 'S':
path_syslogpid = optarg;
break;
case 'm': /* Used by OpenBSD for "monitor mode" */
default:
usage();
/* NOTREACHED */
}
if (force && norotate) {
warnx("Only one of -F and -N may be specified.");
usage();
/* NOTREACHED */
}
if (rotatereq) {
if (optind == argc) {
warnx("At least one filename must be given when -R is specified.");
usage();
/* NOTREACHED */
}
/* Make sure "requestor" value is safe for a syslog message. */
for (p = requestor; *p != '\0'; p++) {
if (!isprintch(*p) && (*p != '\t'))
*p = '.';
}
}
if (dbg_timenow) {
/*
* Note that the 'daytime' variable is not changed.
* That is only used in messages that track when a
* logfile is rotated, and if a file *is* rotated,
* then it will still rotated at the "real now" time.
*/
ptime_free(timenow);
timenow = dbg_timenow;
fprintf(stderr, "Debug: Running as if TimeNow is %s",
ptimeget_ctime(dbg_timenow));
}
}
/*
* These debugging options are mainly meant for developer use, such
* as writing regression-tests. They would not be needed by users
* during normal operation of newsyslog...
*/
static int
parse_doption(const char *doption)
{
const char TN[] = "TN=";
int res;
if (strncmp(doption, TN, sizeof(TN) - 1) == 0) {
/*
* The "TimeNow" debugging option. This might be off
* by an hour when crossing a timezone change.
*/
dbg_timenow = ptime_init(NULL);
res = ptime_relparse(dbg_timenow, PTM_PARSE_ISO8601,
time(NULL), doption + sizeof(TN) - 1);
if (res == -2) {
warnx("Non-existent time specified on -D %s", doption);
return (0); /* failure */
} else if (res < 0) {
warnx("Malformed time given on -D %s", doption);
return (0); /* failure */
}
return (1); /* successfully parsed */
}
if (strcmp(doption, "ats") == 0) {
dbg_at_times++;
return (1); /* successfully parsed */
}
/* XXX - This check could probably be dropped. */
if ((strcmp(doption, "neworder") == 0) || (strcmp(doption, "oldorder")
== 0)) {
warnx("NOTE: newsyslog always uses 'neworder'.");
return (1); /* successfully parsed */
}
warnx("Unknown -D (debug) option: '%s'", doption);
return (0); /* failure */
}
static void
usage(void)
{
fprintf(stderr,
"usage: newsyslog [-CFNPnrsv] [-a directory] [-d directory] [-f config_file]\n"
" [-S pidfile] [-t timefmt] [[-R tagname] file ...]\n");
exit(1);
}
/*
* Parse a configuration file and return a linked list of all the logs
* which should be processed.
*/
static struct cflist *
get_worklist(char **files)
{
FILE *f;
char **given;
struct cflist *cmdlist, *filelist, *globlist;
struct conf_entry *defconf, *dupent, *ent;
struct ilist inclist;
struct include_entry *inc;
int gmatch, fnres;
defconf = NULL;
STAILQ_INIT(&inclist);
filelist = malloc(sizeof(struct cflist));
if (filelist == NULL)
err(1, "malloc of filelist");
STAILQ_INIT(filelist);
globlist = malloc(sizeof(struct cflist));
if (globlist == NULL)
err(1, "malloc of globlist");
STAILQ_INIT(globlist);
inc = malloc(sizeof(struct include_entry));
if (inc == NULL)
err(1, "malloc of inc");
inc->file = conf;
if (inc->file == NULL)
inc->file = _PATH_CONF;
STAILQ_INSERT_TAIL(&inclist, inc, inc_nextp);
STAILQ_FOREACH(inc, &inclist, inc_nextp) {
if (strcmp(inc->file, "-") != 0)
f = fopen(inc->file, "r");
else {
f = stdin;
inc->file = "<stdin>";
}
if (!f)
err(1, "%s", inc->file);
if (verbose)
printf("Processing %s\n", inc->file);
parse_file(f, filelist, globlist, defconf, &inclist);
fclose(f);
}
/*
* All config-file information has been read in and turned into
* a filelist and a globlist. If there were no specific files
* given on the run command, then the only thing left to do is to
* call a routine which finds all files matched by the globlist
* and adds them to the filelist. Then return the worklist.
*/
if (*files == NULL) {
expand_globs(filelist, globlist);
free_clist(globlist);
if (defconf != NULL)
free_entry(defconf);
return (filelist);
/* NOTREACHED */
}
/*
* If newsyslog was given a specific list of files to process,
* it may be that some of those files were not listed in any
* config file. Those unlisted files should get the default
* rotation action. First, create the default-rotation action
* if none was found in a system config file.
*/
if (defconf == NULL) {
defconf = init_entry(DEFAULT_MARKER, NULL);
defconf->numlogs = 3;
defconf->trsize = 50;
defconf->permissions = S_IRUSR|S_IWUSR;
}
/*
* If newsyslog was run with a list of specific filenames,
* then create a new worklist which has only those files in
* it, picking up the rotation-rules for those files from
* the original filelist.
*
* XXX - Note that this will copy multiple rules for a single
* logfile, if multiple entries are an exact match for
* that file. That matches the historic behavior, but do
* we want to continue to allow it? If so, it should
* probably be handled more intelligently.
*/
cmdlist = malloc(sizeof(struct cflist));
if (cmdlist == NULL)
err(1, "malloc of cmdlist");
STAILQ_INIT(cmdlist);
for (given = files; *given; ++given) {
/*
* First try to find exact-matches for this given file.
*/
gmatch = 0;
STAILQ_FOREACH(ent, filelist, cf_nextp) {
if (strcmp(ent->log, *given) == 0) {
gmatch++;
dupent = init_entry(*given, ent);
STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
}
}
if (gmatch) {
if (verbose > 2)
printf("\t+ Matched entry %s\n", *given);
continue;
}
/*
* There was no exact-match for this given file, so look
* for a "glob" entry which does match.
*/
gmatch = 0;
if (verbose > 2 && globlist != NULL)
printf("\t+ Checking globs for %s\n", *given);
STAILQ_FOREACH(ent, globlist, cf_nextp) {
fnres = fnmatch(ent->log, *given, FNM_PATHNAME);
if (verbose > 2)
printf("\t+ = %d for pattern %s\n", fnres,
ent->log);
if (fnres == 0) {
gmatch++;
dupent = init_entry(*given, ent);
/* This new entry is not a glob! */
dupent->flags &= ~CE_GLOB;
STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
/* Only allow a match to one glob-entry */
break;
}
}
if (gmatch) {
if (verbose > 2)
printf("\t+ Matched %s via %s\n", *given,
ent->log);
continue;
}
/*
* This given file was not found in any config file, so
* add a worklist item based on the default entry.
*/
if (verbose > 2)
printf("\t+ No entry matched %s (will use %s)\n",
*given, DEFAULT_MARKER);
dupent = init_entry(*given, defconf);
/* Mark that it was *not* found in a config file */
dupent->def_cfg = 1;
STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
}
/*
* Free all the entries in the original work list, the list of
* glob entries, and the default entry.
*/
free_clist(filelist);
free_clist(globlist);
free_entry(defconf);
/* And finally, return a worklist which matches the given files. */
return (cmdlist);
}
/*
* Expand the list of entries with filename patterns, and add all files
* which match those glob-entries onto the worklist.
*/
static void
expand_globs(struct cflist *work_p, struct cflist *glob_p)
{
int gmatch, gres;
size_t i;