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