1 /*-
2 * ------+---------+---------+-------- + --------+---------+---------+---------*
3 * This file includes significant modifications done by:
4 * Copyright (c) 2003, 2004 - Garance Alistair Drosehn <gad@FreeBSD.org>.
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 *
28 * ------+---------+---------+-------- + --------+---------+---------+---------*
29 */
30
31 /*
32 * This file contains changes from the Open Software Foundation.
33 */
34
35 /*
36 * Copyright 1988, 1989 by the Massachusetts Institute of Technology
37 *
38 * Permission to use, copy, modify, and distribute this software and its
39 * documentation for any purpose and without fee is hereby granted, provided
40 * that the above copyright notice appear in all copies and that both that
41 * copyright notice and this permission notice appear in supporting
42 * documentation, and that the names of M.I.T. and the M.I.T. S.I.P.B. not be
43 * used in advertising or publicity pertaining to distribution of the
44 * software without specific, written prior permission. M.I.T. and the M.I.T.
45 * S.I.P.B. make no representations about the suitability of this software
46 * for any purpose. It is provided "as is" without express or implied
47 * warranty.
48 *
49 */
50
51 /*
52 * newsyslog - roll over selected logs at the appropriate time, keeping the a
53 * specified number of backup files around.
54 */
55
56 #include <sys/cdefs.h>
57 #define OSF
58
59 #include <sys/param.h>
60 #include <sys/queue.h>
61 #include <sys/sbuf.h>
62 #include <sys/stat.h>
63 #include <sys/wait.h>
64
65 #include <assert.h>
66 #include <ctype.h>
67 #include <err.h>
68 #include <errno.h>
69 #include <dirent.h>
70 #include <fcntl.h>
71 #include <fnmatch.h>
72 #include <glob.h>
73 #include <grp.h>
74 #include <paths.h>
75 #include <pwd.h>
76 #include <signal.h>
77 #include <stdbool.h>
78 #include <stdio.h>
79 #include <libgen.h>
80 #include <libutil.h>
81 #include <stdlib.h>
82 #include <string.h>
83 #include <syslog.h>
84 #include <time.h>
85 #include <unistd.h>
86
87 #include "pathnames.h"
88 #include "extern.h"
89
90 /*
91 * Compression types
92 */
93 enum compress_types_enum {
94 COMPRESS_NONE = 0,
95 COMPRESS_GZIP = 1,
96 COMPRESS_BZIP2 = 2,
97 COMPRESS_XZ = 3,
98 COMPRESS_ZSTD = 4,
99 COMPRESS_LEGACY = 5, /* Special: use legacy type */
100 COMPRESS_TYPES = COMPRESS_LEGACY /* Number of supported compression types */
101 };
102
103 /*
104 * Bit-values for the 'flags' parsed from a config-file entry.
105 */
106 #define CE_BINARY 0x0008 /* Logfile is in binary, do not add status */
107 /* messages to logfile(s) when rotating. */
108 #define CE_NOSIGNAL 0x0010 /* There is no process to signal when */
109 /* trimming this file. */
110 #define CE_TRIMAT 0x0020 /* trim file at a specific time. */
111 #define CE_GLOB 0x0040 /* name of the log is file name pattern. */
112 #define CE_SIGNALGROUP 0x0080 /* Signal a process-group instead of a single */
113 /* process when trimming this file. */
114 #define CE_CREATE 0x0100 /* Create the log file if it does not exist. */
115 #define CE_NODUMP 0x0200 /* Set 'nodump' on newly created log file. */
116 #define CE_PID2CMD 0x0400 /* Replace PID file with a shell command.*/
117 #define CE_PLAIN0 0x0800 /* Do not compress zero'th history file */
118 #define CE_RFC5424 0x1000 /* Use RFC5424 format rotation message */
119 #define CE_NOEMPTY 0x2000 /* Do not rotate the file when its size */
120 /* is zero */
121 #define MIN_PID 5 /* Don't touch pids lower than this */
122 #define MAX_PID 99999 /* was lower, see /usr/include/sys/proc.h */
123
124 #define kbytes(size) (((size) + 1023) >> 10)
125
126 #define DEFAULT_MARKER "<default>"
127 #define DEBUG_MARKER "<debug>"
128 #define INCLUDE_MARKER "<include>"
129 #define COMPRESS_MARKER "<compress>"
130 #define DEFAULT_TIMEFNAME_FMT "%Y%m%dT%H%M%S"
131
132 #define MAX_OLDLOGS 65536 /* Default maximum number of old logfiles */
133
134 struct compress_types {
135 const char *name; /* Name of compression type */
136 const char *flag; /* Flag in configuration file */
137 const char *suffix; /* Compression suffix */
138 const char *path; /* Path to compression program */
139 const char **flags; /* Compression program flags */
140 int nflags; /* Program flags count */
141 };
142
143 static const char *gzip_flags[] = { "-f" };
144 #define bzip2_flags gzip_flags
145 #define xz_flags gzip_flags
146 static const char *zstd_flags[] = { "-q", "-T0", "--adapt", "--long", "--rm" };
147
148 static struct compress_types compress_type[COMPRESS_TYPES] = {
149 [COMPRESS_NONE] = {
150 .name = "none", .flag = "", .suffix = "",
151 .path = "", .flags = NULL, .nflags = 0
152 },
153 [COMPRESS_GZIP] = {
154 .name = "gzip", .flag = "Z", .suffix = ".gz",
155 .path = _PATH_GZIP, .flags = gzip_flags, .nflags = nitems(gzip_flags)
156 },
157 [COMPRESS_BZIP2] = {
158 .name = "bzip2", .flag = "J", .suffix = ".bz2",
159 .path = _PATH_BZIP2, .flags = bzip2_flags, .nflags = nitems(bzip2_flags)
160 },
161 [COMPRESS_XZ] = {
162 .name = "xz", .flag = "X", .suffix = ".xz",
163 .path = _PATH_XZ, .flags = xz_flags, .nflags = nitems(xz_flags)
164 },
165 [COMPRESS_ZSTD] = {
166 .name = "zstd", .flag = "Y", .suffix = ".zst",
167 .path = _PATH_ZSTD, .flags = zstd_flags, .nflags = nitems(zstd_flags)
168 },
169 };
170
171 struct conf_entry {
172 STAILQ_ENTRY(conf_entry) cf_nextp;
173 char *log; /* Name of the log */
174 char *pid_cmd_file; /* PID or command file */
175 char *r_reason; /* The reason this file is being rotated */
176 int firstcreate; /* Creating log for the first time (-C). */
177 int rotate; /* Non-zero if this file should be rotated */
178 int fsize; /* size found for the log file */
179 uid_t uid; /* Owner of log */
180 gid_t gid; /* Group of log */
181 int numlogs; /* Number of logs to keep */
182 int trsize; /* Size cutoff to trigger trimming the log */
183 int hours; /* Hours between log trimming */
184 struct ptime_data *trim_at; /* Specific time to do trimming */
185 unsigned int permissions; /* File permissions on the log */
186 int flags; /* CE_BINARY */
187 int compress; /* Compression */
188 int sig; /* Signal to send */
189 int def_cfg; /* Using the <default> rule for this file */
190 };
191
192 struct sigwork_entry {
193 SLIST_ENTRY(sigwork_entry) sw_nextp;
194 int sw_signum; /* the signal to send */
195 int sw_pidok; /* true if pid value is valid */
196 pid_t sw_pid; /* the process id from the PID file */
197 const char *sw_pidtype; /* "daemon" or "process group" */
198 int sw_runcmd; /* run command or send PID to signal */
199 char sw_fname[1]; /* file the PID was read from or shell cmd */
200 };
201
202 struct zipwork_entry {
203 SLIST_ENTRY(zipwork_entry) zw_nextp;
204 const struct conf_entry *zw_conf; /* for chown/perm/flag info */
205 const struct sigwork_entry *zw_swork; /* to know success of signal */
206 int zw_fsize; /* size of the file to compress */
207 char zw_fname[1]; /* the file to compress */
208 };
209
210 struct include_entry {
211 STAILQ_ENTRY(include_entry) inc_nextp;
212 const char *file; /* Name of file to process */
213 };
214
215 struct oldlog_entry {
216 char *fname; /* Filename of the log file */
217 time_t t; /* Parsed timestamp of the logfile */
218 };
219
220 typedef enum {
221 FREE_ENT, KEEP_ENT
222 } fk_entry;
223
224 STAILQ_HEAD(cflist, conf_entry);
225 static SLIST_HEAD(swlisthead, sigwork_entry) swhead =
226 SLIST_HEAD_INITIALIZER(swhead);
227 static SLIST_HEAD(zwlisthead, zipwork_entry) zwhead =
228 SLIST_HEAD_INITIALIZER(zwhead);
229 STAILQ_HEAD(ilist, include_entry);
230
231 int dbg_at_times; /* -D Show details of 'trim_at' code */
232
233 static int archtodir = 0; /* Archive old logfiles to other directory */
234 static int createlogs; /* Create (non-GLOB) logfiles which do not */
235 /* already exist. 1=='for entries with */
236 /* C flag', 2=='for all entries'. */
237 int verbose = 0; /* Print out what's going on */
238 static int needroot = 1; /* Root privs are necessary */
239 int noaction = 0; /* Don't do anything, just show it */
240 static int norotate = 0; /* Don't rotate */
241 static int nosignal; /* Do not send any signals */
242 static int enforcepid = 0; /* If PID file does not exist or empty, do nothing */
243 static int force = 0; /* Force the trim no matter what */
244 static int defsignal = SIGHUP; /* -I Signal to send by default */
245 static int rotatereq = 0; /* -R = Always rotate the file(s) as given */
246 /* on the command (this also requires */
247 /* that a list of files *are* given on */
248 /* the run command). */
249 static char *requestor; /* The name given on a -R request */
250 static char *timefnamefmt = NULL;/* Use time based filenames instead of .0 */
251 static char *archdirname; /* Directory path to old logfiles archive */
252 static char *destdir = NULL; /* Directory to treat at root for logs */
253 static const char *conf; /* Configuration file to use */
254 static enum compress_types_enum compress_type_override = COMPRESS_LEGACY; /* Compression type */
255 static bool compress_type_set = false;
256 static bool compress_type_seen = false;
257
258 struct ptime_data *dbg_timenow; /* A "timenow" value set via -D option */
259 static struct ptime_data *timenow; /* The time to use for checking at-fields */
260
261 #define DAYTIME_LEN 16
262 static char daytime[DAYTIME_LEN];/* The current time in human readable form,
263 * used for rotation-tracking messages. */
264
265 /* Another buffer to hold the current time in RFC5424 format. Fractional
266 * seconds are allowed by the RFC, but are not included in the
267 * rotation-tracking messages written by newsyslog and so are not accounted for
268 * in the length below.
269 */
270 #define DAYTIME_RFC5424_LEN sizeof("YYYY-MM-DDTHH:MM:SS+00:00")
271 static char daytime_rfc5424[DAYTIME_RFC5424_LEN];
272
273 static char hostname[MAXHOSTNAMELEN]; /* hostname */
274 static size_t hostname_shortlen;
275
276 static const char *path_syslogpid = _PATH_SYSLOGPID;
277
278 static struct cflist *get_worklist(char **files);
279 static void parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
280 struct conf_entry **defconf, struct ilist *inclist);
281 static void add_to_queue(const char *fname, struct ilist *inclist);
282 static char *sob(char *p);
283 static char *son(char *p);
284 static int isnumberstr(const char *);
285 static int isglobstr(const char *);
286 static char *missing_field(char *p, char *errline);
287 static void change_attrs(const char *, const struct conf_entry *);
288 static const char *get_logfile_suffix(const char *logfile);
289 static fk_entry do_entry(struct conf_entry *);
290 static fk_entry do_rotate(const struct conf_entry *);
291 static void do_sigwork(struct sigwork_entry *);
292 static void do_zipwork(struct zipwork_entry *);
293 static struct sigwork_entry *
294 save_sigwork(const struct conf_entry *);
295 static struct zipwork_entry *
296 save_zipwork(const struct conf_entry *, const struct
297 sigwork_entry *, int, const char *);
298 static void set_swpid(struct sigwork_entry *, const struct conf_entry *);
299 static int sizefile(const char *);
300 static void expand_globs(struct cflist *work_p, struct cflist *glob_p);
301 static void free_clist(struct cflist *list);
302 static void free_entry(struct conf_entry *ent);
303 static struct conf_entry *init_entry(const char *fname,
304 struct conf_entry *src_entry);
305 static void parse_args(int argc, char **argv);
306 static int parse_doption(const char *doption);
307 static void usage(void) __dead2;
308 static int log_trim(const char *logname, const struct conf_entry *log_ent);
309 static int age_old_log(const char *file);
310 static void savelog(char *from, char *to);
311 static void createdir(const struct conf_entry *ent, char *dirpart);
312 static void createlog(const struct conf_entry *ent);
313
314 /*
315 * All the following take a parameter of 'int', but expect values in the
316 * range of unsigned char. Define wrappers which take values of type 'char',
317 * whether signed or unsigned, and ensure they end up in the right range.
318 */
319 #define isdigitch(Anychar) isdigit((u_char)(Anychar))
320 #define isprintch(Anychar) isprint((u_char)(Anychar))
321 #define isspacech(Anychar) isspace((u_char)(Anychar))
322 #define tolowerch(Anychar) tolower((u_char)(Anychar))
323
324 int
main(int argc,char ** argv)325 main(int argc, char **argv)
326 {
327 struct cflist *worklist;
328 struct conf_entry *p;
329 struct sigwork_entry *stmp;
330 struct zipwork_entry *ztmp;
331
332 SLIST_INIT(&swhead);
333 SLIST_INIT(&zwhead);
334
335 parse_args(argc, argv);
336 argc -= optind;
337 argv += optind;
338
339 if (needroot && getuid() && geteuid())
340 errx(1, "must have root privs");
341 worklist = get_worklist(argv);
342
343 /*
344 * Rotate all the files which need to be rotated. Note that
345 * some users have *hundreds* of entries in newsyslog.conf!
346 */
347 while (!STAILQ_EMPTY(worklist)) {
348 p = STAILQ_FIRST(worklist);
349 STAILQ_REMOVE_HEAD(worklist, cf_nextp);
350 if (do_entry(p) == FREE_ENT)
351 free_entry(p);
352 }
353
354 /*
355 * Send signals to any processes which need a signal to tell
356 * them to close and re-open the log file(s) we have rotated.
357 * Note that zipwork_entries include pointers to these
358 * sigwork_entry's, so we can not free the entries here.
359 */
360 if (!SLIST_EMPTY(&swhead)) {
361 if (noaction || verbose)
362 printf("Signal all daemon process(es)...\n");
363 SLIST_FOREACH(stmp, &swhead, sw_nextp)
364 do_sigwork(stmp);
365 if (!(rotatereq && nosignal)) {
366 if (noaction)
367 printf("\tsleep 10\n");
368 else {
369 if (verbose)
370 printf("Pause 10 seconds to allow "
371 "daemon(s) to close log file(s)\n");
372 sleep(10);
373 }
374 }
375 }
376 /*
377 * Compress all files that we're expected to compress, now
378 * that all processes should have closed the files which
379 * have been rotated.
380 */
381 if (!SLIST_EMPTY(&zwhead)) {
382 if (noaction || verbose)
383 printf("Compress all rotated log file(s)...\n");
384 while (!SLIST_EMPTY(&zwhead)) {
385 ztmp = SLIST_FIRST(&zwhead);
386 do_zipwork(ztmp);
387 SLIST_REMOVE_HEAD(&zwhead, zw_nextp);
388 free(ztmp);
389 }
390 }
391 /* Now free all the sigwork entries. */
392 while (!SLIST_EMPTY(&swhead)) {
393 stmp = SLIST_FIRST(&swhead);
394 SLIST_REMOVE_HEAD(&swhead, sw_nextp);
395 free(stmp);
396 }
397
398 while (wait(NULL) > 0 || errno == EINTR)
399 ;
400 return (0);
401 }
402
403 static struct conf_entry *
init_entry(const char * fname,struct conf_entry * src_entry)404 init_entry(const char *fname, struct conf_entry *src_entry)
405 {
406 struct conf_entry *tempwork;
407
408 if (verbose > 4)
409 printf("\t--> [creating entry for %s]\n", fname);
410
411 tempwork = malloc(sizeof(struct conf_entry));
412 if (tempwork == NULL)
413 err(1, "malloc of conf_entry for %s", fname);
414
415 if (destdir == NULL || fname[0] != '/')
416 tempwork->log = strdup(fname);
417 else
418 asprintf(&tempwork->log, "%s%s", destdir, fname);
419 if (tempwork->log == NULL)
420 err(1, "strdup for %s", fname);
421
422 if (src_entry != NULL) {
423 tempwork->pid_cmd_file = NULL;
424 if (src_entry->pid_cmd_file)
425 tempwork->pid_cmd_file = strdup(src_entry->pid_cmd_file);
426 tempwork->r_reason = NULL;
427 tempwork->firstcreate = 0;
428 tempwork->rotate = 0;
429 tempwork->fsize = -1;
430 tempwork->uid = src_entry->uid;
431 tempwork->gid = src_entry->gid;
432 tempwork->numlogs = src_entry->numlogs;
433 tempwork->trsize = src_entry->trsize;
434 tempwork->hours = src_entry->hours;
435 tempwork->trim_at = NULL;
436 if (src_entry->trim_at != NULL)
437 tempwork->trim_at = ptime_init(src_entry->trim_at);
438 tempwork->permissions = src_entry->permissions;
439 tempwork->flags = src_entry->flags;
440 tempwork->compress = src_entry->compress;
441 tempwork->sig = src_entry->sig;
442 tempwork->def_cfg = src_entry->def_cfg;
443 } else {
444 /* Initialize as a "do-nothing" entry */
445 tempwork->pid_cmd_file = NULL;
446 tempwork->r_reason = NULL;
447 tempwork->firstcreate = 0;
448 tempwork->rotate = 0;
449 tempwork->fsize = -1;
450 tempwork->uid = (uid_t)-1;
451 tempwork->gid = (gid_t)-1;
452 tempwork->numlogs = 1;
453 tempwork->trsize = -1;
454 tempwork->hours = -1;
455 tempwork->trim_at = NULL;
456 tempwork->permissions = 0;
457 tempwork->flags = 0;
458 tempwork->compress = COMPRESS_NONE;
459 tempwork->sig = defsignal;
460 tempwork->def_cfg = 0;
461 }
462
463 return (tempwork);
464 }
465
466 static void
free_entry(struct conf_entry * ent)467 free_entry(struct conf_entry *ent)
468 {
469
470 if (ent == NULL)
471 return;
472
473 if (ent->log != NULL) {
474 if (verbose > 4)
475 printf("\t--> [freeing entry for %s]\n", ent->log);
476 free(ent->log);
477 ent->log = NULL;
478 }
479
480 if (ent->pid_cmd_file != NULL) {
481 free(ent->pid_cmd_file);
482 ent->pid_cmd_file = NULL;
483 }
484
485 if (ent->r_reason != NULL) {
486 free(ent->r_reason);
487 ent->r_reason = NULL;
488 }
489
490 if (ent->trim_at != NULL) {
491 ptime_free(ent->trim_at);
492 ent->trim_at = NULL;
493 }
494
495 free(ent);
496 }
497
498 static void
free_clist(struct cflist * list)499 free_clist(struct cflist *list)
500 {
501 struct conf_entry *ent;
502
503 while (!STAILQ_EMPTY(list)) {
504 ent = STAILQ_FIRST(list);
505 STAILQ_REMOVE_HEAD(list, cf_nextp);
506 free_entry(ent);
507 }
508
509 free(list);
510 list = NULL;
511 }
512
513 static bool
parse_compression_type(const char * str,enum compress_types_enum * type)514 parse_compression_type(const char *str, enum compress_types_enum *type)
515 {
516 int i;
517
518 for (i = 0; i < COMPRESS_TYPES; i++) {
519 if (strcasecmp(str, compress_type[i].name) == 0) {
520 *type = i;
521 break;
522 }
523 }
524 if (i == COMPRESS_TYPES) {
525 if (strcasecmp(str, "legacy") == 0)
526 compress_type_override = COMPRESS_LEGACY;
527 else {
528 return (false);
529 }
530 }
531 return (true);
532 }
533
534 static const char *
compression_type_name(enum compress_types_enum type)535 compression_type_name(enum compress_types_enum type)
536 {
537
538 if (type == COMPRESS_LEGACY)
539 return ("legacy");
540 else
541 return (compress_type[type].name);
542 }
543
544 static fk_entry
do_entry(struct conf_entry * ent)545 do_entry(struct conf_entry * ent)
546 {
547 #define REASON_MAX 80
548 int modtime;
549 fk_entry free_or_keep;
550 double diffsecs;
551 char temp_reason[REASON_MAX];
552 int oversized;
553
554 free_or_keep = FREE_ENT;
555 if (verbose)
556 printf("%s <%d%s>: ", ent->log, ent->numlogs,
557 compress_type[ent->compress].flag);
558 ent->fsize = sizefile(ent->log);
559 oversized = ((ent->trsize > 0) && (ent->fsize >= ent->trsize));
560 modtime = age_old_log(ent->log);
561 ent->rotate = 0;
562 ent->firstcreate = 0;
563 if (ent->fsize < 0) {
564 /*
565 * If either the C flag or the -C option was specified,
566 * and if we won't be creating the file, then have the
567 * verbose message include a hint as to why the file
568 * will not be created.
569 */
570 temp_reason[0] = '\0';
571 if (createlogs > 1)
572 ent->firstcreate = 1;
573 else if ((ent->flags & CE_CREATE) && createlogs)
574 ent->firstcreate = 1;
575 else if (ent->flags & CE_CREATE)
576 strlcpy(temp_reason, " (no -C option)", REASON_MAX);
577 else if (createlogs)
578 strlcpy(temp_reason, " (no C flag)", REASON_MAX);
579
580 if (ent->firstcreate) {
581 if (verbose)
582 printf("does not exist -> will create.\n");
583 createlog(ent);
584 } else if (verbose) {
585 printf("does not exist, skipped%s.\n", temp_reason);
586 }
587 } else {
588 if (ent->flags & CE_NOEMPTY && ent->fsize == 0) {
589 if (verbose)
590 printf("--> Not rotating empty file\n");
591 return (free_or_keep);
592 }
593 if (ent->flags & CE_TRIMAT && !force && !rotatereq &&
594 !oversized) {
595 diffsecs = ptimeget_diff(timenow, ent->trim_at);
596 if (diffsecs < 0.0) {
597 /* trim_at is some time in the future. */
598 if (verbose) {
599 ptime_adjust4dst(ent->trim_at,
600 timenow);
601 printf("--> will trim at %s",
602 ptimeget_ctime(ent->trim_at));
603 }
604 return (free_or_keep);
605 } else if (diffsecs >= 3600.0) {
606 /*
607 * trim_at is more than an hour in the past,
608 * so find the next valid trim_at time, and
609 * tell the user what that will be.
610 */
611 if (verbose && dbg_at_times)
612 printf("\n\t--> prev trim at %s\t",
613 ptimeget_ctime(ent->trim_at));
614 if (verbose) {
615 ptimeset_nxtime(ent->trim_at);
616 printf("--> will trim at %s",
617 ptimeget_ctime(ent->trim_at));
618 }
619 return (free_or_keep);
620 } else if (verbose && noaction && dbg_at_times) {
621 /*
622 * If we are just debugging at-times, then
623 * a detailed message is helpful. Also
624 * skip "doing" any commands, since they
625 * would all be turned off by no-action.
626 */
627 printf("\n\t--> timematch at %s",
628 ptimeget_ctime(ent->trim_at));
629 return (free_or_keep);
630 } else if (verbose && ent->hours <= 0) {
631 printf("--> time is up\n");
632 }
633 }
634 if (verbose && (ent->trsize > 0))
635 printf("size (Kb): %d [%d] ", ent->fsize, ent->trsize);
636 if (verbose && (ent->hours > 0))
637 printf(" age (hr): %d [%d] ", modtime, ent->hours);
638
639 /*
640 * Figure out if this logfile needs to be rotated.
641 */
642 temp_reason[0] = '\0';
643 if (rotatereq) {
644 ent->rotate = 1;
645 snprintf(temp_reason, REASON_MAX, " due to -R from %s",
646 requestor);
647 } else if (force) {
648 ent->rotate = 1;
649 snprintf(temp_reason, REASON_MAX, " due to -F request");
650 } else if (oversized) {
651 ent->rotate = 1;
652 snprintf(temp_reason, REASON_MAX, " due to size>%dK",
653 ent->trsize);
654 } else if (ent->hours <= 0 && (ent->flags & CE_TRIMAT)) {
655 ent->rotate = 1;
656 } else if ((ent->hours > 0) && ((modtime >= ent->hours) ||
657 (modtime < 0))) {
658 ent->rotate = 1;
659 }
660
661 /*
662 * If the file needs to be rotated, then rotate it.
663 */
664 if (ent->rotate && !norotate) {
665 if (temp_reason[0] != '\0')
666 ent->r_reason = strdup(temp_reason);
667 if (verbose) {
668 if (ent->compress == COMPRESS_NONE)
669 printf("--> trimming log....\n");
670 else
671 printf("--> trimming log and compressing with %s....\n",
672 compression_type_name(ent->compress));
673 }
674 if (noaction && !verbose)
675 printf("%s <%d%s>: trimming\n", ent->log,
676 ent->numlogs,
677 compress_type[ent->compress].flag);
678 free_or_keep = do_rotate(ent);
679 } else {
680 if (verbose)
681 printf("--> skipping\n");
682 }
683 }
684 return (free_or_keep);
685 #undef REASON_MAX
686 }
687
688 static void
parse_args(int argc,char ** argv)689 parse_args(int argc, char **argv)
690 {
691 int ch;
692 char *p;
693
694 timenow = ptime_init(NULL);
695 ptimeset_time(timenow, time(NULL));
696 strlcpy(daytime, ptimeget_ctime(timenow) + 4, DAYTIME_LEN);
697 ptimeget_ctime_rfc5424(timenow, daytime_rfc5424, DAYTIME_RFC5424_LEN);
698
699 /* Let's get our hostname */
700 (void)gethostname(hostname, sizeof(hostname));
701 hostname_shortlen = strcspn(hostname, ".");
702
703 /* Parse command line options. */
704 while ((ch = getopt(argc, argv, "a:d:f:nrst:vCD:FI:NPR:S:")) != -1)
705 switch (ch) {
706 case 'a':
707 archtodir++;
708 archdirname = optarg;
709 break;
710 case 'd':
711 destdir = optarg;
712 break;
713 case 'f':
714 conf = optarg;
715 break;
716 case 'n':
717 noaction++;
718 /* FALLTHROUGH */
719 case 'r':
720 needroot = 0;
721 break;
722 case 's':
723 nosignal = 1;
724 break;
725 case 't':
726 if (optarg[0] == '\0' ||
727 strcmp(optarg, "DEFAULT") == 0)
728 timefnamefmt = strdup(DEFAULT_TIMEFNAME_FMT);
729 else
730 timefnamefmt = strdup(optarg);
731 break;
732 case 'v':
733 verbose++;
734 break;
735 case 'C':
736 /* Useful for things like rc.diskless... */
737 createlogs++;
738 break;
739 case 'D':
740 /*
741 * Set some debugging option. The specific option
742 * depends on the value of optarg. These options
743 * may come and go without notice or documentation.
744 */
745 if (parse_doption(optarg))
746 break;
747 usage();
748 /* NOTREACHED */
749 case 'F':
750 force++;
751 break;
752 case 'I':
753 if (str2sig(optarg, &defsignal) != 0)
754 usage();
755 break;
756 case 'N':
757 norotate++;
758 break;
759 case 'P':
760 enforcepid++;
761 break;
762 case 'R':
763 rotatereq++;
764 requestor = strdup(optarg);
765 break;
766 case 'S':
767 path_syslogpid = optarg;
768 break;
769 case 'm': /* Used by OpenBSD for "monitor mode" */
770 default:
771 usage();
772 /* NOTREACHED */
773 }
774
775 if (force && norotate) {
776 warnx("Only one of -F and -N may be specified.");
777 usage();
778 /* NOTREACHED */
779 }
780
781 if (rotatereq) {
782 if (optind == argc) {
783 warnx("At least one filename must be given when -R is specified.");
784 usage();
785 /* NOTREACHED */
786 }
787 /* Make sure "requestor" value is safe for a syslog message. */
788 for (p = requestor; *p != '\0'; p++) {
789 if (!isprintch(*p) && (*p != '\t'))
790 *p = '.';
791 }
792 }
793
794 if (dbg_timenow) {
795 /*
796 * Note that the 'daytime' variable is not changed.
797 * That is only used in messages that track when a
798 * logfile is rotated, and if a file *is* rotated,
799 * then it will still rotated at the "real now" time.
800 */
801 ptime_free(timenow);
802 timenow = dbg_timenow;
803 fprintf(stderr, "Debug: Running as if TimeNow is %s",
804 ptimeget_ctime(dbg_timenow));
805 }
806
807 }
808
809 /*
810 * These debugging options are mainly meant for developer use, such
811 * as writing regression-tests. They would not be needed by users
812 * during normal operation of newsyslog...
813 */
814 static int
parse_doption(const char * doption)815 parse_doption(const char *doption)
816 {
817 const char TN[] = "TN=";
818 int res;
819
820 if (strncmp(doption, TN, sizeof(TN) - 1) == 0) {
821 /*
822 * The "TimeNow" debugging option. This might be off
823 * by an hour when crossing a timezone change.
824 */
825 dbg_timenow = ptime_init(NULL);
826 res = ptime_relparse(dbg_timenow, PTM_PARSE_ISO8601,
827 time(NULL), doption + sizeof(TN) - 1);
828 if (res == -2) {
829 warnx("Non-existent time specified on -D %s", doption);
830 return (0); /* failure */
831 } else if (res < 0) {
832 warnx("Malformed time given on -D %s", doption);
833 return (0); /* failure */
834 }
835 return (1); /* successfully parsed */
836
837 }
838
839 if (strcmp(doption, "ats") == 0) {
840 dbg_at_times++;
841 return (1); /* successfully parsed */
842 }
843
844 warnx("Unknown -D (debug) option: '%s'", doption);
845 return (0); /* failure */
846 }
847
848 static void
usage(void)849 usage(void)
850 {
851
852 fprintf(stderr,
853 "usage: newsyslog [-CFNPnrsv] [-a directory] [-d directory] [-f config_file]\n"
854 " [-I signal] [-S pidfile] [-t timefmt] [[-R tagname] file ...]\n");
855 exit(1);
856 }
857
858 /*
859 * Parse a configuration file and return a linked list of all the logs
860 * which should be processed.
861 */
862 static struct cflist *
get_worklist(char ** files)863 get_worklist(char **files)
864 {
865 FILE *f;
866 char **given;
867 struct cflist *cmdlist, *filelist, *globlist;
868 struct conf_entry *defconf, *dupent, *ent;
869 struct ilist inclist;
870 struct include_entry *inc;
871 int gmatch, fnres;
872
873 defconf = NULL;
874 STAILQ_INIT(&inclist);
875
876 filelist = malloc(sizeof(struct cflist));
877 if (filelist == NULL)
878 err(1, "malloc of filelist");
879 STAILQ_INIT(filelist);
880 globlist = malloc(sizeof(struct cflist));
881 if (globlist == NULL)
882 err(1, "malloc of globlist");
883 STAILQ_INIT(globlist);
884
885 inc = malloc(sizeof(struct include_entry));
886 if (inc == NULL)
887 err(1, "malloc of inc");
888 inc->file = conf;
889 if (inc->file == NULL)
890 inc->file = _PATH_CONF;
891 STAILQ_INSERT_TAIL(&inclist, inc, inc_nextp);
892
893 STAILQ_FOREACH(inc, &inclist, inc_nextp) {
894 if (strcmp(inc->file, "-") != 0)
895 f = fopen(inc->file, "r");
896 else {
897 f = stdin;
898 inc->file = "<stdin>";
899 }
900 if (!f)
901 err(1, "%s", inc->file);
902
903 if (verbose)
904 printf("Processing %s\n", inc->file);
905 parse_file(f, filelist, globlist, &defconf, &inclist);
906 (void) fclose(f);
907 }
908
909 /*
910 * All config-file information has been read in and turned into
911 * a filelist and a globlist. If there were no specific files
912 * given on the run command, then the only thing left to do is to
913 * call a routine which finds all files matched by the globlist
914 * and adds them to the filelist. Then return the worklist.
915 */
916 if (*files == NULL) {
917 expand_globs(filelist, globlist);
918 free_clist(globlist);
919 if (defconf != NULL)
920 free_entry(defconf);
921 return (filelist);
922 }
923
924 /*
925 * If newsyslog was given a specific list of files to process,
926 * it may be that some of those files were not listed in any
927 * config file. Those unlisted files should get the default
928 * rotation action. First, create the default-rotation action
929 * if none was found in a system config file.
930 */
931 if (defconf == NULL) {
932 defconf = init_entry(DEFAULT_MARKER, NULL);
933 defconf->numlogs = 3;
934 defconf->trsize = 50;
935 defconf->permissions = S_IRUSR|S_IWUSR;
936 }
937
938 /*
939 * If newsyslog was run with a list of specific filenames,
940 * then create a new worklist which has only those files in
941 * it, picking up the rotation-rules for those files from
942 * the original filelist.
943 *
944 * XXX - Note that this will copy multiple rules for a single
945 * logfile, if multiple entries are an exact match for
946 * that file. That matches the historic behavior, but do
947 * we want to continue to allow it? If so, it should
948 * probably be handled more intelligently.
949 */
950 cmdlist = malloc(sizeof(struct cflist));
951 if (cmdlist == NULL)
952 err(1, "malloc of cmdlist");
953 STAILQ_INIT(cmdlist);
954
955 for (given = files; *given; ++given) {
956 /*
957 * First try to find exact-matches for this given file.
958 */
959 gmatch = 0;
960 STAILQ_FOREACH(ent, filelist, cf_nextp) {
961 if (strcmp(ent->log, *given) == 0) {
962 gmatch++;
963 dupent = init_entry(*given, ent);
964 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
965 }
966 }
967 if (gmatch) {
968 if (verbose > 2)
969 printf("\t+ Matched entry %s\n", *given);
970 continue;
971 }
972
973 /*
974 * There was no exact-match for this given file, so look
975 * for a "glob" entry which does match.
976 */
977 gmatch = 0;
978 if (verbose > 2)
979 printf("\t+ Checking globs for %s\n", *given);
980 STAILQ_FOREACH(ent, globlist, cf_nextp) {
981 fnres = fnmatch(ent->log, *given, FNM_PATHNAME);
982 if (verbose > 2)
983 printf("\t+ = %d for pattern %s\n", fnres,
984 ent->log);
985 if (fnres == 0) {
986 gmatch++;
987 dupent = init_entry(*given, ent);
988 /* This new entry is not a glob! */
989 dupent->flags &= ~CE_GLOB;
990 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
991 /* Only allow a match to one glob-entry */
992 break;
993 }
994 }
995 if (gmatch) {
996 if (verbose > 2)
997 printf("\t+ Matched %s via %s\n", *given,
998 ent->log);
999 continue;
1000 }
1001
1002 /*
1003 * This given file was not found in any config file, so
1004 * add a worklist item based on the default entry.
1005 */
1006 if (verbose > 2)
1007 printf("\t+ No entry matched %s (will use %s)\n",
1008 *given, DEFAULT_MARKER);
1009 dupent = init_entry(*given, defconf);
1010 /* Mark that it was *not* found in a config file */
1011 dupent->def_cfg = 1;
1012 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
1013 }
1014
1015 /*
1016 * Free all the entries in the original work list, the list of
1017 * glob entries, and the default entry.
1018 */
1019 free_clist(filelist);
1020 free_clist(globlist);
1021 free_entry(defconf);
1022
1023 /* And finally, return a worklist which matches the given files. */
1024 return (cmdlist);
1025 }
1026
1027 /*
1028 * Expand the list of entries with filename patterns, and add all files
1029 * which match those glob-entries onto the worklist.
1030 */
1031 static void
expand_globs(struct cflist * work_p,struct cflist * glob_p)1032 expand_globs(struct cflist *work_p, struct cflist *glob_p)
1033 {
1034 int gmatch, gres;
1035 size_t i;
1036 char *mfname;
1037 struct conf_entry *dupent, *ent, *globent;
1038 glob_t pglob;
1039 struct stat st_fm;
1040
1041 /*
1042 * The worklist contains all fully-specified (non-GLOB) names.
1043 *
1044 * Now expand the list of filename-pattern (GLOB) entries into
1045 * a second list, which (by definition) will only match files
1046 * that already exist. Do not add a glob-related entry for any
1047 * file which already exists in the fully-specified list.
1048 */
1049 STAILQ_FOREACH(globent, glob_p, cf_nextp) {
1050 gres = glob(globent->log, GLOB_NOCHECK, NULL, &pglob);
1051 if (gres != 0) {
1052 warn("cannot expand pattern (%d): %s", gres,
1053 globent->log);
1054 continue;
1055 }
1056
1057 if (verbose > 2)
1058 printf("\t+ Expanding pattern %s\n", globent->log);
1059 for (i = 0; i < pglob.gl_matchc; i++) {
1060 mfname = pglob.gl_pathv[i];
1061
1062 /* See if this file already has a specific entry. */
1063 gmatch = 0;
1064 STAILQ_FOREACH(ent, work_p, cf_nextp) {
1065 if (strcmp(mfname, ent->log) == 0) {
1066 gmatch++;
1067 break;
1068 }
1069 }
1070 if (gmatch)
1071 continue;
1072
1073 /* Make sure the named matched is a file. */
1074 gres = lstat(mfname, &st_fm);
1075 if (gres != 0) {
1076 /* Error on a file that glob() matched?!? */
1077 warn("Skipping %s - lstat() error", mfname);
1078 continue;
1079 }
1080 if (!S_ISREG(st_fm.st_mode)) {
1081 /* We only rotate files! */
1082 if (verbose > 2)
1083 printf("\t+ . skipping %s (!file)\n",
1084 mfname);
1085 continue;
1086 }
1087
1088 if (verbose > 2)
1089 printf("\t+ . add file %s\n", mfname);
1090 dupent = init_entry(mfname, globent);
1091 /* This new entry is not a glob! */
1092 dupent->flags &= ~CE_GLOB;
1093
1094 /* Add to the worklist. */
1095 STAILQ_INSERT_TAIL(work_p, dupent, cf_nextp);
1096 }
1097 globfree(&pglob);
1098 if (verbose > 2)
1099 printf("\t+ Done with pattern %s\n", globent->log);
1100 }
1101 }
1102
1103 /*
1104 * Parse a configuration file and update a linked list of all the logs to
1105 * process.
1106 */
1107 static void
parse_file(FILE * cf,struct cflist * work_p,struct cflist * glob_p,struct conf_entry ** defconf_p,struct ilist * inclist)1108 parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
1109 struct conf_entry **defconf_p, struct ilist *inclist)
1110 {
1111 char line[BUFSIZ], *parse, *q;
1112 char *cp, *errline, *group;
1113 struct conf_entry *working;
1114 struct passwd *pwd;
1115 struct group *grp;
1116 glob_t pglob;
1117 int eol, ptm_opts, res, special;
1118 size_t i;
1119
1120 errline = NULL;
1121 while (fgets(line, BUFSIZ, cf)) {
1122 if ((line[0] == '\n') || (line[0] == '#') ||
1123 (strlen(line) == 0))
1124 continue;
1125 if (errline != NULL)
1126 free(errline);
1127 errline = strdup(line);
1128 for (cp = line + 1; *cp != '\0'; cp++) {
1129 if (*cp != '#')
1130 continue;
1131 if (*(cp - 1) == '\\') {
1132 strcpy(cp - 1, cp);
1133 cp--;
1134 continue;
1135 }
1136 *cp = '\0';
1137 break;
1138 }
1139
1140 q = parse = missing_field(sob(line), errline);
1141 parse = son(line);
1142 if (!*parse) {
1143 warnx("malformed line (missing fields):\n%s",
1144 errline);
1145 continue;
1146 }
1147 *parse = '\0';
1148
1149 /*
1150 * Allow people to set debug options via the config file.
1151 * (NOTE: debug options are undocumented, and may disappear
1152 * at any time, etc).
1153 */
1154 if (strcasecmp(DEBUG_MARKER, q) == 0) {
1155 q = parse = missing_field(sob(parse + 1), errline);
1156 parse = son(parse);
1157 if (!*parse)
1158 warnx("debug line specifies no option:\n%s",
1159 errline);
1160 else {
1161 *parse = '\0';
1162 parse_doption(q);
1163 }
1164 continue;
1165 } else if (strcasecmp(INCLUDE_MARKER, q) == 0) {
1166 if (verbose)
1167 printf("Found: %s", errline);
1168 q = parse = missing_field(sob(parse + 1), errline);
1169 parse = son(parse);
1170 if (!*parse) {
1171 warnx("include line missing argument:\n%s",
1172 errline);
1173 continue;
1174 }
1175
1176 *parse = '\0';
1177
1178 if (isglobstr(q)) {
1179 res = glob(q, GLOB_NOCHECK, NULL, &pglob);
1180 if (res != 0) {
1181 warn("cannot expand pattern (%d): %s",
1182 res, q);
1183 continue;
1184 }
1185
1186 if (verbose > 2)
1187 printf("\t+ Expanding pattern %s\n", q);
1188
1189 for (i = 0; i < pglob.gl_matchc; i++)
1190 add_to_queue(pglob.gl_pathv[i],
1191 inclist);
1192 globfree(&pglob);
1193 } else
1194 add_to_queue(q, inclist);
1195 continue;
1196 } else if (strcasecmp(COMPRESS_MARKER, q) == 0) {
1197 enum compress_types_enum result;
1198
1199 if (verbose)
1200 printf("Found: %s", errline);
1201 q = parse = missing_field(sob(parse + 1), errline);
1202 parse = son(parse);
1203 if (!*parse)
1204 warnx("compress line specifies no option:\n%s",
1205 errline);
1206 else {
1207 *parse = '\0';
1208 if (parse_compression_type(q, &result)) {
1209 if (compress_type_set) {
1210 warnx("Ignoring compress line "
1211 "option '%s', using '%s' instead",
1212 q,
1213 compression_type_name(compress_type_override));
1214 } else {
1215 if (compress_type_seen)
1216 warnx("Compress type should appear before all log files:\n%s",
1217 errline);
1218 compress_type_override = result;
1219 compress_type_set = true;
1220 }
1221 } else {
1222 warnx("Bad compress option '%s'", q);
1223 };
1224 }
1225 continue;
1226 }
1227
1228 #define badline(msg, ...) do { \
1229 warnx(msg, __VA_ARGS__); \
1230 goto cleanup; \
1231 } while (0)
1232
1233 special = 0;
1234 working = init_entry(q, NULL);
1235 if (strcasecmp(DEFAULT_MARKER, q) == 0) {
1236 special = 1;
1237 if (*defconf_p != NULL)
1238 badline("Ignoring duplicate entry for %s!", q);
1239 *defconf_p = working;
1240 }
1241
1242 q = parse = missing_field(sob(parse + 1), errline);
1243 parse = son(parse);
1244 if (!*parse)
1245 badline("malformed line (missing fields):\n%s",
1246 errline);
1247 *parse = '\0';
1248 if ((group = strchr(q, ':')) != NULL ||
1249 (group = strrchr(q, '.')) != NULL) {
1250 *group++ = '\0';
1251 if (*q) {
1252 if (!(isnumberstr(q))) {
1253 if ((pwd = getpwnam(q)) == NULL)
1254 badline(
1255 "error in config file; unknown user:\n%s",
1256 errline);
1257 working->uid = pwd->pw_uid;
1258 } else
1259 working->uid = atoi(q);
1260 } else
1261 working->uid = (uid_t)-1;
1262
1263 q = group;
1264 if (*q) {
1265 if (!(isnumberstr(q))) {
1266 if ((grp = getgrnam(q)) == NULL)
1267 badline(
1268 "error in config file; unknown group:\n%s",
1269 errline);
1270 working->gid = grp->gr_gid;
1271 } else
1272 working->gid = atoi(q);
1273 } else
1274 working->gid = (gid_t)-1;
1275
1276 q = parse = missing_field(sob(parse + 1), errline);
1277 parse = son(parse);
1278 if (!*parse)
1279 badline("malformed line (missing fields):\n%s",
1280 errline);
1281 *parse = '\0';
1282 } else {
1283 working->uid = (uid_t)-1;
1284 working->gid = (gid_t)-1;
1285 }
1286
1287 if (!sscanf(q, "%o", &working->permissions))
1288 badline("error in config file; bad permissions:\n%s",
1289 errline);
1290 if ((working->permissions & ~DEFFILEMODE) != 0) {
1291 warnx("File mode bits 0%o changed to 0%o in line:\n%s",
1292 working->permissions,
1293 working->permissions & DEFFILEMODE, errline);
1294 working->permissions &= DEFFILEMODE;
1295 }
1296
1297 q = parse = missing_field(sob(parse + 1), errline);
1298 parse = son(parse);
1299 if (!*parse)
1300 badline("malformed line (missing fields):\n%s",
1301 errline);
1302 *parse = '\0';
1303 if (!sscanf(q, "%d", &working->numlogs) || working->numlogs < 0)
1304 badline("error in config file; bad value for count of logs to save:\n%s",
1305 errline);
1306
1307 q = parse = missing_field(sob(parse + 1), errline);
1308 parse = son(parse);
1309 if (!*parse)
1310 badline("malformed line (missing fields):\n%s",
1311 errline);
1312 *parse = '\0';
1313 if (isdigitch(*q)) {
1314 char last_digit = q[strlen(q) - 1];
1315 if (isdigitch(last_digit))
1316 working->trsize = atoi(q);
1317 else {
1318 uint64_t trsize = 0;
1319 if (expand_number(q, &trsize) == 0)
1320 working->trsize = trsize / 1024;
1321 else {
1322 working->trsize = -1;
1323 warnx("Invalid value of '%s' for 'size' in line:\n%s",
1324 q, errline);
1325 }
1326 }
1327 } else if (strcmp(q, "*") == 0)
1328 working->trsize = -1;
1329 else {
1330 warnx("Invalid value of '%s' for 'size' in line:\n%s",
1331 q, errline);
1332 working->trsize = -1;
1333 }
1334
1335 working->flags = 0;
1336 working->compress = COMPRESS_NONE;
1337 q = parse = missing_field(sob(parse + 1), errline);
1338 parse = son(parse);
1339 eol = !*parse;
1340 *parse = '\0';
1341 {
1342 char *ep;
1343 u_long ul;
1344
1345 ul = strtoul(q, &ep, 10);
1346 if (ep == q)
1347 working->hours = 0;
1348 else if (*ep == '*')
1349 working->hours = -1;
1350 else if (ul > INT_MAX)
1351 badline("interval is too large:\n%s", errline);
1352 else
1353 working->hours = ul;
1354
1355 if (*ep == '\0' || strcmp(ep, "*") == 0)
1356 goto no_trimat;
1357 if (*ep != '@' && *ep != '$')
1358 badline("malformed interval/at:\n%s", errline);
1359
1360 working->flags |= CE_TRIMAT;
1361 working->trim_at = ptime_init(NULL);
1362 ptm_opts = PTM_PARSE_ISO8601;
1363 if (*ep == '$')
1364 ptm_opts = PTM_PARSE_DWM;
1365 ptm_opts |= PTM_PARSE_MATCHDOM;
1366 res = ptime_relparse(working->trim_at, ptm_opts,
1367 ptimeget_secs(timenow), ep + 1);
1368 if (res == -2)
1369 badline("nonexistent time for 'at' value:\n%s",
1370 errline);
1371 else if (res < 0)
1372 badline("malformed 'at' value:\n%s", errline);
1373 }
1374 no_trimat:
1375
1376 if (eol)
1377 q = NULL;
1378 else {
1379 q = parse = sob(parse + 1); /* Optional field */
1380 parse = son(parse);
1381 if (!*parse)
1382 eol = 1;
1383 *parse = '\0';
1384 }
1385
1386 for (; q && *q && !isspacech(*q); q++) {
1387 switch (tolowerch(*q)) {
1388 case 'b':
1389 working->flags |= CE_BINARY;
1390 break;
1391 case 'c':
1392 working->flags |= CE_CREATE;
1393 break;
1394 case 'd':
1395 working->flags |= CE_NODUMP;
1396 break;
1397 case 'e':
1398 working->flags |= CE_NOEMPTY;
1399 break;
1400 case 'g':
1401 working->flags |= CE_GLOB;
1402 break;
1403 case 'j':
1404 if (compress_type_override == COMPRESS_LEGACY)
1405 working->compress = COMPRESS_BZIP2;
1406 else
1407 working->compress = compress_type_override;
1408 compress_type_seen = true;
1409 break;
1410 case 'n':
1411 working->flags |= CE_NOSIGNAL;
1412 break;
1413 case 'p':
1414 working->flags |= CE_PLAIN0;
1415 break;
1416 case 'r':
1417 working->flags |= CE_PID2CMD;
1418 break;
1419 case 't':
1420 working->flags |= CE_RFC5424;
1421 break;
1422 case 'u':
1423 working->flags |= CE_SIGNALGROUP;
1424 break;
1425 case 'w':
1426 /* Deprecated flag - keep for compatibility purposes */
1427 break;
1428 case 'x':
1429 if (compress_type_override == COMPRESS_LEGACY)
1430 working->compress = COMPRESS_XZ;
1431 else
1432 working->compress = compress_type_override;
1433 compress_type_seen = true;
1434 break;
1435 case 'y':
1436 if (compress_type_override == COMPRESS_LEGACY)
1437 working->compress = COMPRESS_ZSTD;
1438 else
1439 working->compress = compress_type_override;
1440 compress_type_seen = true;
1441 break;
1442 case 'z':
1443 if (compress_type_override == COMPRESS_LEGACY)
1444 working->compress = COMPRESS_GZIP;
1445 else
1446 working->compress = compress_type_override;
1447 compress_type_seen = true;
1448 break;
1449 case '-':
1450 break;
1451 case 'f': /* Used by OpenBSD for "CE_FOLLOW" */
1452 case 'm': /* Used by OpenBSD for "CE_MONITOR" */
1453 default:
1454 badline("illegal flag in config file -- %c",
1455 *q);
1456 }
1457 }
1458
1459 if (eol)
1460 q = NULL;
1461 else {
1462 q = parse = sob(parse + 1); /* Optional field */
1463 parse = son(parse);
1464 if (!*parse)
1465 eol = 1;
1466 *parse = '\0';
1467 }
1468
1469 working->pid_cmd_file = NULL;
1470 if (q && *q) {
1471 if (*q == '/')
1472 working->pid_cmd_file = strdup(q);
1473 else if (isalnum(*q))
1474 goto got_sig;
1475 else {
1476 badline(
1477 "illegal pid file or signal in config file:\n%s",
1478 errline);
1479 }
1480 }
1481 if (eol)
1482 q = NULL;
1483 else {
1484 q = parse = sob(parse + 1); /* Optional field */
1485 parse = son(parse);
1486 *parse = '\0';
1487 }
1488
1489 working->sig = defsignal;
1490 if (q && *q) {
1491 got_sig:
1492 if (str2sig(q, &working->sig) != 0) {
1493 badline(
1494 "illegal signal in config file:\n%s",
1495 errline);
1496 }
1497 }
1498
1499 /*
1500 * Finish figuring out what pid-file to use (if any) in
1501 * later processing if this logfile needs to be rotated.
1502 */
1503 if ((working->flags & CE_NOSIGNAL) == CE_NOSIGNAL) {
1504 /*
1505 * This config-entry specified 'n' for nosignal,
1506 * see if it also specified an explicit pid_cmd_file.
1507 * This would be a pretty pointless combination.
1508 */
1509 if (working->pid_cmd_file != NULL) {
1510 warnx("Ignoring '%s' because flag 'n' was specified in line:\n%s",
1511 working->pid_cmd_file, errline);
1512 free(working->pid_cmd_file);
1513 working->pid_cmd_file = NULL;
1514 }
1515 } else if (working->pid_cmd_file == NULL) {
1516 /*
1517 * This entry did not specify the 'n' flag, which
1518 * means it should signal syslogd unless it had
1519 * specified some other pid-file (and obviously the
1520 * syslog pid-file will not be for a process-group).
1521 * Also, we should only try to notify syslog if we
1522 * are root.
1523 */
1524 if (working->flags & CE_SIGNALGROUP) {
1525 warnx("Ignoring flag 'U' in line:\n%s",
1526 errline);
1527 working->flags &= ~CE_SIGNALGROUP;
1528 }
1529 if (needroot)
1530 working->pid_cmd_file = strdup(path_syslogpid);
1531 }
1532
1533 /*
1534 * Add this entry to the appropriate list of entries, unless
1535 * it was some kind of special entry (eg: <default>).
1536 */
1537 if (special) {
1538 ; /* Do not add to any list */
1539 } else if (working->flags & CE_GLOB) {
1540 STAILQ_INSERT_TAIL(glob_p, working, cf_nextp);
1541 } else {
1542 STAILQ_INSERT_TAIL(work_p, working, cf_nextp);
1543 }
1544 continue;
1545 cleanup:
1546 free_entry(working);
1547 #undef badline
1548 } /* while (fgets(line, BUFSIZ, cf)) */
1549 if (errline != NULL)
1550 free(errline);
1551 }
1552
1553 static char *
missing_field(char * p,char * errline)1554 missing_field(char *p, char *errline)
1555 {
1556
1557 if (!p || !*p)
1558 errx(1, "missing field in config file:\n%s", errline);
1559 return (p);
1560 }
1561
1562 /*
1563 * In our sort we return it in the reverse of what qsort normally
1564 * would do, as we want the newest files first. If we have two
1565 * entries with the same time we don't really care about order.
1566 *
1567 * Support function for qsort() in delete_oldest_timelog().
1568 */
1569 static int
oldlog_entry_compare(const void * a,const void * b)1570 oldlog_entry_compare(const void *a, const void *b)
1571 {
1572 const struct oldlog_entry *ola = a, *olb = b;
1573
1574 if (ola->t > olb->t)
1575 return (-1);
1576 else if (ola->t < olb->t)
1577 return (1);
1578 else
1579 return (0);
1580 }
1581
1582 /*
1583 * Check whether the file corresponding to dp is an archive of the logfile
1584 * logfname, based on the timefnamefmt format string. Return true and fill out
1585 * tm if this is the case; otherwise return false.
1586 */
1587 static int
validate_old_timelog(int fd,const struct dirent * dp,const char * logfname,struct tm * tm)1588 validate_old_timelog(int fd, const struct dirent *dp, const char *logfname,
1589 struct tm *tm)
1590 {
1591 struct stat sb;
1592 size_t logfname_len;
1593 char *s;
1594 int c;
1595
1596 logfname_len = strlen(logfname);
1597
1598 if (dp->d_type != DT_REG) {
1599 /*
1600 * Some filesystems (e.g. NFS) don't fill out the d_type field
1601 * and leave it set to DT_UNKNOWN; in this case we must obtain
1602 * the file type ourselves.
1603 */
1604 if (dp->d_type != DT_UNKNOWN ||
1605 fstatat(fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW) != 0 ||
1606 !S_ISREG(sb.st_mode))
1607 return (0);
1608 }
1609 /* Ignore everything but files with our logfile prefix. */
1610 if (strncmp(dp->d_name, logfname, logfname_len) != 0)
1611 return (0);
1612 /* Ignore the actual non-rotated logfile. */
1613 if (dp->d_namlen == logfname_len)
1614 return (0);
1615
1616 /*
1617 * Make sure we created have found a logfile, so the
1618 * postfix is valid, IE format is: '.<time>(.[bgx]z)?'.
1619 */
1620 if (dp->d_name[logfname_len] != '.') {
1621 if (verbose)
1622 printf("Ignoring %s which has unexpected "
1623 "extension '%s'\n", dp->d_name,
1624 &dp->d_name[logfname_len]);
1625 return (0);
1626 }
1627 memset(tm, 0, sizeof(*tm));
1628 if ((s = strptime(&dp->d_name[logfname_len + 1],
1629 timefnamefmt, tm)) == NULL) {
1630 /*
1631 * We could special case "old" sequentially named logfiles here,
1632 * but we do not as that would require special handling to
1633 * decide which one was the oldest compared to "new" time based
1634 * logfiles.
1635 */
1636 if (verbose)
1637 printf("Ignoring %s which does not "
1638 "match time format\n", dp->d_name);
1639 return (0);
1640 }
1641
1642 for (c = 0; c < COMPRESS_TYPES; c++)
1643 if (strcmp(s, compress_type[c].suffix) == 0)
1644 /* We're done. */
1645 return (1);
1646
1647 if (verbose)
1648 printf("Ignoring %s which has unexpected extension '%s'\n",
1649 dp->d_name, s);
1650
1651 return (0);
1652 }
1653
1654 /*
1655 * Delete the oldest logfiles, when using time based filenames.
1656 */
1657 static void
delete_oldest_timelog(const struct conf_entry * ent,const char * archive_dir)1658 delete_oldest_timelog(const struct conf_entry *ent, const char *archive_dir)
1659 {
1660 char *basebuf, *dirbuf, errbuf[80];
1661 const char *base, *dir;
1662 int dir_fd, i, logcnt, max_logcnt;
1663 struct oldlog_entry *oldlogs;
1664 struct dirent *dp;
1665 struct tm tm;
1666 DIR *dirp;
1667
1668 oldlogs = malloc(MAX_OLDLOGS * sizeof(struct oldlog_entry));
1669 max_logcnt = MAX_OLDLOGS;
1670 logcnt = 0;
1671
1672 if (archive_dir != NULL && archive_dir[0] != '\0') {
1673 dirbuf = NULL;
1674 dir = archive_dir;
1675 } else {
1676 if ((dirbuf = strdup(ent->log)) == NULL)
1677 err(1, "strdup()");
1678 dir = dirname(dirbuf);
1679 }
1680
1681 if ((basebuf = strdup(ent->log)) == NULL)
1682 err(1, "strdup()");
1683 base = basename(basebuf);
1684 if (strcmp(base, "/") == 0)
1685 errx(1, "Invalid log filename - became '/'");
1686
1687 if (verbose > 2)
1688 printf("Searching for old logs in %s\n", dir);
1689
1690 /* First we create a 'list' of all archived logfiles */
1691 if ((dirp = opendir(dir)) == NULL)
1692 err(1, "Cannot open log directory '%s'", dir);
1693 dir_fd = dirfd(dirp);
1694 while ((dp = readdir(dirp)) != NULL) {
1695 if (validate_old_timelog(dir_fd, dp, base, &tm) == 0)
1696 continue;
1697
1698 /*
1699 * We should now have old an old rotated logfile, so
1700 * add it to the 'list'.
1701 */
1702 if ((oldlogs[logcnt].t = timegm(&tm)) == -1)
1703 err(1, "Could not convert time string to time value");
1704 if ((oldlogs[logcnt].fname = strdup(dp->d_name)) == NULL)
1705 err(1, "strdup()");
1706 logcnt++;
1707
1708 /*
1709 * It is very unlikely we ever run out of space in the
1710 * logfile array from the default size, but lets
1711 * handle it anyway...
1712 */
1713 if (logcnt >= max_logcnt) {
1714 max_logcnt *= 4;
1715 /* Detect integer overflow */
1716 if (max_logcnt < logcnt)
1717 errx(1, "Too many old logfiles found");
1718 oldlogs = realloc(oldlogs,
1719 max_logcnt * sizeof(struct oldlog_entry));
1720 if (oldlogs == NULL)
1721 err(1, "realloc()");
1722 }
1723 }
1724
1725 /* Second, if needed we delete oldest archived logfiles */
1726 if (logcnt > 0 && logcnt >= ent->numlogs && ent->numlogs > 1) {
1727 oldlogs = realloc(oldlogs, logcnt *
1728 sizeof(struct oldlog_entry));
1729 if (oldlogs == NULL)
1730 err(1, "realloc()");
1731
1732 /*
1733 * We now sort the logs in the order of newest to
1734 * oldest. That way we can simply skip over the
1735 * number of records we want to keep.
1736 */
1737 qsort(oldlogs, logcnt, sizeof(struct oldlog_entry),
1738 oldlog_entry_compare);
1739 for (i = ent->numlogs - 1; i < logcnt; i++) {
1740 if (noaction)
1741 printf("\trm -f %s/%s\n", dir,
1742 oldlogs[i].fname);
1743 else if (unlinkat(dir_fd, oldlogs[i].fname, 0) != 0) {
1744 snprintf(errbuf, sizeof(errbuf),
1745 "Could not delete old logfile '%s'",
1746 oldlogs[i].fname);
1747 perror(errbuf);
1748 }
1749 }
1750 } else if (verbose > 1)
1751 printf("No old logs to delete for logfile %s\n", ent->log);
1752
1753 /* Third, cleanup */
1754 closedir(dirp);
1755 for (i = 0; i < logcnt; i++) {
1756 assert(oldlogs[i].fname != NULL);
1757 free(oldlogs[i].fname);
1758 }
1759 free(oldlogs);
1760 free(dirbuf);
1761 free(basebuf);
1762 }
1763
1764 /*
1765 * Generate a log filename, when using classic filenames.
1766 */
1767 static void
gen_classiclog_fname(char * fname,size_t fname_sz,const char * archive_dir,const char * namepart,int numlogs_c)1768 gen_classiclog_fname(char *fname, size_t fname_sz, const char *archive_dir,
1769 const char *namepart, int numlogs_c)
1770 {
1771
1772 if (archive_dir[0] != '\0')
1773 (void) snprintf(fname, fname_sz, "%s/%s.%d", archive_dir,
1774 namepart, numlogs_c);
1775 else
1776 (void) snprintf(fname, fname_sz, "%s.%d", namepart, numlogs_c);
1777 }
1778
1779 /*
1780 * Delete a rotated logfile, when using classic filenames.
1781 */
1782 static void
delete_classiclog(const char * archive_dir,const char * namepart,int numlog_c)1783 delete_classiclog(const char *archive_dir, const char *namepart, int numlog_c)
1784 {
1785 char file1[MAXPATHLEN], zfile1[MAXPATHLEN];
1786 int c;
1787
1788 gen_classiclog_fname(file1, sizeof(file1), archive_dir, namepart,
1789 numlog_c);
1790
1791 for (c = 0; c < COMPRESS_TYPES; c++) {
1792 (void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
1793 compress_type[c].suffix);
1794 if (noaction)
1795 printf("\trm -f %s\n", zfile1);
1796 else
1797 (void) unlink(zfile1);
1798 }
1799 }
1800
1801 /*
1802 * Only add to the queue if the file hasn't already been added. This is
1803 * done to prevent circular include loops.
1804 */
1805 static void
add_to_queue(const char * fname,struct ilist * inclist)1806 add_to_queue(const char *fname, struct ilist *inclist)
1807 {
1808 struct include_entry *inc;
1809
1810 STAILQ_FOREACH(inc, inclist, inc_nextp) {
1811 if (strcmp(fname, inc->file) == 0) {
1812 warnx("duplicate include detected: %s", fname);
1813 return;
1814 }
1815 }
1816
1817 inc = malloc(sizeof(struct include_entry));
1818 if (inc == NULL)
1819 err(1, "malloc of inc");
1820 inc->file = strdup(fname);
1821
1822 if (verbose > 2)
1823 printf("\t+ Adding %s to the processing queue.\n", fname);
1824
1825 STAILQ_INSERT_TAIL(inclist, inc, inc_nextp);
1826 }
1827
1828 /*
1829 * Search for logfile and return its compression suffix (if supported)
1830 * The suffix detection is first-match in the order of compress_types
1831 *
1832 * Note: if logfile without suffix exists (uncompressed, COMPRESS_NONE)
1833 * a zero-length string is returned
1834 */
1835 static const char *
get_logfile_suffix(const char * logfile)1836 get_logfile_suffix(const char *logfile)
1837 {
1838 struct stat st;
1839 char zfile[MAXPATHLEN];
1840 int c;
1841
1842 for (c = 0; c < COMPRESS_TYPES; c++) {
1843 (void) strlcpy(zfile, logfile, MAXPATHLEN);
1844 (void) strlcat(zfile, compress_type[c].suffix, MAXPATHLEN);
1845 if (lstat(zfile, &st) == 0)
1846 return (compress_type[c].suffix);
1847 }
1848 return (NULL);
1849 }
1850
1851 static fk_entry
do_rotate(const struct conf_entry * ent)1852 do_rotate(const struct conf_entry *ent)
1853 {
1854 char dirpart[MAXPATHLEN], namepart[MAXPATHLEN];
1855 char file1[MAXPATHLEN], file2[MAXPATHLEN];
1856 char zfile1[MAXPATHLEN], zfile2[MAXPATHLEN];
1857 const char *logfile_suffix;
1858 char datetimestr[30];
1859 int flags, numlogs_c;
1860 fk_entry free_or_keep;
1861 struct sigwork_entry *swork;
1862 struct stat st;
1863 struct tm tm;
1864 time_t now;
1865
1866 flags = ent->flags;
1867 free_or_keep = FREE_ENT;
1868
1869 if (archtodir) {
1870 char *p;
1871
1872 /* build complete name of archive directory into dirpart */
1873 if (*archdirname == '/') { /* absolute */
1874 strlcpy(dirpart, archdirname, sizeof(dirpart));
1875 } else { /* relative */
1876 /* get directory part of logfile */
1877 strlcpy(dirpart, ent->log, sizeof(dirpart));
1878 if ((p = strrchr(dirpart, '/')) == NULL)
1879 dirpart[0] = '\0';
1880 else
1881 *(p + 1) = '\0';
1882 strlcat(dirpart, archdirname, sizeof(dirpart));
1883 }
1884
1885 /* check if archive directory exists, if not, create it */
1886 if (lstat(dirpart, &st))
1887 createdir(ent, dirpart);
1888
1889 /* get filename part of logfile */
1890 if ((p = strrchr(ent->log, '/')) == NULL)
1891 strlcpy(namepart, ent->log, sizeof(namepart));
1892 else
1893 strlcpy(namepart, p + 1, sizeof(namepart));
1894 } else {
1895 /*
1896 * Tell utility functions we are not using an archive
1897 * dir.
1898 */
1899 dirpart[0] = '\0';
1900 strlcpy(namepart, ent->log, sizeof(namepart));
1901 }
1902
1903 /* Delete old logs */
1904 if (timefnamefmt != NULL)
1905 delete_oldest_timelog(ent, dirpart);
1906 else {
1907 /*
1908 * Handle cleaning up after legacy newsyslog where we
1909 * kept ent->numlogs + 1 files. This code can go away
1910 * at some point in the future.
1911 */
1912 delete_classiclog(dirpart, namepart, ent->numlogs);
1913
1914 if (ent->numlogs > 0)
1915 delete_classiclog(dirpart, namepart, ent->numlogs - 1);
1916
1917 }
1918
1919 if (timefnamefmt != NULL) {
1920 /* If time functions fails we can't really do any sensible */
1921 if (time(&now) == (time_t)-1 ||
1922 localtime_r(&now, &tm) == NULL)
1923 bzero(&tm, sizeof(tm));
1924
1925 strftime(datetimestr, sizeof(datetimestr), timefnamefmt, &tm);
1926 if (archtodir)
1927 (void) snprintf(file1, sizeof(file1), "%s/%s.%s",
1928 dirpart, namepart, datetimestr);
1929 else
1930 (void) snprintf(file1, sizeof(file1), "%s.%s",
1931 ent->log, datetimestr);
1932
1933 /* Don't run the code to move down logs */
1934 numlogs_c = -1;
1935 } else {
1936 gen_classiclog_fname(file1, sizeof(file1), dirpart, namepart,
1937 ent->numlogs - 1);
1938 numlogs_c = ent->numlogs - 2; /* copy for countdown */
1939 }
1940
1941 /* Move down log files */
1942 for (; numlogs_c >= 0; numlogs_c--) {
1943 (void) strlcpy(file2, file1, sizeof(file2));
1944
1945 gen_classiclog_fname(file1, sizeof(file1), dirpart, namepart,
1946 numlogs_c);
1947
1948 logfile_suffix = get_logfile_suffix(file1);
1949 if (logfile_suffix == NULL)
1950 continue;
1951 (void) strlcpy(zfile1, file1, MAXPATHLEN);
1952 (void) strlcpy(zfile2, file2, MAXPATHLEN);
1953 (void) strlcat(zfile1, logfile_suffix, MAXPATHLEN);
1954 (void) strlcat(zfile2, logfile_suffix, MAXPATHLEN);
1955
1956 if (noaction)
1957 printf("\tmv %s %s\n", zfile1, zfile2);
1958 else {
1959 /* XXX - Ought to be checking for failure! */
1960 (void)rename(zfile1, zfile2);
1961 }
1962 change_attrs(zfile2, ent);
1963 if (ent->compress && strlen(logfile_suffix) == 0) {
1964 /* compress old rotation */
1965 struct zipwork_entry *zwork;
1966 size_t sz;
1967
1968 sz = sizeof(*zwork) + strlen(zfile2) + 1;
1969 zwork = calloc(1, sz);
1970 if (zwork == NULL)
1971 err(1, "calloc");
1972
1973 zwork->zw_conf = ent;
1974 zwork->zw_fsize = sizefile(zfile2);
1975 strcpy(zwork->zw_fname, zfile2);
1976 do_zipwork(zwork);
1977 free(zwork);
1978 }
1979 }
1980
1981 if (ent->numlogs > 0) {
1982 if (noaction) {
1983 /*
1984 * Note that savelog() may succeed with using link()
1985 * for the archtodir case, but there is no good way
1986 * of knowing if it will when doing "noaction", so
1987 * here we claim that it will have to do a copy...
1988 */
1989 if (archtodir)
1990 printf("\tcp %s %s\n", ent->log, file1);
1991 else
1992 printf("\tln %s %s\n", ent->log, file1);
1993 printf("\ttouch %s\t\t"
1994 "# Update mtime for 'when'-interval processing\n",
1995 file1);
1996 } else {
1997 if (!(flags & CE_BINARY)) {
1998 /* Report the trimming to the old log */
1999 log_trim(ent->log, ent);
2000 }
2001 savelog(ent->log, file1);
2002 /*
2003 * Interval-based rotations are done using the mtime of
2004 * the most recently archived log, so make sure it gets
2005 * updated during a rotation.
2006 */
2007 utimes(file1, NULL);
2008 }
2009 change_attrs(file1, ent);
2010 }
2011
2012 /* Create the new log file and move it into place */
2013 if (noaction)
2014 printf("Start new log...\n");
2015 createlog(ent);
2016
2017 /*
2018 * Save all signalling and file-compression to be done after log
2019 * files from all entries have been rotated. This way any one
2020 * process will not be sent the same signal multiple times when
2021 * multiple log files had to be rotated.
2022 */
2023 swork = NULL;
2024 if (ent->pid_cmd_file != NULL)
2025 swork = save_sigwork(ent);
2026 if (ent->numlogs > 0 && ent->compress > COMPRESS_NONE) {
2027 if (!(ent->flags & CE_PLAIN0) ||
2028 strcmp(&file1[strlen(file1) - 2], ".0") != 0) {
2029 /*
2030 * The zipwork_entry will include a pointer to this
2031 * conf_entry, so the conf_entry should not be freed.
2032 */
2033 free_or_keep = KEEP_ENT;
2034 save_zipwork(ent, swork, ent->fsize, file1);
2035 }
2036 }
2037
2038 return (free_or_keep);
2039 }
2040
2041 static void
do_sigwork(struct sigwork_entry * swork)2042 do_sigwork(struct sigwork_entry *swork)
2043 {
2044 struct sigwork_entry *nextsig;
2045 int kres, secs;
2046 char *tmp;
2047
2048 if (swork->sw_runcmd == 0 && (!(swork->sw_pidok) || swork->sw_pid == 0))
2049 return; /* no work to do... */
2050
2051 /*
2052 * If nosignal (-s) was specified, then do not signal any process.
2053 * Note that a nosignal request triggers a warning message if the
2054 * rotated logfile needs to be compressed, *unless* -R was also
2055 * specified. We assume that an `-sR' request came from a process
2056 * which writes to the logfile, and as such, we assume that process
2057 * has already made sure the logfile is not presently in use. This
2058 * just sets swork->sw_pidok to a special value, and do_zipwork
2059 * will print any necessary warning(s).
2060 */
2061 if (nosignal) {
2062 if (!rotatereq)
2063 swork->sw_pidok = -1;
2064 return;
2065 }
2066
2067 /*
2068 * Compute the pause between consecutive signals. Use a longer
2069 * sleep time if we will be sending two signals to the same
2070 * daemon or process-group.
2071 */
2072 secs = 0;
2073 nextsig = SLIST_NEXT(swork, sw_nextp);
2074 if (nextsig != NULL) {
2075 if (swork->sw_pid == nextsig->sw_pid)
2076 secs = 10;
2077 else
2078 secs = 1;
2079 }
2080
2081 if (noaction) {
2082 if (swork->sw_runcmd)
2083 printf("\tsh -c '%s %d'\n", swork->sw_fname,
2084 swork->sw_signum);
2085 else {
2086 printf("\tkill -%d %d \t\t# %s\n", swork->sw_signum,
2087 (int)swork->sw_pid, swork->sw_fname);
2088 if (secs > 0)
2089 printf("\tsleep %d\n", secs);
2090 }
2091 return;
2092 }
2093
2094 if (swork->sw_runcmd) {
2095 asprintf(&tmp, "%s %d", swork->sw_fname, swork->sw_signum);
2096 if (tmp == NULL) {
2097 warn("can't allocate memory to run %s",
2098 swork->sw_fname);
2099 return;
2100 }
2101 if (verbose)
2102 printf("Run command: %s\n", tmp);
2103 kres = system(tmp);
2104 if (kres) {
2105 warnx("%s: returned non-zero exit code: %d",
2106 tmp, kres);
2107 }
2108 free(tmp);
2109 return;
2110 }
2111
2112 kres = kill(swork->sw_pid, swork->sw_signum);
2113 if (kres != 0) {
2114 /*
2115 * Assume that "no such process" (ESRCH) is something
2116 * to warn about, but is not an error. Presumably the
2117 * process which writes to the rotated log file(s) is
2118 * gone, in which case we should have no problem with
2119 * compressing the rotated log file(s).
2120 */
2121 if (errno != ESRCH)
2122 swork->sw_pidok = 0;
2123 warn("can't notify %s, pid %d = %s", swork->sw_pidtype,
2124 (int)swork->sw_pid, swork->sw_fname);
2125 } else {
2126 if (verbose)
2127 printf("Notified %s pid %d = %s\n", swork->sw_pidtype,
2128 (int)swork->sw_pid, swork->sw_fname);
2129 if (secs > 0) {
2130 if (verbose)
2131 printf("Pause %d second(s) between signals\n",
2132 secs);
2133 sleep(secs);
2134 }
2135 }
2136 }
2137
2138 static void
do_zipwork(struct zipwork_entry * zwork)2139 do_zipwork(struct zipwork_entry *zwork)
2140 {
2141 const struct compress_types *ct;
2142 struct sbuf *command;
2143 pid_t pidzip, wpid;
2144 int c, errsav, fcount, zstatus;
2145 const char **args, *pgm_name, *pgm_path;
2146 char *zresult;
2147
2148 assert(zwork != NULL);
2149 assert(zwork->zw_conf != NULL);
2150 assert(zwork->zw_conf->compress > COMPRESS_NONE);
2151 assert(zwork->zw_conf->compress < COMPRESS_TYPES);
2152 assert(zwork->zw_conf->compress != COMPRESS_LEGACY);
2153
2154 if (zwork->zw_swork != NULL && zwork->zw_swork->sw_runcmd == 0 &&
2155 zwork->zw_swork->sw_pidok <= 0) {
2156 warnx(
2157 "log %s not compressed because daemon(s) not notified",
2158 zwork->zw_fname);
2159 change_attrs(zwork->zw_fname, zwork->zw_conf);
2160 return;
2161 }
2162
2163 ct = &compress_type[zwork->zw_conf->compress];
2164
2165 /*
2166 * execv will be called with the array [ program, flags ... ,
2167 * filename, NULL ] so allocate nflags+3 elements for the array.
2168 */
2169 args = calloc(ct->nflags + 3, sizeof(*args));
2170 if (args == NULL)
2171 err(1, "calloc");
2172
2173 pgm_path = ct->path;
2174 pgm_name = strrchr(pgm_path, '/');
2175 if (pgm_name == NULL)
2176 pgm_name = pgm_path;
2177 else
2178 pgm_name++;
2179
2180 /* Build the argument array. */
2181 args[0] = pgm_name;
2182 for (c = 0; c < ct->nflags; c++)
2183 args[c + 1] = ct->flags[c];
2184 args[c + 1] = zwork->zw_fname;
2185
2186 /* Also create a space-delimited version if we need to print it. */
2187 if ((command = sbuf_new_auto()) == NULL)
2188 errx(1, "sbuf_new");
2189 sbuf_cpy(command, pgm_path);
2190 for (c = 1; args[c] != NULL; c++) {
2191 sbuf_putc(command, ' ');
2192 sbuf_cat(command, args[c]);
2193 }
2194 if (sbuf_finish(command) == -1)
2195 err(1, "sbuf_finish");
2196
2197 /* Determine the filename of the compressed file. */
2198 asprintf(&zresult, "%s%s", zwork->zw_fname, ct->suffix);
2199 if (zresult == NULL)
2200 errx(1, "asprintf");
2201
2202 if (verbose)
2203 printf("Executing: %s\n", sbuf_data(command));
2204
2205 if (noaction) {
2206 printf("\t%s %s\n", pgm_name, zwork->zw_fname);
2207 change_attrs(zresult, zwork->zw_conf);
2208 goto out;
2209 }
2210
2211 fcount = 1;
2212 pidzip = fork();
2213 while (pidzip < 0) {
2214 /*
2215 * The fork failed. If the failure was due to a temporary
2216 * problem, then wait a short time and try it again.
2217 */
2218 errsav = errno;
2219 warn("fork() for `%s %s'", pgm_name, zwork->zw_fname);
2220 if (errsav != EAGAIN || fcount > 5)
2221 errx(1, "Exiting...");
2222 sleep(fcount * 12);
2223 fcount++;
2224 pidzip = fork();
2225 }
2226 if (!pidzip) {
2227 /* The child process executes the compression command */
2228 execv(pgm_path, __DECONST(char *const*, args));
2229 err(1, "execv(`%s')", sbuf_data(command));
2230 }
2231
2232 wpid = waitpid(pidzip, &zstatus, 0);
2233 if (wpid == -1) {
2234 /* XXX - should this be a fatal error? */
2235 warn("%s: waitpid(%d)", pgm_path, pidzip);
2236 goto out;
2237 }
2238 if (!WIFEXITED(zstatus)) {
2239 warnx("`%s' did not terminate normally", sbuf_data(command));
2240 goto out;
2241 }
2242 if (WEXITSTATUS(zstatus)) {
2243 warnx("`%s' terminated with a non-zero status (%d)",
2244 sbuf_data(command), WEXITSTATUS(zstatus));
2245 goto out;
2246 }
2247
2248 /* Compression was successful, set file attributes on the result. */
2249 change_attrs(zresult, zwork->zw_conf);
2250
2251 out:
2252 sbuf_delete(command);
2253 free(args);
2254 free(zresult);
2255 }
2256
2257 /*
2258 * Save information on any process we need to signal. Any single
2259 * process may need to be sent different signal-values for different
2260 * log files, but usually a single signal-value will cause the process
2261 * to close and re-open all of its log files.
2262 */
2263 static struct sigwork_entry *
save_sigwork(const struct conf_entry * ent)2264 save_sigwork(const struct conf_entry *ent)
2265 {
2266 struct sigwork_entry *sprev, *stmp;
2267 int ndiff;
2268 size_t tmpsiz;
2269
2270 sprev = NULL;
2271 ndiff = 1;
2272 SLIST_FOREACH(stmp, &swhead, sw_nextp) {
2273 ndiff = strcmp(ent->pid_cmd_file, stmp->sw_fname);
2274 if (ndiff > 0)
2275 break;
2276 if (ndiff == 0) {
2277 if (ent->sig == stmp->sw_signum)
2278 break;
2279 if (ent->sig > stmp->sw_signum) {
2280 ndiff = 1;
2281 break;
2282 }
2283 }
2284 sprev = stmp;
2285 }
2286 if (stmp != NULL && ndiff == 0)
2287 return (stmp);
2288
2289 tmpsiz = sizeof(struct sigwork_entry) + strlen(ent->pid_cmd_file) + 1;
2290 stmp = malloc(tmpsiz);
2291
2292 stmp->sw_runcmd = 0;
2293 /* If this is a command to run we just set the flag and run command */
2294 if (ent->flags & CE_PID2CMD) {
2295 stmp->sw_pid = -1;
2296 stmp->sw_pidok = 0;
2297 stmp->sw_runcmd = 1;
2298 } else {
2299 set_swpid(stmp, ent);
2300 }
2301 stmp->sw_signum = ent->sig;
2302 strcpy(stmp->sw_fname, ent->pid_cmd_file);
2303 if (sprev == NULL)
2304 SLIST_INSERT_HEAD(&swhead, stmp, sw_nextp);
2305 else
2306 SLIST_INSERT_AFTER(sprev, stmp, sw_nextp);
2307 return (stmp);
2308 }
2309
2310 /*
2311 * Save information on any file we need to compress. We may see the same
2312 * file multiple times, so check the full list to avoid duplicates. The
2313 * list itself is sorted smallest-to-largest, because that's the order we
2314 * want to compress the files. If the partition is very low on disk space,
2315 * then the smallest files are the most likely to compress, and compressing
2316 * them first will free up more space for the larger files.
2317 */
2318 static struct zipwork_entry *
save_zipwork(const struct conf_entry * ent,const struct sigwork_entry * swork,int zsize,const char * zipfname)2319 save_zipwork(const struct conf_entry *ent, const struct sigwork_entry *swork,
2320 int zsize, const char *zipfname)
2321 {
2322 struct zipwork_entry *zprev, *ztmp;
2323 int ndiff;
2324 size_t tmpsiz;
2325
2326 /* Compute the size if the caller did not know it. */
2327 if (zsize < 0)
2328 zsize = sizefile(zipfname);
2329
2330 zprev = NULL;
2331 ndiff = 1;
2332 SLIST_FOREACH(ztmp, &zwhead, zw_nextp) {
2333 ndiff = strcmp(zipfname, ztmp->zw_fname);
2334 if (ndiff == 0)
2335 break;
2336 if (zsize > ztmp->zw_fsize)
2337 zprev = ztmp;
2338 }
2339 if (ztmp != NULL && ndiff == 0)
2340 return (ztmp);
2341
2342 tmpsiz = sizeof(struct zipwork_entry) + strlen(zipfname) + 1;
2343 ztmp = malloc(tmpsiz);
2344 ztmp->zw_conf = ent;
2345 ztmp->zw_swork = swork;
2346 ztmp->zw_fsize = zsize;
2347 strcpy(ztmp->zw_fname, zipfname);
2348 if (zprev == NULL)
2349 SLIST_INSERT_HEAD(&zwhead, ztmp, zw_nextp);
2350 else
2351 SLIST_INSERT_AFTER(zprev, ztmp, zw_nextp);
2352 return (ztmp);
2353 }
2354
2355 /* Send a signal to the pid specified by pidfile */
2356 static void
set_swpid(struct sigwork_entry * swork,const struct conf_entry * ent)2357 set_swpid(struct sigwork_entry *swork, const struct conf_entry *ent)
2358 {
2359 FILE *f;
2360 long minok, maxok, rval;
2361 char *endp, *linep, line[BUFSIZ];
2362
2363 minok = MIN_PID;
2364 maxok = MAX_PID;
2365 swork->sw_pidok = 0;
2366 swork->sw_pid = 0;
2367 swork->sw_pidtype = "daemon";
2368 if (ent->flags & CE_SIGNALGROUP) {
2369 /*
2370 * If we are expected to signal a process-group when
2371 * rotating this logfile, then the value read in should
2372 * be the negative of a valid process ID.
2373 */
2374 minok = -MAX_PID;
2375 maxok = -MIN_PID;
2376 swork->sw_pidtype = "process-group";
2377 }
2378
2379 f = fopen(ent->pid_cmd_file, "r");
2380 if (f == NULL) {
2381 if (errno == ENOENT && enforcepid == 0) {
2382 /*
2383 * Warn if the PID file doesn't exist, but do
2384 * not consider it an error. Most likely it
2385 * means the process has been terminated,
2386 * so it should be safe to rotate any log
2387 * files that the process would have been using.
2388 */
2389 swork->sw_pidok = 1;
2390 warnx("pid file doesn't exist: %s", ent->pid_cmd_file);
2391 } else
2392 warn("can't open pid file: %s", ent->pid_cmd_file);
2393 return;
2394 }
2395
2396 if (fgets(line, BUFSIZ, f) == NULL) {
2397 /*
2398 * Warn if the PID file is empty, but do not consider
2399 * it an error. Most likely it means the process has
2400 * terminated, so it should be safe to rotate any
2401 * log files that the process would have been using.
2402 */
2403 if (feof(f) && enforcepid == 0) {
2404 swork->sw_pidok = 1;
2405 warnx("pid/cmd file is empty: %s", ent->pid_cmd_file);
2406 } else
2407 warn("can't read from pid file: %s", ent->pid_cmd_file);
2408 (void)fclose(f);
2409 return;
2410 }
2411 (void)fclose(f);
2412
2413 errno = 0;
2414 linep = line;
2415 while (*linep == ' ')
2416 linep++;
2417 rval = strtol(linep, &endp, 10);
2418 if (*endp != '\0' && !isspacech(*endp)) {
2419 warnx("pid file does not start with a valid number: %s",
2420 ent->pid_cmd_file);
2421 } else if (rval < minok || rval > maxok) {
2422 warnx("bad value '%ld' for process number in %s",
2423 rval, ent->pid_cmd_file);
2424 if (verbose)
2425 warnx("\t(expecting value between %ld and %ld)",
2426 minok, maxok);
2427 } else {
2428 swork->sw_pidok = 1;
2429 swork->sw_pid = rval;
2430 }
2431
2432 return;
2433 }
2434
2435 /* Log the fact that the logs were turned over */
2436 static int
log_trim(const char * logname,const struct conf_entry * log_ent)2437 log_trim(const char *logname, const struct conf_entry *log_ent)
2438 {
2439 FILE *f;
2440 const char *xtra;
2441
2442 if ((f = fopen(logname, "a")) == NULL)
2443 return (-1);
2444 xtra = "";
2445 if (log_ent->def_cfg)
2446 xtra = " using <default> rule";
2447 if (log_ent->flags & CE_RFC5424) {
2448 if (log_ent->firstcreate) {
2449 fprintf(f, "<%d>1 %s %s newsyslog %d - - %s%s\n",
2450 LOG_MAKEPRI(LOG_USER, LOG_INFO),
2451 daytime_rfc5424, hostname, getpid(),
2452 "logfile first created", xtra);
2453 } else if (log_ent->r_reason != NULL) {
2454 fprintf(f, "<%d>1 %s %s newsyslog %d - - %s%s%s\n",
2455 LOG_MAKEPRI(LOG_USER, LOG_INFO),
2456 daytime_rfc5424, hostname, getpid(),
2457 "logfile turned over", log_ent->r_reason, xtra);
2458 } else {
2459 fprintf(f, "<%d>1 %s %s newsyslog %d - - %s%s\n",
2460 LOG_MAKEPRI(LOG_USER, LOG_INFO),
2461 daytime_rfc5424, hostname, getpid(),
2462 "logfile turned over", xtra);
2463 }
2464 } else {
2465 if (log_ent->firstcreate)
2466 fprintf(f,
2467 "%s %.*s newsyslog[%d]: logfile first created%s\n",
2468 daytime, (int)hostname_shortlen, hostname, getpid(),
2469 xtra);
2470 else if (log_ent->r_reason != NULL)
2471 fprintf(f,
2472 "%s %.*s newsyslog[%d]: logfile turned over%s%s\n",
2473 daytime, (int)hostname_shortlen, hostname, getpid(),
2474 log_ent->r_reason, xtra);
2475 else
2476 fprintf(f,
2477 "%s %.*s newsyslog[%d]: logfile turned over%s\n",
2478 daytime, (int)hostname_shortlen, hostname, getpid(),
2479 xtra);
2480 }
2481 if (fclose(f) == EOF)
2482 err(1, "log_trim: fclose");
2483 return (0);
2484 }
2485
2486 /* Return size in kilobytes of a file */
2487 static int
sizefile(const char * file)2488 sizefile(const char *file)
2489 {
2490 struct stat sb;
2491
2492 if (stat(file, &sb) < 0)
2493 return (-1);
2494 return (kbytes(sb.st_size));
2495 }
2496
2497 /*
2498 * Return the mtime of the most recent archive of the logfile, using timestamp
2499 * based filenames.
2500 */
2501 static time_t
mtime_old_timelog(const char * file)2502 mtime_old_timelog(const char *file)
2503 {
2504 struct stat sb;
2505 struct tm tm;
2506 int dir_fd;
2507 time_t t;
2508 struct dirent *dp;
2509 DIR *dirp;
2510 char *logfname, *logfnamebuf, *dir, *dirbuf;
2511
2512 t = -1;
2513
2514 if ((dirbuf = strdup(file)) == NULL) {
2515 warn("strdup() of '%s'", file);
2516 return (t);
2517 }
2518 dir = dirname(dirbuf);
2519 if ((logfnamebuf = strdup(file)) == NULL) {
2520 warn("strdup() of '%s'", file);
2521 free(dirbuf);
2522 return (t);
2523 }
2524 logfname = basename(logfnamebuf);
2525 if (logfname[0] == '/') {
2526 warnx("Invalid log filename '%s'", logfname);
2527 goto out;
2528 }
2529
2530 if ((dirp = opendir(dir)) == NULL) {
2531 warn("Cannot open log directory '%s'", dir);
2532 goto out;
2533 }
2534 dir_fd = dirfd(dirp);
2535 /* Open the archive dir and find the most recent archive of logfname. */
2536 while ((dp = readdir(dirp)) != NULL) {
2537 if (validate_old_timelog(dir_fd, dp, logfname, &tm) == 0)
2538 continue;
2539
2540 if (fstatat(dir_fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
2541 warn("Cannot stat '%s'", file);
2542 continue;
2543 }
2544 if (t < sb.st_mtime)
2545 t = sb.st_mtime;
2546 }
2547 closedir(dirp);
2548
2549 out:
2550 free(dirbuf);
2551 free(logfnamebuf);
2552 return (t);
2553 }
2554
2555 /* Return the age in hours of the most recent archive of the logfile. */
2556 static int
age_old_log(const char * file)2557 age_old_log(const char *file)
2558 {
2559 struct stat sb;
2560 const char *logfile_suffix;
2561 static unsigned int suffix_maxlen = 0;
2562 char *tmp;
2563 size_t tmpsiz;
2564 time_t mtime;
2565 int c;
2566
2567 if (suffix_maxlen == 0) {
2568 for (c = 0; c < COMPRESS_TYPES; c++)
2569 suffix_maxlen = MAX(suffix_maxlen,
2570 strlen(compress_type[c].suffix));
2571 }
2572
2573 tmpsiz = MAXPATHLEN + sizeof(".0") + suffix_maxlen + 1;
2574 tmp = alloca(tmpsiz);
2575
2576 if (archtodir) {
2577 char *p;
2578
2579 /* build name of archive directory into tmp */
2580 if (*archdirname == '/') { /* absolute */
2581 strlcpy(tmp, archdirname, tmpsiz);
2582 } else { /* relative */
2583 /* get directory part of logfile */
2584 strlcpy(tmp, file, tmpsiz);
2585 if ((p = strrchr(tmp, '/')) == NULL)
2586 tmp[0] = '\0';
2587 else
2588 *(p + 1) = '\0';
2589 strlcat(tmp, archdirname, tmpsiz);
2590 }
2591
2592 strlcat(tmp, "/", tmpsiz);
2593
2594 /* get filename part of logfile */
2595 if ((p = strrchr(file, '/')) == NULL)
2596 strlcat(tmp, file, tmpsiz);
2597 else
2598 strlcat(tmp, p + 1, tmpsiz);
2599 } else {
2600 (void) strlcpy(tmp, file, tmpsiz);
2601 }
2602
2603 if (timefnamefmt != NULL) {
2604 mtime = mtime_old_timelog(tmp);
2605 if (mtime == -1)
2606 return (-1);
2607 } else {
2608 strlcat(tmp, ".0", tmpsiz);
2609 logfile_suffix = get_logfile_suffix(tmp);
2610 if (logfile_suffix == NULL)
2611 return (-1);
2612 (void) strlcat(tmp, logfile_suffix, tmpsiz);
2613 if (stat(tmp, &sb) < 0)
2614 return (-1);
2615 mtime = sb.st_mtime;
2616 }
2617
2618 return ((int)(ptimeget_secs(timenow) - mtime + 180) / 3600);
2619 }
2620
2621 /* Skip Over Blanks */
2622 static char *
sob(char * p)2623 sob(char *p)
2624 {
2625 while (p && *p && isspace(*p))
2626 p++;
2627 return (p);
2628 }
2629
2630 /* Skip Over Non-Blanks */
2631 static char *
son(char * p)2632 son(char *p)
2633 {
2634 while (p && *p && !isspace(*p))
2635 p++;
2636 return (p);
2637 }
2638
2639 /* Check if string is actually a number */
2640 static int
isnumberstr(const char * string)2641 isnumberstr(const char *string)
2642 {
2643 while (*string) {
2644 if (!isdigitch(*string++))
2645 return (0);
2646 }
2647 return (1);
2648 }
2649
2650 /* Check if string contains a glob */
2651 static int
isglobstr(const char * string)2652 isglobstr(const char *string)
2653 {
2654 char chr;
2655
2656 while ((chr = *string++)) {
2657 if (chr == '*' || chr == '?' || chr == '[')
2658 return (1);
2659 }
2660 return (0);
2661 }
2662
2663 /*
2664 * Save the active log file under a new name. A link to the new name
2665 * is the quick-and-easy way to do this. If that fails (which it will
2666 * if the destination is on another partition), then make a copy of
2667 * the file to the new location.
2668 */
2669 static void
savelog(char * from,char * to)2670 savelog(char *from, char *to)
2671 {
2672 FILE *src, *dst;
2673 int c, res;
2674
2675 res = link(from, to);
2676 if (res == 0)
2677 return;
2678
2679 if ((src = fopen(from, "r")) == NULL)
2680 err(1, "can't fopen %s for reading", from);
2681 if ((dst = fopen(to, "w")) == NULL)
2682 err(1, "can't fopen %s for writing", to);
2683
2684 while ((c = getc(src)) != EOF) {
2685 if ((putc(c, dst)) == EOF)
2686 err(1, "error writing to %s", to);
2687 }
2688
2689 if (ferror(src))
2690 err(1, "error reading from %s", from);
2691 if ((fclose(src)) != 0)
2692 err(1, "can't fclose %s", to);
2693 if ((fclose(dst)) != 0)
2694 err(1, "can't fclose %s", from);
2695 }
2696
2697 /* create one or more directory components of a path */
2698 static void
createdir(const struct conf_entry * ent,char * dirpart)2699 createdir(const struct conf_entry *ent, char *dirpart)
2700 {
2701 int res;
2702 char *s, *d;
2703 char mkdirpath[MAXPATHLEN];
2704 struct stat st;
2705
2706 s = dirpart;
2707 d = mkdirpath;
2708
2709 for (;;) {
2710 *d++ = *s++;
2711 if (*s != '/' && *s != '\0')
2712 continue;
2713 *d = '\0';
2714 res = lstat(mkdirpath, &st);
2715 if (res != 0) {
2716 if (noaction) {
2717 printf("\tmkdir %s\n", mkdirpath);
2718 } else {
2719 res = mkdir(mkdirpath, 0755);
2720 if (res != 0)
2721 err(1, "Error on mkdir(\"%s\") for -a",
2722 mkdirpath);
2723 }
2724 }
2725 if (*s == '\0')
2726 break;
2727 }
2728 if (verbose) {
2729 if (ent->firstcreate)
2730 printf("Created directory '%s' for new %s\n",
2731 dirpart, ent->log);
2732 else
2733 printf("Created directory '%s' for -a\n", dirpart);
2734 }
2735 }
2736
2737 /*
2738 * Create a new log file, destroying any currently-existing version
2739 * of the log file in the process. If the caller wants a backup copy
2740 * of the file to exist, they should call 'link(logfile,logbackup)'
2741 * before calling this routine.
2742 */
2743 void
createlog(const struct conf_entry * ent)2744 createlog(const struct conf_entry *ent)
2745 {
2746 int fd, failed;
2747 struct stat st;
2748 char *realfile, *slash, tempfile[MAXPATHLEN];
2749
2750 fd = -1;
2751 realfile = ent->log;
2752
2753 /*
2754 * If this log file is being created for the first time (-C option),
2755 * then it may also be true that the parent directory does not exist
2756 * yet. Check, and create that directory if it is missing.
2757 */
2758 if (ent->firstcreate) {
2759 strlcpy(tempfile, realfile, sizeof(tempfile));
2760 slash = strrchr(tempfile, '/');
2761 if (slash != NULL) {
2762 *slash = '\0';
2763 failed = stat(tempfile, &st);
2764 if (failed && errno != ENOENT)
2765 err(1, "Error on stat(%s)", tempfile);
2766 if (failed)
2767 createdir(ent, tempfile);
2768 else if (!S_ISDIR(st.st_mode))
2769 errx(1, "%s exists but is not a directory",
2770 tempfile);
2771 }
2772 }
2773
2774 /*
2775 * First create an unused filename, so it can be chown'ed and
2776 * chmod'ed before it is moved into the real location. mkstemp
2777 * will create the file mode=600 & owned by us. Note that all
2778 * temp files will have a suffix of '.z<something>'.
2779 */
2780 strlcpy(tempfile, realfile, sizeof(tempfile));
2781 strlcat(tempfile, ".zXXXXXX", sizeof(tempfile));
2782 if (noaction)
2783 printf("\tmktemp %s\n", tempfile);
2784 else {
2785 fd = mkstemp(tempfile);
2786 if (fd < 0)
2787 err(1, "can't mkstemp logfile %s", tempfile);
2788
2789 /*
2790 * Add status message to what will become the new log file.
2791 */
2792 if (!(ent->flags & CE_BINARY)) {
2793 if (log_trim(tempfile, ent))
2794 err(1, "can't add status message to log");
2795 }
2796 }
2797
2798 /* Change the owner/group, if we are supposed to */
2799 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2800 if (noaction)
2801 printf("\tchown %u:%u %s\n", ent->uid, ent->gid,
2802 tempfile);
2803 else {
2804 failed = fchown(fd, ent->uid, ent->gid);
2805 if (failed)
2806 err(1, "can't fchown temp file %s", tempfile);
2807 }
2808 }
2809
2810 /* Turn on NODUMP if it was requested in the config-file. */
2811 if (ent->flags & CE_NODUMP) {
2812 if (noaction)
2813 printf("\tchflags nodump %s\n", tempfile);
2814 else {
2815 failed = fchflags(fd, UF_NODUMP);
2816 if (failed) {
2817 warn("log_trim: fchflags(NODUMP)");
2818 }
2819 }
2820 }
2821
2822 /*
2823 * Note that if the real logfile still exists, and if the call
2824 * to rename() fails, then "neither the old file nor the new
2825 * file shall be changed or created" (to quote the standard).
2826 * If the call succeeds, then the file will be replaced without
2827 * any window where some other process might find that the file
2828 * did not exist.
2829 * XXX - ? It may be that for some error conditions, we could
2830 * retry by first removing the realfile and then renaming.
2831 */
2832 if (noaction) {
2833 printf("\tchmod %o %s\n", ent->permissions, tempfile);
2834 printf("\tmv %s %s\n", tempfile, realfile);
2835 } else {
2836 failed = fchmod(fd, ent->permissions);
2837 if (failed)
2838 err(1, "can't fchmod temp file '%s'", tempfile);
2839 failed = rename(tempfile, realfile);
2840 if (failed)
2841 err(1, "can't mv %s to %s", tempfile, realfile);
2842 }
2843
2844 if (fd >= 0)
2845 close(fd);
2846 }
2847
2848 /*
2849 * Change the attributes of a given filename to what was specified in
2850 * the newsyslog.conf entry. This routine is only called for files
2851 * that newsyslog expects that it has created, and thus it is a fatal
2852 * error if this routine finds that the file does not exist.
2853 */
2854 static void
change_attrs(const char * fname,const struct conf_entry * ent)2855 change_attrs(const char *fname, const struct conf_entry *ent)
2856 {
2857 int failed;
2858
2859 if (noaction) {
2860 printf("\tchmod %o %s\n", ent->permissions, fname);
2861
2862 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
2863 printf("\tchown %u:%u %s\n",
2864 ent->uid, ent->gid, fname);
2865
2866 if (ent->flags & CE_NODUMP)
2867 printf("\tchflags nodump %s\n", fname);
2868 return;
2869 }
2870
2871 failed = chmod(fname, ent->permissions);
2872 if (failed) {
2873 if (errno != EPERM)
2874 err(1, "chmod(%s) in change_attrs", fname);
2875 warn("change_attrs couldn't chmod(%s)", fname);
2876 }
2877
2878 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2879 failed = chown(fname, ent->uid, ent->gid);
2880 if (failed)
2881 warn("can't chown %s", fname);
2882 }
2883
2884 if (ent->flags & CE_NODUMP) {
2885 failed = chflags(fname, UF_NODUMP);
2886 if (failed)
2887 warn("can't chflags %s NODUMP", fname);
2888 }
2889 }
2890