newsyslog.c revision 130165
1/* 2 * This file contains changes from the Open Software Foundation. 3 */ 4 5/* 6 * Copyright 1988, 1989 by the Massachusetts Institute of Technology 7 * 8 * Permission to use, copy, modify, and distribute this software and its 9 * documentation for any purpose and without fee is hereby granted, provided 10 * that the above copyright notice appear in all copies and that both that 11 * copyright notice and this permission notice appear in supporting 12 * documentation, and that the names of M.I.T. and the M.I.T. S.I.P.B. not be 13 * used in advertising or publicity pertaining to distribution of the 14 * software without specific, written prior permission. M.I.T. and the M.I.T. 15 * S.I.P.B. make no representations about the suitability of this software 16 * for any purpose. It is provided "as is" without express or implied 17 * warranty. 18 * 19 */ 20 21/* 22 * newsyslog - roll over selected logs at the appropriate time, keeping the a 23 * specified number of backup files around. 24 */ 25 26#include <sys/cdefs.h> 27__FBSDID("$FreeBSD: head/usr.sbin/newsyslog/newsyslog.c 130165 2004-06-07 01:21:30Z gad $"); 28 29#define OSF 30#ifndef COMPRESS_POSTFIX 31#define COMPRESS_POSTFIX ".gz" 32#endif 33#ifndef BZCOMPRESS_POSTFIX 34#define BZCOMPRESS_POSTFIX ".bz2" 35#endif 36 37#include <sys/param.h> 38#include <sys/stat.h> 39#include <sys/wait.h> 40 41#include <ctype.h> 42#include <err.h> 43#include <errno.h> 44#include <fcntl.h> 45#include <fnmatch.h> 46#include <glob.h> 47#include <grp.h> 48#include <paths.h> 49#include <pwd.h> 50#include <signal.h> 51#include <stdio.h> 52#include <stdlib.h> 53#include <string.h> 54#include <time.h> 55#include <unistd.h> 56 57#include "pathnames.h" 58#include "extern.h" 59 60/* 61 * Bit-values for the 'flags' parsed from a config-file entry. 62 */ 63#define CE_COMPACT 0x0001 /* Compact the achived log files with gzip. */ 64#define CE_BZCOMPACT 0x0002 /* Compact the achived log files with bzip2. */ 65#define CE_COMPACTWAIT 0x0004 /* wait until compressing one file finishes */ 66 /* before starting the next step. */ 67#define CE_BINARY 0x0008 /* Logfile is in binary, do not add status */ 68 /* messages to logfile(s) when rotating. */ 69#define CE_NOSIGNAL 0x0010 /* There is no process to signal when */ 70 /* trimming this file. */ 71#define CE_TRIMAT 0x0020 /* trim file at a specific time. */ 72#define CE_GLOB 0x0040 /* name of the log is file name pattern. */ 73#define CE_SIGNALGROUP 0x0080 /* Signal a process-group instead of a single */ 74 /* process when trimming this file. */ 75#define CE_CREATE 0x0100 /* Create the log file if it does not exist. */ 76#define CE_NODUMP 0x0200 /* Set 'nodump' on newly created log file. */ 77 78#define MIN_PID 5 /* Don't touch pids lower than this */ 79#define MAX_PID 99999 /* was lower, see /usr/include/sys/proc.h */ 80 81#define kbytes(size) (((size) + 1023) >> 10) 82 83#define DEFAULT_MARKER "<default>" 84#define DEBUG_MARKER "<debug>" 85 86struct conf_entry { 87 char *log; /* Name of the log */ 88 char *pid_file; /* PID file */ 89 char *r_reason; /* The reason this file is being rotated */ 90 int firstcreate; /* Creating log for the first time (-C). */ 91 int rotate; /* Non-zero if this file should be rotated */ 92 int fsize; /* size found for the log file */ 93 uid_t uid; /* Owner of log */ 94 gid_t gid; /* Group of log */ 95 int numlogs; /* Number of logs to keep */ 96 int trsize; /* Size cutoff to trigger trimming the log */ 97 int hours; /* Hours between log trimming */ 98 struct ptime_data *trim_at; /* Specific time to do trimming */ 99 int permissions; /* File permissions on the log */ 100 int flags; /* CE_COMPACT, CE_BZCOMPACT, CE_BINARY */ 101 int sig; /* Signal to send */ 102 int def_cfg; /* Using the <default> rule for this file */ 103 struct conf_entry *next;/* Linked list pointer */ 104}; 105 106typedef enum { 107 FREE_ENT, KEEP_ENT 108} fk_entry; 109 110int dbg_at_times; /* -D Show details of 'trim_at' code */ 111int dbg_new_order; /* -D Try the 'neworder' of doing the work */ 112 113int archtodir = 0; /* Archive old logfiles to other directory */ 114int createlogs; /* Create (non-GLOB) logfiles which do not */ 115 /* already exist. 1=='for entries with */ 116 /* C flag', 2=='for all entries'. */ 117int verbose = 0; /* Print out what's going on */ 118int needroot = 1; /* Root privs are necessary */ 119int noaction = 0; /* Don't do anything, just show it */ 120int nosignal; /* Do not send any signals */ 121int force = 0; /* Force the trim no matter what */ 122int rotatereq = 0; /* -R = Always rotate the file(s) as given */ 123 /* on the command (this also requires */ 124 /* that a list of files *are* given on */ 125 /* the run command). */ 126char *requestor; /* The name given on a -R request */ 127char *archdirname; /* Directory path to old logfiles archive */ 128const char *conf; /* Configuration file to use */ 129 130struct ptime_data *dbg_timenow; /* A "timenow" value set via -D option */ 131struct ptime_data *timenow; /* The time to use for checking at-fields */ 132 133char hostname[MAXHOSTNAMELEN]; /* hostname */ 134char daytime[16]; /* The current time in human readable form, 135 * used for rotation-tracking messages. */ 136 137static struct conf_entry *get_worklist(char **files); 138static void parse_file(FILE *cf, const char *cfname, struct conf_entry **work_p, 139 struct conf_entry **glob_p, struct conf_entry **defconf_p); 140static char *sob(char *p); 141static char *son(char *p); 142static int isnumberstr(const char *); 143static char *missing_field(char *p, char *errline); 144static void change_attrs(const char *, const struct conf_entry *); 145static fk_entry do_entry(struct conf_entry *); 146static fk_entry do_rotate(const struct conf_entry *); 147static int sizefile(const char *); 148static void expand_globs(struct conf_entry **work_p, 149 struct conf_entry **glob_p); 150static void free_clist(struct conf_entry **firstent); 151static void free_entry(struct conf_entry *ent); 152static struct conf_entry *init_entry(const char *fname, 153 struct conf_entry *src_entry); 154static void parse_args(int argc, char **argv); 155static int parse_doption(const char *doption); 156static void usage(void); 157static int log_trim(const char *logname, const struct conf_entry *log_ent); 158static void compress_log(char *logname, int dowait); 159static void bzcompress_log(char *logname, int dowait); 160static int age_old_log(char *file); 161static int send_signal(const struct conf_entry *ent); 162static void savelog(char *from, char *to); 163static void createdir(const struct conf_entry *ent, char *dirpart); 164static void createlog(const struct conf_entry *ent); 165 166/* 167 * All the following take a parameter of 'int', but expect values in the 168 * range of unsigned char. Define wrappers which take values of type 'char', 169 * whether signed or unsigned, and ensure they end up in the right range. 170 */ 171#define isdigitch(Anychar) isdigit((u_char)(Anychar)) 172#define isprintch(Anychar) isprint((u_char)(Anychar)) 173#define isspacech(Anychar) isspace((u_char)(Anychar)) 174#define tolowerch(Anychar) tolower((u_char)(Anychar)) 175 176int 177main(int argc, char **argv) 178{ 179 fk_entry free_or_keep; 180 struct conf_entry *p, *q; 181 182 parse_args(argc, argv); 183 argc -= optind; 184 argv += optind; 185 186 if (needroot && getuid() && geteuid()) 187 errx(1, "must have root privs"); 188 p = q = get_worklist(argv); 189 190 /* 191 * Rotate all the files which need to be rotated. Note that 192 * some users have *hundreds* of entries in newsyslog.conf! 193 */ 194 while (p) { 195 free_or_keep = do_entry(p); 196 p = p->next; 197 if (free_or_keep == FREE_ENT) 198 free_entry(q); 199 q = p; 200 } 201 202 while (wait(NULL) > 0 || errno == EINTR) 203 ; 204 return (0); 205} 206 207static struct conf_entry * 208init_entry(const char *fname, struct conf_entry *src_entry) 209{ 210 struct conf_entry *tempwork; 211 212 if (verbose > 4) 213 printf("\t--> [creating entry for %s]\n", fname); 214 215 tempwork = malloc(sizeof(struct conf_entry)); 216 if (tempwork == NULL) 217 err(1, "malloc of conf_entry for %s", fname); 218 219 tempwork->log = strdup(fname); 220 if (tempwork->log == NULL) 221 err(1, "strdup for %s", fname); 222 223 if (src_entry != NULL) { 224 tempwork->pid_file = NULL; 225 if (src_entry->pid_file) 226 tempwork->pid_file = strdup(src_entry->pid_file); 227 tempwork->r_reason = NULL; 228 tempwork->firstcreate = 0; 229 tempwork->rotate = 0; 230 tempwork->fsize = -1; 231 tempwork->uid = src_entry->uid; 232 tempwork->gid = src_entry->gid; 233 tempwork->numlogs = src_entry->numlogs; 234 tempwork->trsize = src_entry->trsize; 235 tempwork->hours = src_entry->hours; 236 tempwork->trim_at = NULL; 237 if (src_entry->trim_at != NULL) 238 tempwork->trim_at = ptime_init(src_entry->trim_at); 239 tempwork->permissions = src_entry->permissions; 240 tempwork->flags = src_entry->flags; 241 tempwork->sig = src_entry->sig; 242 tempwork->def_cfg = src_entry->def_cfg; 243 } else { 244 /* Initialize as a "do-nothing" entry */ 245 tempwork->pid_file = NULL; 246 tempwork->r_reason = NULL; 247 tempwork->firstcreate = 0; 248 tempwork->rotate = 0; 249 tempwork->fsize = -1; 250 tempwork->uid = (uid_t)-1; 251 tempwork->gid = (gid_t)-1; 252 tempwork->numlogs = 1; 253 tempwork->trsize = -1; 254 tempwork->hours = -1; 255 tempwork->trim_at = NULL; 256 tempwork->permissions = 0; 257 tempwork->flags = 0; 258 tempwork->sig = SIGHUP; 259 tempwork->def_cfg = 0; 260 } 261 tempwork->next = NULL; 262 263 return (tempwork); 264} 265 266static void 267free_entry(struct conf_entry *ent) 268{ 269 270 if (ent == NULL) 271 return; 272 273 if (ent->log != NULL) { 274 if (verbose > 4) 275 printf("\t--> [freeing entry for %s]\n", ent->log); 276 free(ent->log); 277 ent->log = NULL; 278 } 279 280 if (ent->pid_file != NULL) { 281 free(ent->pid_file); 282 ent->pid_file = NULL; 283 } 284 285 if (ent->r_reason != NULL) { 286 free(ent->r_reason); 287 ent->r_reason = NULL; 288 } 289 290 if (ent->trim_at != NULL) { 291 ptime_free(ent->trim_at); 292 ent->trim_at = NULL; 293 } 294 295 free(ent); 296} 297 298static void 299free_clist(struct conf_entry **firstent) 300{ 301 struct conf_entry *ent, *nextent; 302 303 if (firstent == NULL) 304 return; /* There is nothing to do. */ 305 306 ent = *firstent; 307 firstent = NULL; 308 309 while (ent) { 310 nextent = ent->next; 311 free_entry(ent); 312 ent = nextent; 313 } 314} 315 316static fk_entry 317do_entry(struct conf_entry * ent) 318{ 319#define REASON_MAX 80 320 int modtime; 321 fk_entry free_or_keep; 322 double diffsecs; 323 char temp_reason[REASON_MAX]; 324 325 free_or_keep = FREE_ENT; 326 if (verbose) { 327 if (ent->flags & CE_COMPACT) 328 printf("%s <%dZ>: ", ent->log, ent->numlogs); 329 else if (ent->flags & CE_BZCOMPACT) 330 printf("%s <%dJ>: ", ent->log, ent->numlogs); 331 else 332 printf("%s <%d>: ", ent->log, ent->numlogs); 333 } 334 ent->fsize = sizefile(ent->log); 335 modtime = age_old_log(ent->log); 336 ent->rotate = 0; 337 ent->firstcreate = 0; 338 if (ent->fsize < 0) { 339 /* 340 * If either the C flag or the -C option was specified, 341 * and if we won't be creating the file, then have the 342 * verbose message include a hint as to why the file 343 * will not be created. 344 */ 345 temp_reason[0] = '\0'; 346 if (createlogs > 1) 347 ent->firstcreate = 1; 348 else if ((ent->flags & CE_CREATE) && createlogs) 349 ent->firstcreate = 1; 350 else if (ent->flags & CE_CREATE) 351 strncpy(temp_reason, " (no -C option)", REASON_MAX); 352 else if (createlogs) 353 strncpy(temp_reason, " (no C flag)", REASON_MAX); 354 355 if (ent->firstcreate) { 356 if (verbose) 357 printf("does not exist -> will create.\n"); 358 createlog(ent); 359 } else if (verbose) { 360 printf("does not exist, skipped%s.\n", temp_reason); 361 } 362 } else { 363 if (ent->flags & CE_TRIMAT && !force && !rotatereq) { 364 diffsecs = ptimeget_diff(timenow, ent->trim_at); 365 if (diffsecs < 0.0) { 366 /* trim_at is some time in the future. */ 367 if (verbose) { 368 ptime_adjust4dst(ent->trim_at, 369 timenow); 370 printf("--> will trim at %s", 371 ptimeget_ctime(ent->trim_at)); 372 } 373 return (free_or_keep); 374 } else if (diffsecs >= 3600.0) { 375 /* 376 * trim_at is more than an hour in the past, 377 * so find the next valid trim_at time, and 378 * tell the user what that will be. 379 */ 380 if (verbose && dbg_at_times) 381 printf("\n\t--> prev trim at %s\t", 382 ptimeget_ctime(ent->trim_at)); 383 if (verbose) { 384 ptimeset_nxtime(ent->trim_at); 385 printf("--> will trim at %s", 386 ptimeget_ctime(ent->trim_at)); 387 } 388 return (free_or_keep); 389 } else if (verbose && noaction && dbg_at_times) { 390 /* 391 * If we are just debugging at-times, then 392 * a detailed message is helpful. Also 393 * skip "doing" any commands, since they 394 * would all be turned off by no-action. 395 */ 396 printf("\n\t--> timematch at %s", 397 ptimeget_ctime(ent->trim_at)); 398 return (free_or_keep); 399 } else if (verbose && ent->hours <= 0) { 400 printf("--> time is up\n"); 401 } 402 } 403 if (verbose && (ent->trsize > 0)) 404 printf("size (Kb): %d [%d] ", ent->fsize, ent->trsize); 405 if (verbose && (ent->hours > 0)) 406 printf(" age (hr): %d [%d] ", modtime, ent->hours); 407 408 /* 409 * Figure out if this logfile needs to be rotated. 410 */ 411 temp_reason[0] = '\0'; 412 if (rotatereq) { 413 ent->rotate = 1; 414 snprintf(temp_reason, REASON_MAX, " due to -R from %s", 415 requestor); 416 } else if (force) { 417 ent->rotate = 1; 418 snprintf(temp_reason, REASON_MAX, " due to -F request"); 419 } else if ((ent->trsize > 0) && (ent->fsize >= ent->trsize)) { 420 ent->rotate = 1; 421 snprintf(temp_reason, REASON_MAX, " due to size>%dK", 422 ent->trsize); 423 } else if (ent->hours <= 0 && (ent->flags & CE_TRIMAT)) { 424 ent->rotate = 1; 425 } else if ((ent->hours > 0) && ((modtime >= ent->hours) || 426 (modtime < 0))) { 427 ent->rotate = 1; 428 } 429 430 /* 431 * If the file needs to be rotated, then rotate it. 432 */ 433 if (ent->rotate) { 434 if (temp_reason[0] != '\0') 435 ent->r_reason = strdup(temp_reason); 436 if (verbose) 437 printf("--> trimming log....\n"); 438 if (noaction && !verbose) { 439 if (ent->flags & CE_COMPACT) 440 printf("%s <%dZ>: trimming\n", 441 ent->log, ent->numlogs); 442 else if (ent->flags & CE_BZCOMPACT) 443 printf("%s <%dJ>: trimming\n", 444 ent->log, ent->numlogs); 445 else 446 printf("%s <%d>: trimming\n", 447 ent->log, ent->numlogs); 448 } 449 free_or_keep = do_rotate(ent); 450 } else { 451 if (verbose) 452 printf("--> skipping\n"); 453 } 454 } 455 return (free_or_keep); 456#undef REASON_MAX 457} 458 459/* Send a signal to the pid specified by pidfile */ 460static int 461send_signal(const struct conf_entry *ent) 462{ 463 pid_t target_pid; 464 int did_notify; 465 FILE *f; 466 long minok, maxok, rval; 467 const char *target_name; 468 char *endp, *linep, line[BUFSIZ]; 469 470 did_notify = 0; 471 f = fopen(ent->pid_file, "r"); 472 if (f == NULL) { 473 warn("can't open pid file: %s", ent->pid_file); 474 return (did_notify); 475 /* NOTREACHED */ 476 } 477 478 if (fgets(line, BUFSIZ, f) == NULL) { 479 /* 480 * XXX - If the pid file is empty, is that really a 481 * problem? Wouldn't that mean that the process 482 * has shut down? In that case there would be no 483 * problem with compressing the rotated log file. 484 */ 485 if (feof(f)) 486 warnx("pid file is empty: %s", ent->pid_file); 487 else 488 warn("can't read from pid file: %s", ent->pid_file); 489 (void) fclose(f); 490 return (did_notify); 491 /* NOTREACHED */ 492 } 493 (void) fclose(f); 494 495 target_name = "daemon"; 496 minok = MIN_PID; 497 maxok = MAX_PID; 498 if (ent->flags & CE_SIGNALGROUP) { 499 /* 500 * If we are expected to signal a process-group when 501 * rotating this logfile, then the value read in should 502 * be the negative of a valid process ID. 503 */ 504 target_name = "process-group"; 505 minok = -MAX_PID; 506 maxok = -MIN_PID; 507 } 508 509 errno = 0; 510 linep = line; 511 while (*linep == ' ') 512 linep++; 513 rval = strtol(linep, &endp, 10); 514 if (*endp != '\0' && !isspacech(*endp)) { 515 warnx("pid file does not start with a valid number: %s", 516 ent->pid_file); 517 rval = 0; 518 } else if (rval < minok || rval > maxok) { 519 warnx("bad value '%ld' for process number in %s", 520 rval, ent->pid_file); 521 if (verbose) 522 warnx("\t(expecting value between %ld and %ld)", 523 minok, maxok); 524 rval = 0; 525 } 526 if (rval == 0) { 527 return (did_notify); 528 /* NOTREACHED */ 529 } 530 531 target_pid = rval; 532 533 if (noaction) { 534 did_notify = 1; 535 printf("\tkill -%d %d\n", ent->sig, (int) target_pid); 536 } else if (kill(target_pid, ent->sig)) { 537 /* 538 * XXX - Iff the error was "no such process", should that 539 * really be an error for us? Perhaps the process 540 * is already gone, in which case there would be no 541 * problem with compressing the rotated log file. 542 */ 543 warn("can't notify %s, pid %d", target_name, 544 (int) target_pid); 545 } else { 546 did_notify = 1; 547 if (verbose) 548 printf("%s pid %d notified\n", target_name, 549 (int) target_pid); 550 } 551 552 return (did_notify); 553} 554 555static void 556parse_args(int argc, char **argv) 557{ 558 int ch; 559 char *p; 560 561 timenow = ptime_init(NULL); 562 ptimeset_time(timenow, time(NULL)); 563 (void)strncpy(daytime, ptimeget_ctime(timenow) + 4, 15); 564 daytime[15] = '\0'; 565 566 /* Let's get our hostname */ 567 (void)gethostname(hostname, sizeof(hostname)); 568 569 /* Truncate domain */ 570 if ((p = strchr(hostname, '.')) != NULL) 571 *p = '\0'; 572 573 /* Parse command line options. */ 574 while ((ch = getopt(argc, argv, "a:f:nrsvCD:FR:")) != -1) 575 switch (ch) { 576 case 'a': 577 archtodir++; 578 archdirname = optarg; 579 break; 580 case 'f': 581 conf = optarg; 582 break; 583 case 'n': 584 noaction++; 585 break; 586 case 'r': 587 needroot = 0; 588 break; 589 case 's': 590 nosignal = 1; 591 break; 592 case 'v': 593 verbose++; 594 break; 595 case 'C': 596 /* Useful for things like rc.diskless... */ 597 createlogs++; 598 break; 599 case 'D': 600 /* 601 * Set some debugging option. The specific option 602 * depends on the value of optarg. These options 603 * may come and go without notice or documentation. 604 */ 605 if (parse_doption(optarg)) 606 break; 607 usage(); 608 /* NOTREACHED */ 609 case 'F': 610 force++; 611 break; 612 case 'R': 613 rotatereq++; 614 requestor = strdup(optarg); 615 break; 616 case 'm': /* Used by OpenBSD for "monitor mode" */ 617 default: 618 usage(); 619 /* NOTREACHED */ 620 } 621 622 if (rotatereq) { 623 if (optind == argc) { 624 warnx("At least one filename must be given when -R is specified."); 625 usage(); 626 /* NOTREACHED */ 627 } 628 /* Make sure "requestor" value is safe for a syslog message. */ 629 for (p = requestor; *p != '\0'; p++) { 630 if (!isprintch(*p) && (*p != '\t')) 631 *p = '.'; 632 } 633 } 634 635 if (dbg_timenow) { 636 /* 637 * Note that the 'daytime' variable is not changed. 638 * That is only used in messages that track when a 639 * logfile is rotated, and if a file *is* rotated, 640 * then it will still rotated at the "real now" time. 641 */ 642 ptime_free(timenow); 643 timenow = dbg_timenow; 644 fprintf(stderr, "Debug: Running as if TimeNow is %s", 645 ptimeget_ctime(dbg_timenow)); 646 } 647 648} 649 650/* 651 * These debugging options are mainly meant for developer use, such 652 * as writing regression-tests. They would not be needed by users 653 * during normal operation of newsyslog... 654 */ 655static int 656parse_doption(const char *doption) 657{ 658 const char TN[] = "TN="; 659 int res; 660 661 if (strncmp(doption, TN, sizeof(TN) - 1) == 0) { 662 /* 663 * The "TimeNow" debugging option. This might be off 664 * by an hour when crossing a timezone change. 665 */ 666 dbg_timenow = ptime_init(NULL); 667 res = ptime_relparse(dbg_timenow, PTM_PARSE_ISO8601, 668 time(NULL), doption + sizeof(TN) - 1); 669 if (res == -2) { 670 warnx("Non-existent time specified on -D %s", doption); 671 return (0); /* failure */ 672 } else if (res < 0) { 673 warnx("Malformed time given on -D %s", doption); 674 return (0); /* failure */ 675 } 676 return (1); /* successfully parsed */ 677 678 } 679 680 if (strcmp(doption, "ats") == 0) { 681 dbg_at_times++; 682 return (1); /* successfully parsed */ 683 } 684 685 warnx("Unknown -D (debug) option: '%s'", doption); 686 return (0); /* failure */ 687} 688 689static void 690usage(void) 691{ 692 693 fprintf(stderr, 694 "usage: newsyslog [-CFnrsv] [-a directory] [-f config-file]\n" 695 " [ [-R requestor] filename ... ]\n"); 696 exit(1); 697} 698 699/* 700 * Parse a configuration file and return a linked list of all the logs 701 * which should be processed. 702 */ 703static struct conf_entry * 704get_worklist(char **files) 705{ 706 FILE *f; 707 const char *fname; 708 char **given; 709 struct conf_entry *defconf, *dupent, *ent, *firstnew; 710 struct conf_entry *globlist, *lastnew, *worklist; 711 int gmatch, fnres; 712 713 defconf = globlist = worklist = NULL; 714 715 fname = conf; 716 if (fname == NULL) 717 fname = _PATH_CONF; 718 719 if (strcmp(fname, "-") != 0) 720 f = fopen(fname, "r"); 721 else { 722 f = stdin; 723 fname = "<stdin>"; 724 } 725 if (!f) 726 err(1, "%s", conf); 727 728 parse_file(f, fname, &worklist, &globlist, &defconf); 729 (void) fclose(f); 730 731 /* 732 * All config-file information has been read in and turned into 733 * a worklist and a globlist. If there were no specific files 734 * given on the run command, then the only thing left to do is to 735 * call a routine which finds all files matched by the globlist 736 * and adds them to the worklist. Then return the worklist. 737 */ 738 if (*files == NULL) { 739 expand_globs(&worklist, &globlist); 740 free_clist(&globlist); 741 if (defconf != NULL) 742 free_entry(defconf); 743 return (worklist); 744 /* NOTREACHED */ 745 } 746 747 /* 748 * If newsyslog was given a specific list of files to process, 749 * it may be that some of those files were not listed in any 750 * config file. Those unlisted files should get the default 751 * rotation action. First, create the default-rotation action 752 * if none was found in a system config file. 753 */ 754 if (defconf == NULL) { 755 defconf = init_entry(DEFAULT_MARKER, NULL); 756 defconf->numlogs = 3; 757 defconf->trsize = 50; 758 defconf->permissions = S_IRUSR|S_IWUSR; 759 } 760 761 /* 762 * If newsyslog was run with a list of specific filenames, 763 * then create a new worklist which has only those files in 764 * it, picking up the rotation-rules for those files from 765 * the original worklist. 766 * 767 * XXX - Note that this will copy multiple rules for a single 768 * logfile, if multiple entries are an exact match for 769 * that file. That matches the historic behavior, but do 770 * we want to continue to allow it? If so, it should 771 * probably be handled more intelligently. 772 */ 773 firstnew = lastnew = NULL; 774 for (given = files; *given; ++given) { 775 /* 776 * First try to find exact-matches for this given file. 777 */ 778 gmatch = 0; 779 for (ent = worklist; ent; ent = ent->next) { 780 if (strcmp(ent->log, *given) == 0) { 781 gmatch++; 782 dupent = init_entry(*given, ent); 783 if (!firstnew) 784 firstnew = dupent; 785 else 786 lastnew->next = dupent; 787 lastnew = dupent; 788 } 789 } 790 if (gmatch) { 791 if (verbose > 2) 792 printf("\t+ Matched entry %s\n", *given); 793 continue; 794 } 795 796 /* 797 * There was no exact-match for this given file, so look 798 * for a "glob" entry which does match. 799 */ 800 gmatch = 0; 801 if (verbose > 2 && globlist != NULL) 802 printf("\t+ Checking globs for %s\n", *given); 803 for (ent = globlist; ent; ent = ent->next) { 804 fnres = fnmatch(ent->log, *given, FNM_PATHNAME); 805 if (verbose > 2) 806 printf("\t+ = %d for pattern %s\n", fnres, 807 ent->log); 808 if (fnres == 0) { 809 gmatch++; 810 dupent = init_entry(*given, ent); 811 if (!firstnew) 812 firstnew = dupent; 813 else 814 lastnew->next = dupent; 815 lastnew = dupent; 816 /* This new entry is not a glob! */ 817 dupent->flags &= ~CE_GLOB; 818 /* Only allow a match to one glob-entry */ 819 break; 820 } 821 } 822 if (gmatch) { 823 if (verbose > 2) 824 printf("\t+ Matched %s via %s\n", *given, 825 ent->log); 826 continue; 827 } 828 829 /* 830 * This given file was not found in any config file, so 831 * add a worklist item based on the default entry. 832 */ 833 if (verbose > 2) 834 printf("\t+ No entry matched %s (will use %s)\n", 835 *given, DEFAULT_MARKER); 836 dupent = init_entry(*given, defconf); 837 if (!firstnew) 838 firstnew = dupent; 839 else 840 lastnew->next = dupent; 841 /* Mark that it was *not* found in a config file */ 842 dupent->def_cfg = 1; 843 lastnew = dupent; 844 } 845 846 /* 847 * Free all the entries in the original work list, the list of 848 * glob entries, and the default entry. 849 */ 850 free_clist(&worklist); 851 free_clist(&globlist); 852 free_entry(defconf); 853 854 /* And finally, return a worklist which matches the given files. */ 855 return (firstnew); 856} 857 858/* 859 * Expand the list of entries with filename patterns, and add all files 860 * which match those glob-entries onto the worklist. 861 */ 862static void 863expand_globs(struct conf_entry **work_p, struct conf_entry **glob_p) 864{ 865 int gmatch, gres, i; 866 char *mfname; 867 struct conf_entry *dupent, *ent, *firstmatch, *globent; 868 struct conf_entry *lastmatch; 869 glob_t pglob; 870 struct stat st_fm; 871 872 if ((glob_p == NULL) || (*glob_p == NULL)) 873 return; /* There is nothing to do. */ 874 875 /* 876 * The worklist contains all fully-specified (non-GLOB) names. 877 * 878 * Now expand the list of filename-pattern (GLOB) entries into 879 * a second list, which (by definition) will only match files 880 * that already exist. Do not add a glob-related entry for any 881 * file which already exists in the fully-specified list. 882 */ 883 firstmatch = lastmatch = NULL; 884 for (globent = *glob_p; globent; globent = globent->next) { 885 886 gres = glob(globent->log, GLOB_NOCHECK, NULL, &pglob); 887 if (gres != 0) { 888 warn("cannot expand pattern (%d): %s", gres, 889 globent->log); 890 continue; 891 } 892 893 if (verbose > 2) 894 printf("\t+ Expanding pattern %s\n", globent->log); 895 for (i = 0; i < pglob.gl_matchc; i++) { 896 mfname = pglob.gl_pathv[i]; 897 898 /* See if this file already has a specific entry. */ 899 gmatch = 0; 900 for (ent = *work_p; ent; ent = ent->next) { 901 if (strcmp(mfname, ent->log) == 0) { 902 gmatch++; 903 break; 904 } 905 } 906 if (gmatch) 907 continue; 908 909 /* Make sure the named matched is a file. */ 910 gres = lstat(mfname, &st_fm); 911 if (gres != 0) { 912 /* Error on a file that glob() matched?!? */ 913 warn("Skipping %s - lstat() error", mfname); 914 continue; 915 } 916 if (!S_ISREG(st_fm.st_mode)) { 917 /* We only rotate files! */ 918 if (verbose > 2) 919 printf("\t+ . skipping %s (!file)\n", 920 mfname); 921 continue; 922 } 923 924 if (verbose > 2) 925 printf("\t+ . add file %s\n", mfname); 926 dupent = init_entry(mfname, globent); 927 if (!firstmatch) 928 firstmatch = dupent; 929 else 930 lastmatch->next = dupent; 931 lastmatch = dupent; 932 /* This new entry is not a glob! */ 933 dupent->flags &= ~CE_GLOB; 934 } 935 globfree(&pglob); 936 if (verbose > 2) 937 printf("\t+ Done with pattern %s\n", globent->log); 938 } 939 940 /* Add the list of matched files to the end of the worklist. */ 941 if (!*work_p) 942 *work_p = firstmatch; 943 else { 944 ent = *work_p; 945 while (ent->next) 946 ent = ent->next; 947 ent->next = firstmatch; 948 } 949 950} 951 952/* 953 * Parse a configuration file and update a linked list of all the logs to 954 * process. 955 */ 956static void 957parse_file(FILE *cf, const char *cfname, struct conf_entry **work_p, 958 struct conf_entry **glob_p, struct conf_entry **defconf_p) 959{ 960 char line[BUFSIZ], *parse, *q; 961 char *cp, *errline, *group; 962 struct conf_entry *lastglob, *lastwork, *working; 963 struct passwd *pwd; 964 struct group *grp; 965 int eol, ptm_opts, res, special; 966 967 /* 968 * XXX - for now, assume that only one config file will be read, 969 * ie, this routine is only called one time. 970 */ 971 lastglob = lastwork = NULL; 972 973 errline = NULL; 974 while (fgets(line, BUFSIZ, cf)) { 975 if ((line[0] == '\n') || (line[0] == '#') || 976 (strlen(line) == 0)) 977 continue; 978 if (errline != NULL) 979 free(errline); 980 errline = strdup(line); 981 for (cp = line + 1; *cp != '\0'; cp++) { 982 if (*cp != '#') 983 continue; 984 if (*(cp - 1) == '\\') { 985 strcpy(cp - 1, cp); 986 cp--; 987 continue; 988 } 989 *cp = '\0'; 990 break; 991 } 992 993 q = parse = missing_field(sob(line), errline); 994 parse = son(line); 995 if (!*parse) 996 errx(1, "malformed line (missing fields):\n%s", 997 errline); 998 *parse = '\0'; 999 1000 /* 1001 * Allow people to set debug options via the config file. 1002 * (NOTE: debug optons are undocumented, and may disappear 1003 * at any time, etc). 1004 */ 1005 if (strcasecmp(DEBUG_MARKER, q) == 0) { 1006 q = parse = missing_field(sob(++parse), errline); 1007 parse = son(parse); 1008 if (!*parse) 1009 warnx("debug line specifies no option:\n%s", 1010 errline); 1011 else { 1012 *parse = '\0'; 1013 parse_doption(q); 1014 } 1015 continue; 1016 } 1017 1018 special = 0; 1019 working = init_entry(q, NULL); 1020 if (strcasecmp(DEFAULT_MARKER, q) == 0) { 1021 special = 1; 1022 if (defconf_p == NULL) { 1023 warnx("Ignoring entry for %s in %s!", q, 1024 cfname); 1025 free_entry(working); 1026 continue; 1027 } else if (*defconf_p != NULL) { 1028 warnx("Ignoring duplicate entry for %s!", q); 1029 free_entry(working); 1030 continue; 1031 } 1032 *defconf_p = working; 1033 } 1034 1035 q = parse = missing_field(sob(++parse), errline); 1036 parse = son(parse); 1037 if (!*parse) 1038 errx(1, "malformed line (missing fields):\n%s", 1039 errline); 1040 *parse = '\0'; 1041 if ((group = strchr(q, ':')) != NULL || 1042 (group = strrchr(q, '.')) != NULL) { 1043 *group++ = '\0'; 1044 if (*q) { 1045 if (!(isnumberstr(q))) { 1046 if ((pwd = getpwnam(q)) == NULL) 1047 errx(1, 1048 "error in config file; unknown user:\n%s", 1049 errline); 1050 working->uid = pwd->pw_uid; 1051 } else 1052 working->uid = atoi(q); 1053 } else 1054 working->uid = (uid_t)-1; 1055 1056 q = group; 1057 if (*q) { 1058 if (!(isnumberstr(q))) { 1059 if ((grp = getgrnam(q)) == NULL) 1060 errx(1, 1061 "error in config file; unknown group:\n%s", 1062 errline); 1063 working->gid = grp->gr_gid; 1064 } else 1065 working->gid = atoi(q); 1066 } else 1067 working->gid = (gid_t)-1; 1068 1069 q = parse = missing_field(sob(++parse), errline); 1070 parse = son(parse); 1071 if (!*parse) 1072 errx(1, "malformed line (missing fields):\n%s", 1073 errline); 1074 *parse = '\0'; 1075 } else { 1076 working->uid = (uid_t)-1; 1077 working->gid = (gid_t)-1; 1078 } 1079 1080 if (!sscanf(q, "%o", &working->permissions)) 1081 errx(1, "error in config file; bad permissions:\n%s", 1082 errline); 1083 1084 q = parse = missing_field(sob(++parse), errline); 1085 parse = son(parse); 1086 if (!*parse) 1087 errx(1, "malformed line (missing fields):\n%s", 1088 errline); 1089 *parse = '\0'; 1090 if (!sscanf(q, "%d", &working->numlogs) || working->numlogs < 0) 1091 errx(1, "error in config file; bad value for count of logs to save:\n%s", 1092 errline); 1093 1094 q = parse = missing_field(sob(++parse), errline); 1095 parse = son(parse); 1096 if (!*parse) 1097 errx(1, "malformed line (missing fields):\n%s", 1098 errline); 1099 *parse = '\0'; 1100 if (isdigitch(*q)) 1101 working->trsize = atoi(q); 1102 else if (strcmp(q, "*") == 0) 1103 working->trsize = -1; 1104 else { 1105 warnx("Invalid value of '%s' for 'size' in line:\n%s", 1106 q, errline); 1107 working->trsize = -1; 1108 } 1109 1110 working->flags = 0; 1111 q = parse = missing_field(sob(++parse), errline); 1112 parse = son(parse); 1113 eol = !*parse; 1114 *parse = '\0'; 1115 { 1116 char *ep; 1117 u_long ul; 1118 1119 ul = strtoul(q, &ep, 10); 1120 if (ep == q) 1121 working->hours = 0; 1122 else if (*ep == '*') 1123 working->hours = -1; 1124 else if (ul > INT_MAX) 1125 errx(1, "interval is too large:\n%s", errline); 1126 else 1127 working->hours = ul; 1128 1129 if (*ep == '\0' || strcmp(ep, "*") == 0) 1130 goto no_trimat; 1131 if (*ep != '@' && *ep != '$') 1132 errx(1, "malformed interval/at:\n%s", errline); 1133 1134 working->flags |= CE_TRIMAT; 1135 working->trim_at = ptime_init(NULL); 1136 ptm_opts = PTM_PARSE_ISO8601; 1137 if (*ep == '$') 1138 ptm_opts = PTM_PARSE_DWM; 1139 ptm_opts |= PTM_PARSE_MATCHDOM; 1140 res = ptime_relparse(working->trim_at, ptm_opts, 1141 ptimeget_secs(timenow), ep + 1); 1142 if (res == -2) 1143 errx(1, "nonexistent time for 'at' value:\n%s", 1144 errline); 1145 else if (res < 0) 1146 errx(1, "malformed 'at' value:\n%s", errline); 1147 } 1148no_trimat: 1149 1150 if (eol) 1151 q = NULL; 1152 else { 1153 q = parse = sob(++parse); /* Optional field */ 1154 parse = son(parse); 1155 if (!*parse) 1156 eol = 1; 1157 *parse = '\0'; 1158 } 1159 1160 for (; q && *q && !isspacech(*q); q++) { 1161 switch (tolowerch(*q)) { 1162 case 'b': 1163 working->flags |= CE_BINARY; 1164 break; 1165 case 'c': 1166 /* 1167 * XXX - Ick! Ugly! Remove ASAP! 1168 * We want `c' and `C' for "create". But we 1169 * will temporarily treat `c' as `g', because 1170 * FreeBSD releases <= 4.8 have a typo of 1171 * checking ('G' || 'c') for CE_GLOB. 1172 */ 1173 if (*q == 'c') { 1174 warnx("Assuming 'g' for 'c' in flags for line:\n%s", 1175 errline); 1176 warnx("The 'c' flag will eventually mean 'CREATE'"); 1177 working->flags |= CE_GLOB; 1178 break; 1179 } 1180 working->flags |= CE_CREATE; 1181 break; 1182 case 'd': 1183 working->flags |= CE_NODUMP; 1184 break; 1185 case 'g': 1186 working->flags |= CE_GLOB; 1187 break; 1188 case 'j': 1189 working->flags |= CE_BZCOMPACT; 1190 break; 1191 case 'n': 1192 working->flags |= CE_NOSIGNAL; 1193 break; 1194 case 'u': 1195 working->flags |= CE_SIGNALGROUP; 1196 break; 1197 case 'w': 1198 working->flags |= CE_COMPACTWAIT; 1199 break; 1200 case 'z': 1201 working->flags |= CE_COMPACT; 1202 break; 1203 case '-': 1204 break; 1205 case 'f': /* Used by OpenBSD for "CE_FOLLOW" */ 1206 case 'm': /* Used by OpenBSD for "CE_MONITOR" */ 1207 case 'p': /* Used by NetBSD for "CE_PLAIN0" */ 1208 default: 1209 errx(1, "illegal flag in config file -- %c", 1210 *q); 1211 } 1212 } 1213 1214 if (eol) 1215 q = NULL; 1216 else { 1217 q = parse = sob(++parse); /* Optional field */ 1218 parse = son(parse); 1219 if (!*parse) 1220 eol = 1; 1221 *parse = '\0'; 1222 } 1223 1224 working->pid_file = NULL; 1225 if (q && *q) { 1226 if (*q == '/') 1227 working->pid_file = strdup(q); 1228 else if (isdigit(*q)) 1229 goto got_sig; 1230 else 1231 errx(1, 1232 "illegal pid file or signal number in config file:\n%s", 1233 errline); 1234 } 1235 if (eol) 1236 q = NULL; 1237 else { 1238 q = parse = sob(++parse); /* Optional field */ 1239 *(parse = son(parse)) = '\0'; 1240 } 1241 1242 working->sig = SIGHUP; 1243 if (q && *q) { 1244 if (isdigit(*q)) { 1245 got_sig: 1246 working->sig = atoi(q); 1247 } else { 1248 err_sig: 1249 errx(1, 1250 "illegal signal number in config file:\n%s", 1251 errline); 1252 } 1253 if (working->sig < 1 || working->sig >= NSIG) 1254 goto err_sig; 1255 } 1256 1257 /* 1258 * Finish figuring out what pid-file to use (if any) in 1259 * later processing if this logfile needs to be rotated. 1260 */ 1261 if ((working->flags & CE_NOSIGNAL) == CE_NOSIGNAL) { 1262 /* 1263 * This config-entry specified 'n' for nosignal, 1264 * see if it also specified an explicit pid_file. 1265 * This would be a pretty pointless combination. 1266 */ 1267 if (working->pid_file != NULL) { 1268 warnx("Ignoring '%s' because flag 'n' was specified in line:\n%s", 1269 working->pid_file, errline); 1270 free(working->pid_file); 1271 working->pid_file = NULL; 1272 } 1273 } else if (working->pid_file == NULL) { 1274 /* 1275 * This entry did not specify the 'n' flag, which 1276 * means it should signal syslogd unless it had 1277 * specified some other pid-file (and obviously the 1278 * syslog pid-file will not be for a process-group). 1279 * Also, we should only try to notify syslog if we 1280 * are root. 1281 */ 1282 if (working->flags & CE_SIGNALGROUP) { 1283 warnx("Ignoring flag 'U' in line:\n%s", 1284 errline); 1285 working->flags &= ~CE_SIGNALGROUP; 1286 } 1287 if (needroot) 1288 working->pid_file = strdup(_PATH_SYSLOGPID); 1289 } 1290 1291 /* 1292 * Add this entry to the appropriate list of entries, unless 1293 * it was some kind of special entry (eg: <default>). 1294 */ 1295 if (special) { 1296 ; /* Do not add to any list */ 1297 } else if (working->flags & CE_GLOB) { 1298 if (!*glob_p) 1299 *glob_p = working; 1300 else 1301 lastglob->next = working; 1302 lastglob = working; 1303 } else { 1304 if (!*work_p) 1305 *work_p = working; 1306 else 1307 lastwork->next = working; 1308 lastwork = working; 1309 } 1310 } 1311 if (errline != NULL) 1312 free(errline); 1313} 1314 1315static char * 1316missing_field(char *p, char *errline) 1317{ 1318 1319 if (!p || !*p) 1320 errx(1, "missing field in config file:\n%s", errline); 1321 return (p); 1322} 1323 1324static fk_entry 1325do_rotate(const struct conf_entry *ent) 1326{ 1327 char dirpart[MAXPATHLEN], namepart[MAXPATHLEN]; 1328 char file1[MAXPATHLEN], file2[MAXPATHLEN]; 1329 char zfile1[MAXPATHLEN], zfile2[MAXPATHLEN]; 1330 char jfile1[MAXPATHLEN]; 1331 int flags, notified, need_notification, numlogs_c; 1332 fk_entry free_or_keep; 1333 struct stat st; 1334 1335 flags = ent->flags; 1336 free_or_keep = FREE_ENT; 1337 1338 if (archtodir) { 1339 char *p; 1340 1341 /* build complete name of archive directory into dirpart */ 1342 if (*archdirname == '/') { /* absolute */ 1343 strlcpy(dirpart, archdirname, sizeof(dirpart)); 1344 } else { /* relative */ 1345 /* get directory part of logfile */ 1346 strlcpy(dirpart, ent->log, sizeof(dirpart)); 1347 if ((p = rindex(dirpart, '/')) == NULL) 1348 dirpart[0] = '\0'; 1349 else 1350 *(p + 1) = '\0'; 1351 strlcat(dirpart, archdirname, sizeof(dirpart)); 1352 } 1353 1354 /* check if archive directory exists, if not, create it */ 1355 if (lstat(dirpart, &st)) 1356 createdir(ent, dirpart); 1357 1358 /* get filename part of logfile */ 1359 if ((p = rindex(ent->log, '/')) == NULL) 1360 strlcpy(namepart, ent->log, sizeof(namepart)); 1361 else 1362 strlcpy(namepart, p + 1, sizeof(namepart)); 1363 1364 /* name of oldest log */ 1365 (void) snprintf(file1, sizeof(file1), "%s/%s.%d", dirpart, 1366 namepart, ent->numlogs); 1367 (void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1, 1368 COMPRESS_POSTFIX); 1369 snprintf(jfile1, sizeof(jfile1), "%s%s", file1, 1370 BZCOMPRESS_POSTFIX); 1371 } else { 1372 /* name of oldest log */ 1373 (void) snprintf(file1, sizeof(file1), "%s.%d", ent->log, 1374 ent->numlogs); 1375 (void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1, 1376 COMPRESS_POSTFIX); 1377 snprintf(jfile1, sizeof(jfile1), "%s%s", file1, 1378 BZCOMPRESS_POSTFIX); 1379 } 1380 1381 if (noaction) { 1382 printf("\trm -f %s\n", file1); 1383 printf("\trm -f %s\n", zfile1); 1384 printf("\trm -f %s\n", jfile1); 1385 } else { 1386 (void) unlink(file1); 1387 (void) unlink(zfile1); 1388 (void) unlink(jfile1); 1389 } 1390 1391 /* Move down log files */ 1392 numlogs_c = ent->numlogs; /* copy for countdown */ 1393 while (numlogs_c--) { 1394 1395 (void) strlcpy(file2, file1, sizeof(file2)); 1396 1397 if (archtodir) 1398 (void) snprintf(file1, sizeof(file1), "%s/%s.%d", 1399 dirpart, namepart, numlogs_c); 1400 else 1401 (void) snprintf(file1, sizeof(file1), "%s.%d", 1402 ent->log, numlogs_c); 1403 1404 (void) strlcpy(zfile1, file1, sizeof(zfile1)); 1405 (void) strlcpy(zfile2, file2, sizeof(zfile2)); 1406 if (lstat(file1, &st)) { 1407 (void) strlcat(zfile1, COMPRESS_POSTFIX, 1408 sizeof(zfile1)); 1409 (void) strlcat(zfile2, COMPRESS_POSTFIX, 1410 sizeof(zfile2)); 1411 if (lstat(zfile1, &st)) { 1412 strlcpy(zfile1, file1, sizeof(zfile1)); 1413 strlcpy(zfile2, file2, sizeof(zfile2)); 1414 strlcat(zfile1, BZCOMPRESS_POSTFIX, 1415 sizeof(zfile1)); 1416 strlcat(zfile2, BZCOMPRESS_POSTFIX, 1417 sizeof(zfile2)); 1418 if (lstat(zfile1, &st)) 1419 continue; 1420 } 1421 } 1422 if (noaction) 1423 printf("\tmv %s %s\n", zfile1, zfile2); 1424 else { 1425 /* XXX - Ought to be checking for failure! */ 1426 (void)rename(zfile1, zfile2); 1427 } 1428 change_attrs(zfile2, ent); 1429 } 1430 1431 if (ent->numlogs > 0) { 1432 if (noaction) { 1433 /* 1434 * Note that savelog() may succeed with using link() 1435 * for the archtodir case, but there is no good way 1436 * of knowing if it will when doing "noaction", so 1437 * here we claim that it will have to do a copy... 1438 */ 1439 if (archtodir) 1440 printf("\tcp %s %s\n", ent->log, file1); 1441 else 1442 printf("\tln %s %s\n", ent->log, file1); 1443 } else { 1444 if (!(flags & CE_BINARY)) { 1445 /* Report the trimming to the old log */ 1446 log_trim(ent->log, ent); 1447 } 1448 savelog(ent->log, file1); 1449 } 1450 change_attrs(file1, ent); 1451 } 1452 1453 /* Create the new log file and move it into place */ 1454 if (noaction) 1455 printf("Start new log...\n"); 1456 createlog(ent); 1457 1458 /* 1459 * Find out if there is a process to signal. If nosignal (-s) was 1460 * specified, then do not signal any process. Note that nosignal 1461 * will trigger a warning message if the rotated logfile needs to 1462 * be compressed, *unless* -R was specified. This is because there 1463 * presumably still are process(es) writing to the old logfile, but 1464 * we assume that a -sR request comes from a process which writes 1465 * to the logfile, and as such, that process has already made sure 1466 * that the logfile is not presently in use. 1467 */ 1468 need_notification = notified = 0; 1469 if (ent->pid_file != NULL) { 1470 need_notification = 1; 1471 if (!nosignal) 1472 notified = send_signal(ent); /* the normal case! */ 1473 else if (rotatereq) 1474 need_notification = 0; 1475 } 1476 1477 if ((flags & CE_COMPACT) || (flags & CE_BZCOMPACT)) { 1478 if (need_notification && !notified) 1479 warnx( 1480 "log %s.0 not compressed because daemon(s) not notified", 1481 ent->log); 1482 else if (noaction) { 1483 printf("\tsleep 10\n"); 1484 if (flags & CE_COMPACT) 1485 printf("\tgzip %s.0\n", ent->log); 1486 else 1487 printf("\tbzip2 %s.0\n", ent->log); 1488 } else { 1489 if (notified) { 1490 if (verbose) 1491 printf("small pause to allow daemon(s) to close log\n"); 1492 sleep(10); 1493 } 1494 if (archtodir) { 1495 (void) snprintf(file1, sizeof(file1), "%s/%s", 1496 dirpart, namepart); 1497 if (flags & CE_COMPACT) 1498 compress_log(file1, 1499 flags & CE_COMPACTWAIT); 1500 else if (flags & CE_BZCOMPACT) 1501 bzcompress_log(file1, 1502 flags & CE_COMPACTWAIT); 1503 } else { 1504 if (flags & CE_COMPACT) 1505 compress_log(ent->log, 1506 flags & CE_COMPACTWAIT); 1507 else if (flags & CE_BZCOMPACT) 1508 bzcompress_log(ent->log, 1509 flags & CE_COMPACTWAIT); 1510 } 1511 } 1512 } 1513 return (free_or_keep); 1514} 1515 1516/* Log the fact that the logs were turned over */ 1517static int 1518log_trim(const char *logname, const struct conf_entry *log_ent) 1519{ 1520 FILE *f; 1521 const char *xtra; 1522 1523 if ((f = fopen(logname, "a")) == NULL) 1524 return (-1); 1525 xtra = ""; 1526 if (log_ent->def_cfg) 1527 xtra = " using <default> rule"; 1528 if (log_ent->firstcreate) 1529 fprintf(f, "%s %s newsyslog[%d]: logfile first created%s\n", 1530 daytime, hostname, (int) getpid(), xtra); 1531 else if (log_ent->r_reason != NULL) 1532 fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s%s\n", 1533 daytime, hostname, (int) getpid(), log_ent->r_reason, xtra); 1534 else 1535 fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s\n", 1536 daytime, hostname, (int) getpid(), xtra); 1537 if (fclose(f) == EOF) 1538 err(1, "log_trim: fclose"); 1539 return (0); 1540} 1541 1542/* 1543 * XXX - Note that both compress_log and bzcompress_log will lose the 1544 * NODUMP flag if it was set on somelog.0. Fixing that in newsyslog 1545 * (as opposed to fixing gzip/bzip2) will require some restructuring 1546 * of the code. That restructuring is planned for a later update... 1547 */ 1548/* Fork of gzip to compress the old log file */ 1549static void 1550compress_log(char *logname, int dowait) 1551{ 1552 pid_t pid; 1553 char tmp[MAXPATHLEN]; 1554 1555 while (dowait && (wait(NULL) > 0 || errno == EINTR)) 1556 ; 1557 (void) snprintf(tmp, sizeof(tmp), "%s.0", logname); 1558 pid = fork(); 1559 if (pid < 0) 1560 err(1, "gzip fork"); 1561 else if (!pid) { 1562 (void) execl(_PATH_GZIP, _PATH_GZIP, "-f", tmp, (char *)0); 1563 err(1, _PATH_GZIP); 1564 } 1565} 1566 1567/* Fork of bzip2 to compress the old log file */ 1568static void 1569bzcompress_log(char *logname, int dowait) 1570{ 1571 pid_t pid; 1572 char tmp[MAXPATHLEN]; 1573 1574 while (dowait && (wait(NULL) > 0 || errno == EINTR)) 1575 ; 1576 snprintf(tmp, sizeof(tmp), "%s.0", logname); 1577 pid = fork(); 1578 if (pid < 0) 1579 err(1, "bzip2 fork"); 1580 else if (!pid) { 1581 execl(_PATH_BZIP2, _PATH_BZIP2, "-f", tmp, (char *)0); 1582 err(1, _PATH_BZIP2); 1583 } 1584} 1585 1586/* Return size in kilobytes of a file */ 1587static int 1588sizefile(const char *file) 1589{ 1590 struct stat sb; 1591 1592 if (stat(file, &sb) < 0) 1593 return (-1); 1594 return (kbytes(dbtob(sb.st_blocks))); 1595} 1596 1597/* Return the age of old log file (file.0) */ 1598static int 1599age_old_log(char *file) 1600{ 1601 struct stat sb; 1602 char *endp; 1603 char tmp[MAXPATHLEN + sizeof(".0") + sizeof(COMPRESS_POSTFIX) + 1604 sizeof(BZCOMPRESS_POSTFIX) + 1]; 1605 1606 if (archtodir) { 1607 char *p; 1608 1609 /* build name of archive directory into tmp */ 1610 if (*archdirname == '/') { /* absolute */ 1611 strlcpy(tmp, archdirname, sizeof(tmp)); 1612 } else { /* relative */ 1613 /* get directory part of logfile */ 1614 strlcpy(tmp, file, sizeof(tmp)); 1615 if ((p = rindex(tmp, '/')) == NULL) 1616 tmp[0] = '\0'; 1617 else 1618 *(p + 1) = '\0'; 1619 strlcat(tmp, archdirname, sizeof(tmp)); 1620 } 1621 1622 strlcat(tmp, "/", sizeof(tmp)); 1623 1624 /* get filename part of logfile */ 1625 if ((p = rindex(file, '/')) == NULL) 1626 strlcat(tmp, file, sizeof(tmp)); 1627 else 1628 strlcat(tmp, p + 1, sizeof(tmp)); 1629 } else { 1630 (void) strlcpy(tmp, file, sizeof(tmp)); 1631 } 1632 1633 strlcat(tmp, ".0", sizeof(tmp)); 1634 if (stat(tmp, &sb) < 0) { 1635 /* 1636 * A plain '.0' file does not exist. Try again, first 1637 * with the added suffix of '.gz', then with an added 1638 * suffix of '.bz2' instead of '.gz'. 1639 */ 1640 endp = strchr(tmp, '\0'); 1641 strlcat(tmp, COMPRESS_POSTFIX, sizeof(tmp)); 1642 if (stat(tmp, &sb) < 0) { 1643 *endp = '\0'; /* Remove .gz */ 1644 strlcat(tmp, BZCOMPRESS_POSTFIX, sizeof(tmp)); 1645 if (stat(tmp, &sb) < 0) 1646 return (-1); 1647 } 1648 } 1649 return ((int)(ptimeget_secs(timenow) - sb.st_mtime + 1800) / 3600); 1650} 1651 1652/* Skip Over Blanks */ 1653static char * 1654sob(char *p) 1655{ 1656 while (p && *p && isspace(*p)) 1657 p++; 1658 return (p); 1659} 1660 1661/* Skip Over Non-Blanks */ 1662static char * 1663son(char *p) 1664{ 1665 while (p && *p && !isspace(*p)) 1666 p++; 1667 return (p); 1668} 1669 1670/* Check if string is actually a number */ 1671static int 1672isnumberstr(const char *string) 1673{ 1674 while (*string) { 1675 if (!isdigitch(*string++)) 1676 return (0); 1677 } 1678 return (1); 1679} 1680 1681/* 1682 * Save the active log file under a new name. A link to the new name 1683 * is the quick-and-easy way to do this. If that fails (which it will 1684 * if the destination is on another partition), then make a copy of 1685 * the file to the new location. 1686 */ 1687static void 1688savelog(char *from, char *to) 1689{ 1690 FILE *src, *dst; 1691 int c, res; 1692 1693 res = link(from, to); 1694 if (res == 0) 1695 return; 1696 1697 if ((src = fopen(from, "r")) == NULL) 1698 err(1, "can't fopen %s for reading", from); 1699 if ((dst = fopen(to, "w")) == NULL) 1700 err(1, "can't fopen %s for writing", to); 1701 1702 while ((c = getc(src)) != EOF) { 1703 if ((putc(c, dst)) == EOF) 1704 err(1, "error writing to %s", to); 1705 } 1706 1707 if (ferror(src)) 1708 err(1, "error reading from %s", from); 1709 if ((fclose(src)) != 0) 1710 err(1, "can't fclose %s", to); 1711 if ((fclose(dst)) != 0) 1712 err(1, "can't fclose %s", from); 1713} 1714 1715/* create one or more directory components of a path */ 1716static void 1717createdir(const struct conf_entry *ent, char *dirpart) 1718{ 1719 int res; 1720 char *s, *d; 1721 char mkdirpath[MAXPATHLEN]; 1722 struct stat st; 1723 1724 s = dirpart; 1725 d = mkdirpath; 1726 1727 for (;;) { 1728 *d++ = *s++; 1729 if (*s != '/' && *s != '\0') 1730 continue; 1731 *d = '\0'; 1732 res = lstat(mkdirpath, &st); 1733 if (res != 0) { 1734 if (noaction) { 1735 printf("\tmkdir %s\n", mkdirpath); 1736 } else { 1737 res = mkdir(mkdirpath, 0755); 1738 if (res != 0) 1739 err(1, "Error on mkdir(\"%s\") for -a", 1740 mkdirpath); 1741 } 1742 } 1743 if (*s == '\0') 1744 break; 1745 } 1746 if (verbose) { 1747 if (ent->firstcreate) 1748 printf("Created directory '%s' for new %s\n", 1749 dirpart, ent->log); 1750 else 1751 printf("Created directory '%s' for -a\n", dirpart); 1752 } 1753} 1754 1755/* 1756 * Create a new log file, destroying any currently-existing version 1757 * of the log file in the process. If the caller wants a backup copy 1758 * of the file to exist, they should call 'link(logfile,logbackup)' 1759 * before calling this routine. 1760 */ 1761void 1762createlog(const struct conf_entry *ent) 1763{ 1764 int fd, failed; 1765 struct stat st; 1766 char *realfile, *slash, tempfile[MAXPATHLEN]; 1767 1768 fd = -1; 1769 realfile = ent->log; 1770 1771 /* 1772 * If this log file is being created for the first time (-C option), 1773 * then it may also be true that the parent directory does not exist 1774 * yet. Check, and create that directory if it is missing. 1775 */ 1776 if (ent->firstcreate) { 1777 strlcpy(tempfile, realfile, sizeof(tempfile)); 1778 slash = strrchr(tempfile, '/'); 1779 if (slash != NULL) { 1780 *slash = '\0'; 1781 failed = lstat(tempfile, &st); 1782 if (failed && errno != ENOENT) 1783 err(1, "Error on lstat(%s)", tempfile); 1784 if (failed) 1785 createdir(ent, tempfile); 1786 else if (!S_ISDIR(st.st_mode)) 1787 errx(1, "%s exists but is not a directory", 1788 tempfile); 1789 } 1790 } 1791 1792 /* 1793 * First create an unused filename, so it can be chown'ed and 1794 * chmod'ed before it is moved into the real location. mkstemp 1795 * will create the file mode=600 & owned by us. Note that all 1796 * temp files will have a suffix of '.z<something>'. 1797 */ 1798 strlcpy(tempfile, realfile, sizeof(tempfile)); 1799 strlcat(tempfile, ".zXXXXXX", sizeof(tempfile)); 1800 if (noaction) 1801 printf("\tmktemp %s\n", tempfile); 1802 else { 1803 fd = mkstemp(tempfile); 1804 if (fd < 0) 1805 err(1, "can't mkstemp logfile %s", tempfile); 1806 1807 /* 1808 * Add status message to what will become the new log file. 1809 */ 1810 if (!(ent->flags & CE_BINARY)) { 1811 if (log_trim(tempfile, ent)) 1812 err(1, "can't add status message to log"); 1813 } 1814 } 1815 1816 /* Change the owner/group, if we are supposed to */ 1817 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) { 1818 if (noaction) 1819 printf("\tchown %u:%u %s\n", ent->uid, ent->gid, 1820 tempfile); 1821 else { 1822 failed = fchown(fd, ent->uid, ent->gid); 1823 if (failed) 1824 err(1, "can't fchown temp file %s", tempfile); 1825 } 1826 } 1827 1828 /* Turn on NODUMP if it was requested in the config-file. */ 1829 if (ent->flags & CE_NODUMP) { 1830 if (noaction) 1831 printf("\tchflags nodump %s\n", tempfile); 1832 else { 1833 failed = fchflags(fd, UF_NODUMP); 1834 if (failed) { 1835 warn("log_trim: fchflags(NODUMP)"); 1836 } 1837 } 1838 } 1839 1840 /* 1841 * Note that if the real logfile still exists, and if the call 1842 * to rename() fails, then "neither the old file nor the new 1843 * file shall be changed or created" (to quote the standard). 1844 * If the call succeeds, then the file will be replaced without 1845 * any window where some other process might find that the file 1846 * did not exist. 1847 * XXX - ? It may be that for some error conditions, we could 1848 * retry by first removing the realfile and then renaming. 1849 */ 1850 if (noaction) { 1851 printf("\tchmod %o %s\n", ent->permissions, tempfile); 1852 printf("\tmv %s %s\n", tempfile, realfile); 1853 } else { 1854 failed = fchmod(fd, ent->permissions); 1855 if (failed) 1856 err(1, "can't fchmod temp file '%s'", tempfile); 1857 failed = rename(tempfile, realfile); 1858 if (failed) 1859 err(1, "can't mv %s to %s", tempfile, realfile); 1860 } 1861 1862 if (fd >= 0) 1863 close(fd); 1864} 1865 1866static void 1867change_attrs(const char *fname, const struct conf_entry *ent) 1868{ 1869 int failed; 1870 1871 if (noaction) { 1872 printf("\tchmod %o %s\n", ent->permissions, fname); 1873 1874 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) 1875 printf("\tchown %u:%u %s\n", 1876 ent->uid, ent->gid, fname); 1877 1878 if (ent->flags & CE_NODUMP) 1879 printf("\tchflags nodump %s\n", fname); 1880 return; 1881 } 1882 1883 failed = chmod(fname, ent->permissions); 1884 if (failed) 1885 warn("can't chmod %s", fname); 1886 1887 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) { 1888 failed = chown(fname, ent->uid, ent->gid); 1889 if (failed) 1890 warn("can't chown %s", fname); 1891 } 1892 1893 if (ent->flags & CE_NODUMP) { 1894 failed = chflags(fname, UF_NODUMP); 1895 if (failed) 1896 warn("can't chflags %s NODUMP", fname); 1897 } 1898} 1899