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