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