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