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