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