newsyslog.c revision 238520
157429Smarkm/*- 257429Smarkm * ------+---------+---------+-------- + --------+---------+---------+---------* 357429Smarkm * This file includes significant modifications done by: 457429Smarkm * Copyright (c) 2003, 2004 - Garance Alistair Drosehn <gad@FreeBSD.org>. 557429Smarkm * All rights reserved. 657429Smarkm * 757429Smarkm * Redistribution and use in source and binary forms, with or without 857429Smarkm * modification, are permitted provided that the following conditions 957429Smarkm * are met: 1057429Smarkm * 1. Redistributions of source code must retain the above copyright 1157429Smarkm * notice, this list of conditions and the following disclaimer. 1257429Smarkm * 2. Redistributions in binary form must reproduce the above copyright 1357429Smarkm * notice, this list of conditions and the following disclaimer in the 1457432Smarkm * documentation and/or other materials provided with the distribution. 1557429Smarkm * 1657429Smarkm * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 1757429Smarkm * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 1857429Smarkm * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 1957429Smarkm * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE 2057429Smarkm * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 2157429Smarkm * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 2257429Smarkm * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 2357429Smarkm * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 2457429Smarkm * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 2557429Smarkm * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 2657429Smarkm * SUCH DAMAGE. 2757429Smarkm * 2857429Smarkm * ------+---------+---------+-------- + --------+---------+---------+---------* 2957429Smarkm */ 3057429Smarkm 3157429Smarkm/* 3257429Smarkm * This file contains changes from the Open Software Foundation. 3357429Smarkm */ 3457429Smarkm 3557429Smarkm/* 3657429Smarkm * Copyright 1988, 1989 by the Massachusetts Institute of Technology 3757429Smarkm * 3857429Smarkm * Permission to use, copy, modify, and distribute this software and its 3957429Smarkm * documentation for any purpose and without fee is hereby granted, provided 4057429Smarkm * that the above copyright notice appear in all copies and that both that 4157429Smarkm * copyright notice and this permission notice appear in supporting 4257429Smarkm * documentation, and that the names of M.I.T. and the M.I.T. S.I.P.B. not be 4357429Smarkm * used in advertising or publicity pertaining to distribution of the 4457429Smarkm * software without specific, written prior permission. M.I.T. and the M.I.T. 4557429Smarkm * S.I.P.B. make no representations about the suitability of this software 4657429Smarkm * for any purpose. It is provided "as is" without express or implied 4757429Smarkm * warranty. 4857429Smarkm * 4957429Smarkm */ 5057429Smarkm 5157429Smarkm/* 5257429Smarkm * newsyslog - roll over selected logs at the appropriate time, keeping the a 5357429Smarkm * specified number of backup files around. 5457429Smarkm */ 5557429Smarkm 5657429Smarkm#include <sys/cdefs.h> 5757429Smarkm__FBSDID("$FreeBSD: stable/9/usr.sbin/newsyslog/newsyslog.c 238520 2012-07-16 08:16:41Z ae $"); 5857429Smarkm 5957429Smarkm#define OSF 6057429Smarkm 6157429Smarkm#include <sys/param.h> 6257429Smarkm#include <sys/queue.h> 6357429Smarkm#include <sys/stat.h> 6457429Smarkm#include <sys/wait.h> 6557487Speter 6657429Smarkm#include <assert.h> 6757429Smarkm#include <ctype.h> 6857429Smarkm#include <err.h> 6957429Smarkm#include <errno.h> 7057429Smarkm#include <dirent.h> 7157429Smarkm#include <fcntl.h> 7257429Smarkm#include <fnmatch.h> 7357429Smarkm#include <glob.h> 7457429Smarkm#include <grp.h> 7557429Smarkm#include <paths.h> 7657429Smarkm#include <pwd.h> 7757429Smarkm#include <signal.h> 7857429Smarkm#include <stdio.h> 7957429Smarkm#include <libgen.h> 8057429Smarkm#include <stdlib.h> 8157429Smarkm#include <string.h> 8257467Speter#include <time.h> 8357429Smarkm#include <unistd.h> 8457429Smarkm 8557429Smarkm#include "pathnames.h" 8657429Smarkm#include "extern.h" 8757429Smarkm 8857429Smarkm/* 8957429Smarkm * Compression suffixes 9057429Smarkm */ 9157429Smarkm#ifndef COMPRESS_SUFFIX_GZ 9257429Smarkm#define COMPRESS_SUFFIX_GZ ".gz" 9357429Smarkm#endif 9457429Smarkm 9557429Smarkm#ifndef COMPRESS_SUFFIX_BZ2 9657429Smarkm#define COMPRESS_SUFFIX_BZ2 ".bz2" 9757429Smarkm#endif 9857429Smarkm 9957429Smarkm#ifndef COMPRESS_SUFFIX_XZ 10057429Smarkm#define COMPRESS_SUFFIX_XZ ".xz" 10157429Smarkm#endif 10257429Smarkm 10357429Smarkm#define COMPRESS_SUFFIX_MAXLEN MAX(MAX(sizeof(COMPRESS_SUFFIX_GZ),sizeof(COMPRESS_SUFFIX_BZ2)),sizeof(COMPRESS_SUFFIX_XZ)) 10457429Smarkm 10557429Smarkm/* 10657429Smarkm * Compression types 10757429Smarkm */ 10857429Smarkm#define COMPRESS_TYPES 4 /* Number of supported compression types */ 10957429Smarkm 11057429Smarkm#define COMPRESS_NONE 0 11157429Smarkm#define COMPRESS_GZIP 1 11257429Smarkm#define COMPRESS_BZIP2 2 11357429Smarkm#define COMPRESS_XZ 3 11457429Smarkm 11557429Smarkm/* 11657429Smarkm * Bit-values for the 'flags' parsed from a config-file entry. 11757429Smarkm */ 11857429Smarkm#define CE_BINARY 0x0008 /* Logfile is in binary, do not add status */ 11957429Smarkm /* messages to logfile(s) when rotating. */ 12057429Smarkm#define CE_NOSIGNAL 0x0010 /* There is no process to signal when */ 12157429Smarkm /* trimming this file. */ 12257429Smarkm#define CE_TRIMAT 0x0020 /* trim file at a specific time. */ 12357429Smarkm#define CE_GLOB 0x0040 /* name of the log is file name pattern. */ 12457429Smarkm#define CE_SIGNALGROUP 0x0080 /* Signal a process-group instead of a single */ 12557429Smarkm /* process when trimming this file. */ 12657429Smarkm#define CE_CREATE 0x0100 /* Create the log file if it does not exist. */ 12757429Smarkm#define CE_NODUMP 0x0200 /* Set 'nodump' on newly created log file. */ 12857429Smarkm#define CE_PID2CMD 0x0400 /* Replace PID file with a shell command.*/ 12957429Smarkm 13057429Smarkm#define MIN_PID 5 /* Don't touch pids lower than this */ 13157429Smarkm#define MAX_PID 99999 /* was lower, see /usr/include/sys/proc.h */ 13257429Smarkm 13357429Smarkm#define kbytes(size) (((size) + 1023) >> 10) 13457429Smarkm 13557429Smarkm#define DEFAULT_MARKER "<default>" 13657429Smarkm#define DEBUG_MARKER "<debug>" 13757429Smarkm#define INCLUDE_MARKER "<include>" 13857429Smarkm#define DEFAULT_TIMEFNAME_FMT "%Y%m%dT%H%M%S" 13957429Smarkm 14057429Smarkm#define MAX_OLDLOGS 65536 /* Default maximum number of old logfiles */ 14157429Smarkm 14257429Smarkmstruct compress_types { 14357429Smarkm const char *flag; /* Flag in configuration file */ 14457429Smarkm const char *suffix; /* Compression suffix */ 14557429Smarkm const char *path; /* Path to compression program */ 14657429Smarkm}; 14757429Smarkm 14857429Smarkmconst struct compress_types compress_type[COMPRESS_TYPES] = { 14957429Smarkm { "", "", "" }, /* no compression */ 15057429Smarkm { "Z", COMPRESS_SUFFIX_GZ, _PATH_GZIP }, /* gzip compression */ 15157429Smarkm { "J", COMPRESS_SUFFIX_BZ2, _PATH_BZIP2 }, /* bzip2 compression */ 15257429Smarkm { "X", COMPRESS_SUFFIX_XZ, _PATH_XZ } /* xz compression */ 15357429Smarkm}; 15457429Smarkm 15557429Smarkmstruct conf_entry { 15657429Smarkm STAILQ_ENTRY(conf_entry) cf_nextp; 15757429Smarkm char *log; /* Name of the log */ 15857429Smarkm char *pid_cmd_file; /* PID or command file */ 15957429Smarkm char *r_reason; /* The reason this file is being rotated */ 16057429Smarkm int firstcreate; /* Creating log for the first time (-C). */ 16157429Smarkm int rotate; /* Non-zero if this file should be rotated */ 16257429Smarkm int fsize; /* size found for the log file */ 16357429Smarkm uid_t uid; /* Owner of log */ 16457429Smarkm gid_t gid; /* Group of log */ 16557429Smarkm int numlogs; /* Number of logs to keep */ 16657429Smarkm int trsize; /* Size cutoff to trigger trimming the log */ 16757429Smarkm int hours; /* Hours between log trimming */ 16857429Smarkm struct ptime_data *trim_at; /* Specific time to do trimming */ 16957429Smarkm unsigned int permissions; /* File permissions on the log */ 17057429Smarkm int flags; /* CE_BINARY */ 17157429Smarkm int compress; /* Compression */ 17257429Smarkm int sig; /* Signal to send */ 17357429Smarkm int def_cfg; /* Using the <default> rule for this file */ 17457429Smarkm}; 17557429Smarkm 17657429Smarkmstruct sigwork_entry { 17757429Smarkm SLIST_ENTRY(sigwork_entry) sw_nextp; 17857429Smarkm int sw_signum; /* the signal to send */ 17957429Smarkm int sw_pidok; /* true if pid value is valid */ 18057429Smarkm pid_t sw_pid; /* the process id from the PID file */ 18157429Smarkm const char *sw_pidtype; /* "daemon" or "process group" */ 18257429Smarkm int run_cmd; /* run command or send PID to signal */ 18357429Smarkm char sw_fname[1]; /* file the PID was read from or shell cmd */ 18457429Smarkm}; 18557565Smarkm 18657565Smarkmstruct zipwork_entry { 18757429Smarkm SLIST_ENTRY(zipwork_entry) zw_nextp; 18857429Smarkm const struct conf_entry *zw_conf; /* for chown/perm/flag info */ 18957429Smarkm const struct sigwork_entry *zw_swork; /* to know success of signal */ 19057565Smarkm int zw_fsize; /* size of the file to compress */ 19157565Smarkm char zw_fname[1]; /* the file to compress */ 19257565Smarkm}; 19357429Smarkm 19457429Smarkmstruct include_entry { 19557429Smarkm STAILQ_ENTRY(include_entry) inc_nextp; 19657429Smarkm const char *file; /* Name of file to process */ 19757429Smarkm}; 19857429Smarkm 19957429Smarkmstruct oldlog_entry { 20057429Smarkm char *fname; /* Filename of the log file */ 20157429Smarkm time_t t; /* Parsed timestamp of the logfile */ 20257429Smarkm}; 20357429Smarkm 20457429Smarkmtypedef enum { 20557429Smarkm FREE_ENT, KEEP_ENT 20657429Smarkm} fk_entry; 20757429Smarkm 20857429SmarkmSTAILQ_HEAD(cflist, conf_entry); 20957429SmarkmSLIST_HEAD(swlisthead, sigwork_entry) swhead = SLIST_HEAD_INITIALIZER(swhead); 21057429SmarkmSLIST_HEAD(zwlisthead, zipwork_entry) zwhead = SLIST_HEAD_INITIALIZER(zwhead); 21157429SmarkmSTAILQ_HEAD(ilist, include_entry); 21257429Smarkm 21357429Smarkmint dbg_at_times; /* -D Show details of 'trim_at' code */ 21457429Smarkm 21557429Smarkmint archtodir = 0; /* Archive old logfiles to other directory */ 21657429Smarkmint createlogs; /* Create (non-GLOB) logfiles which do not */ 21757429Smarkm /* already exist. 1=='for entries with */ 21857429Smarkm /* C flag', 2=='for all entries'. */ 21957429Smarkmint verbose = 0; /* Print out what's going on */ 22057429Smarkmint needroot = 1; /* Root privs are necessary */ 22157429Smarkmint noaction = 0; /* Don't do anything, just show it */ 22257429Smarkmint norotate = 0; /* Don't rotate */ 22357429Smarkmint nosignal; /* Do not send any signals */ 22457429Smarkmint enforcepid = 0; /* If PID file does not exist or empty, do nothing */ 22557429Smarkmint force = 0; /* Force the trim no matter what */ 22657429Smarkmint rotatereq = 0; /* -R = Always rotate the file(s) as given */ 22757429Smarkm /* on the command (this also requires */ 22857429Smarkm /* that a list of files *are* given on */ 22957429Smarkm /* the run command). */ 23057429Smarkmchar *requestor; /* The name given on a -R request */ 23157429Smarkmchar *timefnamefmt = NULL; /* Use time based filenames instead of .0 etc */ 23257429Smarkmchar *archdirname; /* Directory path to old logfiles archive */ 23357429Smarkmchar *destdir = NULL; /* Directory to treat at root for logs */ 23457429Smarkmconst char *conf; /* Configuration file to use */ 23557429Smarkm 23657429Smarkmstruct ptime_data *dbg_timenow; /* A "timenow" value set via -D option */ 23757429Smarkmstruct ptime_data *timenow; /* The time to use for checking at-fields */ 23857429Smarkm 23957429Smarkm#define DAYTIME_LEN 16 24057429Smarkmchar daytime[DAYTIME_LEN]; /* The current time in human readable form, 24157429Smarkm * used for rotation-tracking messages. */ 24257429Smarkmchar hostname[MAXHOSTNAMELEN]; /* hostname */ 24357429Smarkm 24457429Smarkmconst char *path_syslogpid = _PATH_SYSLOGPID; 24557429Smarkm 24657565Smarkmstatic struct cflist *get_worklist(char **files); 24757565Smarkmstatic void parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p, 24857565Smarkm struct conf_entry *defconf_p, struct ilist *inclist); 24957429Smarkmstatic void add_to_queue(const char *fname, struct ilist *inclist); 25057429Smarkmstatic char *sob(char *p); 25157565Smarkmstatic char *son(char *p); 25257565Smarkmstatic int isnumberstr(const char *); 25357565Smarkmstatic int isglobstr(const char *); 25457565Smarkmstatic char *missing_field(char *p, char *errline); 25557429Smarkmstatic void change_attrs(const char *, const struct conf_entry *); 25657429Smarkmstatic const char *get_logfile_suffix(const char *logfile); 25757429Smarkmstatic fk_entry do_entry(struct conf_entry *); 25857429Smarkmstatic fk_entry do_rotate(const struct conf_entry *); 25957429Smarkmstatic void do_sigwork(struct sigwork_entry *); 26057429Smarkmstatic void do_zipwork(struct zipwork_entry *); 26157429Smarkmstatic struct sigwork_entry * 26257429Smarkm save_sigwork(const struct conf_entry *); 26357429Smarkmstatic struct zipwork_entry * 26457429Smarkm save_zipwork(const struct conf_entry *, const struct 26557429Smarkm sigwork_entry *, int, const char *); 26657429Smarkmstatic void set_swpid(struct sigwork_entry *, const struct conf_entry *); 26757429Smarkmstatic int sizefile(const char *); 26857429Smarkmstatic void expand_globs(struct cflist *work_p, struct cflist *glob_p); 26957429Smarkmstatic void free_clist(struct cflist *list); 27057429Smarkmstatic void free_entry(struct conf_entry *ent); 27157429Smarkmstatic struct conf_entry *init_entry(const char *fname, 27257429Smarkm struct conf_entry *src_entry); 27357429Smarkmstatic void parse_args(int argc, char **argv); 27457429Smarkmstatic int parse_doption(const char *doption); 27557429Smarkmstatic void usage(void); 27657429Smarkmstatic int log_trim(const char *logname, const struct conf_entry *log_ent); 27757429Smarkmstatic int age_old_log(char *file); 27857429Smarkmstatic void savelog(char *from, char *to); 27957429Smarkmstatic void createdir(const struct conf_entry *ent, char *dirpart); 28057429Smarkmstatic void createlog(const struct conf_entry *ent); 28157429Smarkm 28257429Smarkm/* 28357429Smarkm * All the following take a parameter of 'int', but expect values in the 28457429Smarkm * range of unsigned char. Define wrappers which take values of type 'char', 28557429Smarkm * whether signed or unsigned, and ensure they end up in the right range. 28657429Smarkm */ 28757429Smarkm#define isdigitch(Anychar) isdigit((u_char)(Anychar)) 28857429Smarkm#define isprintch(Anychar) isprint((u_char)(Anychar)) 28957429Smarkm#define isspacech(Anychar) isspace((u_char)(Anychar)) 29057429Smarkm#define tolowerch(Anychar) tolower((u_char)(Anychar)) 29157429Smarkm 29257429Smarkmint 29357429Smarkmmain(int argc, char **argv) 29457429Smarkm{ 29557429Smarkm struct cflist *worklist; 29657429Smarkm struct conf_entry *p; 29757429Smarkm struct sigwork_entry *stmp; 29857429Smarkm struct zipwork_entry *ztmp; 29957429Smarkm 30057429Smarkm SLIST_INIT(&swhead); 30157429Smarkm SLIST_INIT(&zwhead); 30257429Smarkm 30357429Smarkm parse_args(argc, argv); 30457429Smarkm argc -= optind; 30557429Smarkm argv += optind; 30657429Smarkm 30757429Smarkm if (needroot && getuid() && geteuid()) 30857429Smarkm errx(1, "must have root privs"); 30957429Smarkm worklist = get_worklist(argv); 31057429Smarkm 31157429Smarkm /* 31257429Smarkm * Rotate all the files which need to be rotated. Note that 31357429Smarkm * some users have *hundreds* of entries in newsyslog.conf! 31457429Smarkm */ 31557429Smarkm while (!STAILQ_EMPTY(worklist)) { 31657429Smarkm p = STAILQ_FIRST(worklist); 31757429Smarkm STAILQ_REMOVE_HEAD(worklist, cf_nextp); 31857429Smarkm if (do_entry(p) == FREE_ENT) 31957429Smarkm free_entry(p); 32057429Smarkm } 32157429Smarkm 32257429Smarkm /* 32357429Smarkm * Send signals to any processes which need a signal to tell 32457429Smarkm * them to close and re-open the log file(s) we have rotated. 32557429Smarkm * Note that zipwork_entries include pointers to these 32657429Smarkm * sigwork_entry's, so we can not free the entries here. 32757429Smarkm */ 32857429Smarkm if (!SLIST_EMPTY(&swhead)) { 32957429Smarkm if (noaction || verbose) 33057429Smarkm printf("Signal all daemon process(es)...\n"); 33157429Smarkm SLIST_FOREACH(stmp, &swhead, sw_nextp) 33257429Smarkm do_sigwork(stmp); 33357429Smarkm if (noaction) 33457429Smarkm printf("\tsleep 10\n"); 33557429Smarkm else { 33657429Smarkm if (verbose) 33757429Smarkm printf("Pause 10 seconds to allow daemon(s)" 33857429Smarkm " to close log file(s)\n"); 33957429Smarkm sleep(10); 34057429Smarkm } 34157429Smarkm } 34257429Smarkm /* 34357429Smarkm * Compress all files that we're expected to compress, now 34457429Smarkm * that all processes should have closed the files which 34557429Smarkm * have been rotated. 34657429Smarkm */ 34757429Smarkm if (!SLIST_EMPTY(&zwhead)) { 34857429Smarkm if (noaction || verbose) 34957429Smarkm printf("Compress all rotated log file(s)...\n"); 35057429Smarkm while (!SLIST_EMPTY(&zwhead)) { 35157429Smarkm ztmp = SLIST_FIRST(&zwhead); 35257429Smarkm do_zipwork(ztmp); 35357429Smarkm SLIST_REMOVE_HEAD(&zwhead, zw_nextp); 35457429Smarkm free(ztmp); 35557429Smarkm } 35657429Smarkm } 35757429Smarkm /* Now free all the sigwork entries. */ 35857429Smarkm while (!SLIST_EMPTY(&swhead)) { 35957429Smarkm stmp = SLIST_FIRST(&swhead); 36057429Smarkm SLIST_REMOVE_HEAD(&swhead, sw_nextp); 36157429Smarkm free(stmp); 36257429Smarkm } 36357429Smarkm 36457429Smarkm while (wait(NULL) > 0 || errno == EINTR) 36557429Smarkm ; 36657429Smarkm return (0); 36757429Smarkm} 36857429Smarkm 36957429Smarkmstatic struct conf_entry * 37057429Smarkminit_entry(const char *fname, struct conf_entry *src_entry) 37157429Smarkm{ 37257429Smarkm struct conf_entry *tempwork; 37357429Smarkm 37457429Smarkm if (verbose > 4) 37557429Smarkm printf("\t--> [creating entry for %s]\n", fname); 37657429Smarkm 37757429Smarkm tempwork = malloc(sizeof(struct conf_entry)); 37857429Smarkm if (tempwork == NULL) 37957429Smarkm err(1, "malloc of conf_entry for %s", fname); 38057429Smarkm 38157429Smarkm if (destdir == NULL || fname[0] != '/') 38257429Smarkm tempwork->log = strdup(fname); 38357429Smarkm else 38457429Smarkm asprintf(&tempwork->log, "%s%s", destdir, fname); 38557429Smarkm if (tempwork->log == NULL) 38657429Smarkm err(1, "strdup for %s", fname); 38757429Smarkm 38857429Smarkm if (src_entry != NULL) { 38957429Smarkm tempwork->pid_cmd_file = NULL; 39057429Smarkm if (src_entry->pid_cmd_file) 39157429Smarkm tempwork->pid_cmd_file = strdup(src_entry->pid_cmd_file); 39257429Smarkm tempwork->r_reason = NULL; 39357429Smarkm tempwork->firstcreate = 0; 39457429Smarkm tempwork->rotate = 0; 39557429Smarkm tempwork->fsize = -1; 39657429Smarkm tempwork->uid = src_entry->uid; 39757429Smarkm tempwork->gid = src_entry->gid; 39857429Smarkm tempwork->numlogs = src_entry->numlogs; 39957429Smarkm tempwork->trsize = src_entry->trsize; 40057429Smarkm tempwork->hours = src_entry->hours; 40157429Smarkm tempwork->trim_at = NULL; 40257429Smarkm if (src_entry->trim_at != NULL) 40357429Smarkm tempwork->trim_at = ptime_init(src_entry->trim_at); 40457429Smarkm tempwork->permissions = src_entry->permissions; 40557429Smarkm tempwork->flags = src_entry->flags; 40657429Smarkm tempwork->compress = src_entry->compress; 40757429Smarkm tempwork->sig = src_entry->sig; 40857429Smarkm tempwork->def_cfg = src_entry->def_cfg; 40957429Smarkm } else { 41057429Smarkm /* Initialize as a "do-nothing" entry */ 41157429Smarkm tempwork->pid_cmd_file = NULL; 41257429Smarkm tempwork->r_reason = NULL; 41357429Smarkm tempwork->firstcreate = 0; 41457429Smarkm tempwork->rotate = 0; 41557429Smarkm tempwork->fsize = -1; 41657429Smarkm tempwork->uid = (uid_t)-1; 41757429Smarkm tempwork->gid = (gid_t)-1; 41857429Smarkm tempwork->numlogs = 1; 41957429Smarkm tempwork->trsize = -1; 42057429Smarkm tempwork->hours = -1; 42157429Smarkm tempwork->trim_at = NULL; 42257429Smarkm tempwork->permissions = 0; 42357429Smarkm tempwork->flags = 0; 42457429Smarkm tempwork->compress = COMPRESS_NONE; 42557429Smarkm tempwork->sig = SIGHUP; 42657429Smarkm tempwork->def_cfg = 0; 42757429Smarkm } 42857429Smarkm 42957429Smarkm return (tempwork); 43057429Smarkm} 43157429Smarkm 43257429Smarkmstatic void 43357429Smarkmfree_entry(struct conf_entry *ent) 43457429Smarkm{ 43557429Smarkm 43657429Smarkm if (ent == NULL) 43757429Smarkm return; 43857429Smarkm 43957429Smarkm if (ent->log != NULL) { 44057429Smarkm if (verbose > 4) 44157429Smarkm printf("\t--> [freeing entry for %s]\n", ent->log); 44257429Smarkm free(ent->log); 44357429Smarkm ent->log = NULL; 44457429Smarkm } 44557429Smarkm 44657429Smarkm if (ent->pid_cmd_file != NULL) { 44757429Smarkm free(ent->pid_cmd_file); 44857429Smarkm ent->pid_cmd_file = NULL; 44957429Smarkm } 45057429Smarkm 45157429Smarkm if (ent->r_reason != NULL) { 45257429Smarkm free(ent->r_reason); 45357429Smarkm ent->r_reason = NULL; 45457429Smarkm } 45557429Smarkm 45657429Smarkm if (ent->trim_at != NULL) { 45757429Smarkm ptime_free(ent->trim_at); 45857429Smarkm ent->trim_at = NULL; 45957429Smarkm } 46057429Smarkm 46157429Smarkm free(ent); 46257429Smarkm} 46357429Smarkm 46457429Smarkmstatic void 46557429Smarkmfree_clist(struct cflist *list) 46657429Smarkm{ 46757429Smarkm struct conf_entry *ent; 46857429Smarkm 46957429Smarkm while (!STAILQ_EMPTY(list)) { 47057429Smarkm ent = STAILQ_FIRST(list); 47157429Smarkm STAILQ_REMOVE_HEAD(list, cf_nextp); 47257429Smarkm free_entry(ent); 47357429Smarkm } 47457429Smarkm 47557429Smarkm free(list); 47657429Smarkm list = NULL; 47757429Smarkm} 47857429Smarkm 47957429Smarkmstatic fk_entry 48057429Smarkmdo_entry(struct conf_entry * ent) 48157429Smarkm{ 48257429Smarkm#define REASON_MAX 80 48357429Smarkm int modtime; 48457429Smarkm fk_entry free_or_keep; 48557429Smarkm double diffsecs; 48657429Smarkm char temp_reason[REASON_MAX]; 48757429Smarkm int oversized; 48857429Smarkm 48957429Smarkm free_or_keep = FREE_ENT; 49057429Smarkm if (verbose) 49157429Smarkm printf("%s <%d%s>: ", ent->log, ent->numlogs, 49257429Smarkm compress_type[ent->compress].flag); 49357429Smarkm ent->fsize = sizefile(ent->log); 49457429Smarkm oversized = ((ent->trsize > 0) && (ent->fsize >= ent->trsize)); 49557429Smarkm modtime = age_old_log(ent->log); 49657429Smarkm ent->rotate = 0; 49757429Smarkm ent->firstcreate = 0; 49857429Smarkm if (ent->fsize < 0) { 49957429Smarkm /* 50057429Smarkm * If either the C flag or the -C option was specified, 50157429Smarkm * and if we won't be creating the file, then have the 50257429Smarkm * verbose message include a hint as to why the file 50357429Smarkm * will not be created. 50457429Smarkm */ 50557429Smarkm temp_reason[0] = '\0'; 50657429Smarkm if (createlogs > 1) 50757429Smarkm ent->firstcreate = 1; 50857429Smarkm else if ((ent->flags & CE_CREATE) && createlogs) 50957429Smarkm ent->firstcreate = 1; 51057429Smarkm else if (ent->flags & CE_CREATE) 51157429Smarkm strlcpy(temp_reason, " (no -C option)", REASON_MAX); 51257429Smarkm else if (createlogs) 51357429Smarkm strlcpy(temp_reason, " (no C flag)", REASON_MAX); 51457429Smarkm 51557429Smarkm if (ent->firstcreate) { 51657429Smarkm if (verbose) 51757429Smarkm printf("does not exist -> will create.\n"); 51857429Smarkm createlog(ent); 51957429Smarkm } else if (verbose) { 52057429Smarkm printf("does not exist, skipped%s.\n", temp_reason); 52157429Smarkm } 52257429Smarkm } else { 52357429Smarkm if (ent->flags & CE_TRIMAT && !force && !rotatereq && 52457429Smarkm !oversized) { 52557429Smarkm diffsecs = ptimeget_diff(timenow, ent->trim_at); 52657429Smarkm if (diffsecs < 0.0) { 52757429Smarkm /* trim_at is some time in the future. */ 52857429Smarkm if (verbose) { 52957429Smarkm ptime_adjust4dst(ent->trim_at, 53057429Smarkm timenow); 53157429Smarkm printf("--> will trim at %s", 53257429Smarkm ptimeget_ctime(ent->trim_at)); 53357429Smarkm } 53457429Smarkm return (free_or_keep); 53557429Smarkm } else if (diffsecs >= 3600.0) { 53657429Smarkm /* 53757429Smarkm * trim_at is more than an hour in the past, 53857429Smarkm * so find the next valid trim_at time, and 53957429Smarkm * tell the user what that will be. 54057429Smarkm */ 54157429Smarkm if (verbose && dbg_at_times) 54257429Smarkm printf("\n\t--> prev trim at %s\t", 54357429Smarkm ptimeget_ctime(ent->trim_at)); 54457429Smarkm if (verbose) { 54557429Smarkm ptimeset_nxtime(ent->trim_at); 54657429Smarkm printf("--> will trim at %s", 54757429Smarkm ptimeget_ctime(ent->trim_at)); 54857429Smarkm } 54957429Smarkm return (free_or_keep); 55057429Smarkm } else if (verbose && noaction && dbg_at_times) { 55157429Smarkm /* 55257429Smarkm * If we are just debugging at-times, then 55357429Smarkm * a detailed message is helpful. Also 55457429Smarkm * skip "doing" any commands, since they 55557429Smarkm * would all be turned off by no-action. 55657429Smarkm */ 55757429Smarkm printf("\n\t--> timematch at %s", 55857429Smarkm ptimeget_ctime(ent->trim_at)); 55957429Smarkm return (free_or_keep); 56057429Smarkm } else if (verbose && ent->hours <= 0) { 56157429Smarkm printf("--> time is up\n"); 56257429Smarkm } 56357429Smarkm } 56457429Smarkm if (verbose && (ent->trsize > 0)) 56557429Smarkm printf("size (Kb): %d [%d] ", ent->fsize, ent->trsize); 56657429Smarkm if (verbose && (ent->hours > 0)) 56757429Smarkm printf(" age (hr): %d [%d] ", modtime, ent->hours); 56857429Smarkm 56957429Smarkm /* 57057429Smarkm * Figure out if this logfile needs to be rotated. 57157429Smarkm */ 57257429Smarkm temp_reason[0] = '\0'; 57357429Smarkm if (rotatereq) { 57457429Smarkm ent->rotate = 1; 57557429Smarkm snprintf(temp_reason, REASON_MAX, " due to -R from %s", 57657429Smarkm requestor); 57757429Smarkm } else if (force) { 57857429Smarkm ent->rotate = 1; 57957429Smarkm snprintf(temp_reason, REASON_MAX, " due to -F request"); 58057429Smarkm } else if (oversized) { 58157429Smarkm ent->rotate = 1; 58257429Smarkm snprintf(temp_reason, REASON_MAX, " due to size>%dK", 58357429Smarkm ent->trsize); 58457429Smarkm } else if (ent->hours <= 0 && (ent->flags & CE_TRIMAT)) { 58557429Smarkm ent->rotate = 1; 58657429Smarkm } else if ((ent->hours > 0) && ((modtime >= ent->hours) || 58757429Smarkm (modtime < 0))) { 58857429Smarkm ent->rotate = 1; 58957429Smarkm } 59057429Smarkm 59157429Smarkm /* 59257429Smarkm * If the file needs to be rotated, then rotate it. 59357429Smarkm */ 59457429Smarkm if (ent->rotate && !norotate) { 59557429Smarkm if (temp_reason[0] != '\0') 59657429Smarkm ent->r_reason = strdup(temp_reason); 59757429Smarkm if (verbose) 59857429Smarkm printf("--> trimming log....\n"); 59957429Smarkm if (noaction && !verbose) 60057429Smarkm printf("%s <%d%s>: trimming\n", ent->log, 60157429Smarkm ent->numlogs, 60257429Smarkm compress_type[ent->compress].flag); 60357429Smarkm free_or_keep = do_rotate(ent); 60457429Smarkm } else { 60557429Smarkm if (verbose) 60657429Smarkm printf("--> skipping\n"); 60757429Smarkm } 60857429Smarkm } 60957429Smarkm return (free_or_keep); 61057429Smarkm#undef REASON_MAX 61157429Smarkm} 61257429Smarkm 61357429Smarkmstatic void 61457429Smarkmparse_args(int argc, char **argv) 61557429Smarkm{ 61657429Smarkm int ch; 61757429Smarkm char *p; 61857429Smarkm 61957429Smarkm timenow = ptime_init(NULL); 62057429Smarkm ptimeset_time(timenow, time(NULL)); 62157429Smarkm strlcpy(daytime, ptimeget_ctime(timenow) + 4, DAYTIME_LEN); 62257429Smarkm 62357429Smarkm /* Let's get our hostname */ 62457429Smarkm (void)gethostname(hostname, sizeof(hostname)); 62557429Smarkm 62657429Smarkm /* Truncate domain */ 62757429Smarkm if ((p = strchr(hostname, '.')) != NULL) 62857429Smarkm *p = '\0'; 62957429Smarkm 63057429Smarkm /* Parse command line options. */ 63157429Smarkm while ((ch = getopt(argc, argv, "a:d:f:nrst:vCD:FNPR:S:")) != -1) 63257429Smarkm switch (ch) { 63357429Smarkm case 'a': 63457429Smarkm archtodir++; 63557429Smarkm archdirname = optarg; 63657429Smarkm break; 63757429Smarkm case 'd': 63857429Smarkm destdir = optarg; 63957429Smarkm break; 64057429Smarkm case 'f': 64157429Smarkm conf = optarg; 64257429Smarkm break; 64357429Smarkm case 'n': 64457429Smarkm noaction++; 64557429Smarkm break; 64657429Smarkm case 'r': 64757429Smarkm needroot = 0; 64857429Smarkm break; 64957429Smarkm case 's': 65057429Smarkm nosignal = 1; 65157429Smarkm break; 65257429Smarkm case 't': 65357429Smarkm if (optarg[0] == '\0' || 65457429Smarkm strcmp(optarg, "DEFAULT") == 0) 65557429Smarkm timefnamefmt = strdup(DEFAULT_TIMEFNAME_FMT); 65657429Smarkm else 65757429Smarkm timefnamefmt = strdup(optarg); 65857429Smarkm break; 65957429Smarkm case 'v': 66057429Smarkm verbose++; 66157429Smarkm break; 66257429Smarkm case 'C': 66357429Smarkm /* Useful for things like rc.diskless... */ 66457429Smarkm createlogs++; 66557429Smarkm break; 66657429Smarkm case 'D': 66757429Smarkm /* 66857429Smarkm * Set some debugging option. The specific option 66957429Smarkm * depends on the value of optarg. These options 67057429Smarkm * may come and go without notice or documentation. 67157429Smarkm */ 67257429Smarkm if (parse_doption(optarg)) 67357429Smarkm break; 67457429Smarkm usage(); 67557429Smarkm /* NOTREACHED */ 67657429Smarkm case 'F': 67757429Smarkm force++; 67857429Smarkm break; 67957429Smarkm case 'N': 68057429Smarkm norotate++; 68157429Smarkm break; 68257429Smarkm case 'P': 68357429Smarkm enforcepid++; 68457429Smarkm break; 68557429Smarkm case 'R': 68657429Smarkm rotatereq++; 68757429Smarkm requestor = strdup(optarg); 68857429Smarkm break; 68957429Smarkm case 'S': 69057429Smarkm path_syslogpid = optarg; 69157429Smarkm break; 69257429Smarkm case 'm': /* Used by OpenBSD for "monitor mode" */ 69357429Smarkm default: 69457429Smarkm usage(); 69557429Smarkm /* NOTREACHED */ 69657429Smarkm } 69757429Smarkm 69857429Smarkm if (force && norotate) { 69957429Smarkm warnx("Only one of -F and -N may be specified."); 70057565Smarkm usage(); 70157565Smarkm /* NOTREACHED */ 70257565Smarkm } 70357565Smarkm 70457565Smarkm if (rotatereq) { 70557565Smarkm if (optind == argc) { 70657565Smarkm warnx("At least one filename must be given when -R is specified."); 70757565Smarkm usage(); 70857565Smarkm /* NOTREACHED */ 70957429Smarkm } 71057429Smarkm /* Make sure "requestor" value is safe for a syslog message. */ 71157429Smarkm for (p = requestor; *p != '\0'; p++) { 71257429Smarkm if (!isprintch(*p) && (*p != '\t')) 71357429Smarkm *p = '.'; 71457429Smarkm } 71557429Smarkm } 71657429Smarkm 71757429Smarkm if (dbg_timenow) { 71857429Smarkm /* 71957429Smarkm * Note that the 'daytime' variable is not changed. 72057429Smarkm * That is only used in messages that track when a 72157429Smarkm * logfile is rotated, and if a file *is* rotated, 72257429Smarkm * then it will still rotated at the "real now" time. 72357429Smarkm */ 72457429Smarkm ptime_free(timenow); 72557565Smarkm timenow = dbg_timenow; 72657429Smarkm fprintf(stderr, "Debug: Running as if TimeNow is %s", 72757429Smarkm ptimeget_ctime(dbg_timenow)); 72857429Smarkm } 72957429Smarkm 73057429Smarkm} 73157429Smarkm 73257429Smarkm/* 73357429Smarkm * These debugging options are mainly meant for developer use, such 73457429Smarkm * as writing regression-tests. They would not be needed by users 73557429Smarkm * during normal operation of newsyslog... 73657429Smarkm */ 73757429Smarkmstatic int 73857429Smarkmparse_doption(const char *doption) 73957429Smarkm{ 74057429Smarkm const char TN[] = "TN="; 74157429Smarkm int res; 74257429Smarkm 74357429Smarkm if (strncmp(doption, TN, sizeof(TN) - 1) == 0) { 744 /* 745 * The "TimeNow" debugging option. This might be off 746 * by an hour when crossing a timezone change. 747 */ 748 dbg_timenow = ptime_init(NULL); 749 res = ptime_relparse(dbg_timenow, PTM_PARSE_ISO8601, 750 time(NULL), doption + sizeof(TN) - 1); 751 if (res == -2) { 752 warnx("Non-existent time specified on -D %s", doption); 753 return (0); /* failure */ 754 } else if (res < 0) { 755 warnx("Malformed time given on -D %s", doption); 756 return (0); /* failure */ 757 } 758 return (1); /* successfully parsed */ 759 760 } 761 762 if (strcmp(doption, "ats") == 0) { 763 dbg_at_times++; 764 return (1); /* successfully parsed */ 765 } 766 767 /* XXX - This check could probably be dropped. */ 768 if ((strcmp(doption, "neworder") == 0) || (strcmp(doption, "oldorder") 769 == 0)) { 770 warnx("NOTE: newsyslog always uses 'neworder'."); 771 return (1); /* successfully parsed */ 772 } 773 774 warnx("Unknown -D (debug) option: '%s'", doption); 775 return (0); /* failure */ 776} 777 778static void 779usage(void) 780{ 781 782 fprintf(stderr, 783 "usage: newsyslog [-CFNPnrsv] [-a directory] [-d directory] [-f config_file]\n" 784 " [-S pidfile] [-t timefmt] [[-R tagname] file ...]\n"); 785 exit(1); 786} 787 788/* 789 * Parse a configuration file and return a linked list of all the logs 790 * which should be processed. 791 */ 792static struct cflist * 793get_worklist(char **files) 794{ 795 FILE *f; 796 char **given; 797 struct cflist *cmdlist, *filelist, *globlist; 798 struct conf_entry *defconf, *dupent, *ent; 799 struct ilist inclist; 800 struct include_entry *inc; 801 int gmatch, fnres; 802 803 defconf = NULL; 804 STAILQ_INIT(&inclist); 805 806 filelist = malloc(sizeof(struct cflist)); 807 if (filelist == NULL) 808 err(1, "malloc of filelist"); 809 STAILQ_INIT(filelist); 810 globlist = malloc(sizeof(struct cflist)); 811 if (globlist == NULL) 812 err(1, "malloc of globlist"); 813 STAILQ_INIT(globlist); 814 815 inc = malloc(sizeof(struct include_entry)); 816 if (inc == NULL) 817 err(1, "malloc of inc"); 818 inc->file = conf; 819 if (inc->file == NULL) 820 inc->file = _PATH_CONF; 821 STAILQ_INSERT_TAIL(&inclist, inc, inc_nextp); 822 823 STAILQ_FOREACH(inc, &inclist, inc_nextp) { 824 if (strcmp(inc->file, "-") != 0) 825 f = fopen(inc->file, "r"); 826 else { 827 f = stdin; 828 inc->file = "<stdin>"; 829 } 830 if (!f) 831 err(1, "%s", inc->file); 832 833 if (verbose) 834 printf("Processing %s\n", inc->file); 835 parse_file(f, filelist, globlist, defconf, &inclist); 836 (void) fclose(f); 837 } 838 839 /* 840 * All config-file information has been read in and turned into 841 * a filelist and a globlist. If there were no specific files 842 * given on the run command, then the only thing left to do is to 843 * call a routine which finds all files matched by the globlist 844 * and adds them to the filelist. Then return the worklist. 845 */ 846 if (*files == NULL) { 847 expand_globs(filelist, globlist); 848 free_clist(globlist); 849 if (defconf != NULL) 850 free_entry(defconf); 851 return (filelist); 852 /* NOTREACHED */ 853 } 854 855 /* 856 * If newsyslog was given a specific list of files to process, 857 * it may be that some of those files were not listed in any 858 * config file. Those unlisted files should get the default 859 * rotation action. First, create the default-rotation action 860 * if none was found in a system config file. 861 */ 862 if (defconf == NULL) { 863 defconf = init_entry(DEFAULT_MARKER, NULL); 864 defconf->numlogs = 3; 865 defconf->trsize = 50; 866 defconf->permissions = S_IRUSR|S_IWUSR; 867 } 868 869 /* 870 * If newsyslog was run with a list of specific filenames, 871 * then create a new worklist which has only those files in 872 * it, picking up the rotation-rules for those files from 873 * the original filelist. 874 * 875 * XXX - Note that this will copy multiple rules for a single 876 * logfile, if multiple entries are an exact match for 877 * that file. That matches the historic behavior, but do 878 * we want to continue to allow it? If so, it should 879 * probably be handled more intelligently. 880 */ 881 cmdlist = malloc(sizeof(struct cflist)); 882 if (cmdlist == NULL) 883 err(1, "malloc of cmdlist"); 884 STAILQ_INIT(cmdlist); 885 886 for (given = files; *given; ++given) { 887 /* 888 * First try to find exact-matches for this given file. 889 */ 890 gmatch = 0; 891 STAILQ_FOREACH(ent, filelist, cf_nextp) { 892 if (strcmp(ent->log, *given) == 0) { 893 gmatch++; 894 dupent = init_entry(*given, ent); 895 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp); 896 } 897 } 898 if (gmatch) { 899 if (verbose > 2) 900 printf("\t+ Matched entry %s\n", *given); 901 continue; 902 } 903 904 /* 905 * There was no exact-match for this given file, so look 906 * for a "glob" entry which does match. 907 */ 908 gmatch = 0; 909 if (verbose > 2 && globlist != NULL) 910 printf("\t+ Checking globs for %s\n", *given); 911 STAILQ_FOREACH(ent, globlist, cf_nextp) { 912 fnres = fnmatch(ent->log, *given, FNM_PATHNAME); 913 if (verbose > 2) 914 printf("\t+ = %d for pattern %s\n", fnres, 915 ent->log); 916 if (fnres == 0) { 917 gmatch++; 918 dupent = init_entry(*given, ent); 919 /* This new entry is not a glob! */ 920 dupent->flags &= ~CE_GLOB; 921 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp); 922 /* Only allow a match to one glob-entry */ 923 break; 924 } 925 } 926 if (gmatch) { 927 if (verbose > 2) 928 printf("\t+ Matched %s via %s\n", *given, 929 ent->log); 930 continue; 931 } 932 933 /* 934 * This given file was not found in any config file, so 935 * add a worklist item based on the default entry. 936 */ 937 if (verbose > 2) 938 printf("\t+ No entry matched %s (will use %s)\n", 939 *given, DEFAULT_MARKER); 940 dupent = init_entry(*given, defconf); 941 /* Mark that it was *not* found in a config file */ 942 dupent->def_cfg = 1; 943 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp); 944 } 945 946 /* 947 * Free all the entries in the original work list, the list of 948 * glob entries, and the default entry. 949 */ 950 free_clist(filelist); 951 free_clist(globlist); 952 free_entry(defconf); 953 954 /* And finally, return a worklist which matches the given files. */ 955 return (cmdlist); 956} 957 958/* 959 * Expand the list of entries with filename patterns, and add all files 960 * which match those glob-entries onto the worklist. 961 */ 962static void 963expand_globs(struct cflist *work_p, struct cflist *glob_p) 964{ 965 int gmatch, gres; 966 size_t i; 967 char *mfname; 968 struct conf_entry *dupent, *ent, *globent; 969 glob_t pglob; 970 struct stat st_fm; 971 972 /* 973 * The worklist contains all fully-specified (non-GLOB) names. 974 * 975 * Now expand the list of filename-pattern (GLOB) entries into 976 * a second list, which (by definition) will only match files 977 * that already exist. Do not add a glob-related entry for any 978 * file which already exists in the fully-specified list. 979 */ 980 STAILQ_FOREACH(globent, glob_p, cf_nextp) { 981 gres = glob(globent->log, GLOB_NOCHECK, NULL, &pglob); 982 if (gres != 0) { 983 warn("cannot expand pattern (%d): %s", gres, 984 globent->log); 985 continue; 986 } 987 988 if (verbose > 2) 989 printf("\t+ Expanding pattern %s\n", globent->log); 990 for (i = 0; i < pglob.gl_matchc; i++) { 991 mfname = pglob.gl_pathv[i]; 992 993 /* See if this file already has a specific entry. */ 994 gmatch = 0; 995 STAILQ_FOREACH(ent, work_p, cf_nextp) { 996 if (strcmp(mfname, ent->log) == 0) { 997 gmatch++; 998 break; 999 } 1000 } 1001 if (gmatch) 1002 continue; 1003 1004 /* Make sure the named matched is a file. */ 1005 gres = lstat(mfname, &st_fm); 1006 if (gres != 0) { 1007 /* Error on a file that glob() matched?!? */ 1008 warn("Skipping %s - lstat() error", mfname); 1009 continue; 1010 } 1011 if (!S_ISREG(st_fm.st_mode)) { 1012 /* We only rotate files! */ 1013 if (verbose > 2) 1014 printf("\t+ . skipping %s (!file)\n", 1015 mfname); 1016 continue; 1017 } 1018 1019 if (verbose > 2) 1020 printf("\t+ . add file %s\n", mfname); 1021 dupent = init_entry(mfname, globent); 1022 /* This new entry is not a glob! */ 1023 dupent->flags &= ~CE_GLOB; 1024 1025 /* Add to the worklist. */ 1026 STAILQ_INSERT_TAIL(work_p, dupent, cf_nextp); 1027 } 1028 globfree(&pglob); 1029 if (verbose > 2) 1030 printf("\t+ Done with pattern %s\n", globent->log); 1031 } 1032} 1033 1034/* 1035 * Parse a configuration file and update a linked list of all the logs to 1036 * process. 1037 */ 1038static void 1039parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p, 1040 struct conf_entry *defconf_p, struct ilist *inclist) 1041{ 1042 char line[BUFSIZ], *parse, *q; 1043 char *cp, *errline, *group; 1044 struct conf_entry *working; 1045 struct passwd *pwd; 1046 struct group *grp; 1047 glob_t pglob; 1048 int eol, ptm_opts, res, special; 1049 size_t i; 1050 1051 errline = NULL; 1052 while (fgets(line, BUFSIZ, cf)) { 1053 if ((line[0] == '\n') || (line[0] == '#') || 1054 (strlen(line) == 0)) 1055 continue; 1056 if (errline != NULL) 1057 free(errline); 1058 errline = strdup(line); 1059 for (cp = line + 1; *cp != '\0'; cp++) { 1060 if (*cp != '#') 1061 continue; 1062 if (*(cp - 1) == '\\') { 1063 strcpy(cp - 1, cp); 1064 cp--; 1065 continue; 1066 } 1067 *cp = '\0'; 1068 break; 1069 } 1070 1071 q = parse = missing_field(sob(line), errline); 1072 parse = son(line); 1073 if (!*parse) 1074 errx(1, "malformed line (missing fields):\n%s", 1075 errline); 1076 *parse = '\0'; 1077 1078 /* 1079 * Allow people to set debug options via the config file. 1080 * (NOTE: debug options are undocumented, and may disappear 1081 * at any time, etc). 1082 */ 1083 if (strcasecmp(DEBUG_MARKER, q) == 0) { 1084 q = parse = missing_field(sob(++parse), errline); 1085 parse = son(parse); 1086 if (!*parse) 1087 warnx("debug line specifies no option:\n%s", 1088 errline); 1089 else { 1090 *parse = '\0'; 1091 parse_doption(q); 1092 } 1093 continue; 1094 } else if (strcasecmp(INCLUDE_MARKER, q) == 0) { 1095 if (verbose) 1096 printf("Found: %s", errline); 1097 q = parse = missing_field(sob(++parse), errline); 1098 parse = son(parse); 1099 if (!*parse) { 1100 warnx("include line missing argument:\n%s", 1101 errline); 1102 continue; 1103 } 1104 1105 *parse = '\0'; 1106 1107 if (isglobstr(q)) { 1108 res = glob(q, GLOB_NOCHECK, NULL, &pglob); 1109 if (res != 0) { 1110 warn("cannot expand pattern (%d): %s", 1111 res, q); 1112 continue; 1113 } 1114 1115 if (verbose > 2) 1116 printf("\t+ Expanding pattern %s\n", q); 1117 1118 for (i = 0; i < pglob.gl_matchc; i++) 1119 add_to_queue(pglob.gl_pathv[i], 1120 inclist); 1121 globfree(&pglob); 1122 } else 1123 add_to_queue(q, inclist); 1124 continue; 1125 } 1126 1127 special = 0; 1128 working = init_entry(q, NULL); 1129 if (strcasecmp(DEFAULT_MARKER, q) == 0) { 1130 special = 1; 1131 if (defconf_p != NULL) { 1132 warnx("Ignoring duplicate entry for %s!", q); 1133 free_entry(working); 1134 continue; 1135 } 1136 defconf_p = working; 1137 } 1138 1139 q = parse = missing_field(sob(++parse), errline); 1140 parse = son(parse); 1141 if (!*parse) 1142 errx(1, "malformed line (missing fields):\n%s", 1143 errline); 1144 *parse = '\0'; 1145 if ((group = strchr(q, ':')) != NULL || 1146 (group = strrchr(q, '.')) != NULL) { 1147 *group++ = '\0'; 1148 if (*q) { 1149 if (!(isnumberstr(q))) { 1150 if ((pwd = getpwnam(q)) == NULL) 1151 errx(1, 1152 "error in config file; unknown user:\n%s", 1153 errline); 1154 working->uid = pwd->pw_uid; 1155 } else 1156 working->uid = atoi(q); 1157 } else 1158 working->uid = (uid_t)-1; 1159 1160 q = group; 1161 if (*q) { 1162 if (!(isnumberstr(q))) { 1163 if ((grp = getgrnam(q)) == NULL) 1164 errx(1, 1165 "error in config file; unknown group:\n%s", 1166 errline); 1167 working->gid = grp->gr_gid; 1168 } else 1169 working->gid = atoi(q); 1170 } else 1171 working->gid = (gid_t)-1; 1172 1173 q = parse = missing_field(sob(++parse), errline); 1174 parse = son(parse); 1175 if (!*parse) 1176 errx(1, "malformed line (missing fields):\n%s", 1177 errline); 1178 *parse = '\0'; 1179 } else { 1180 working->uid = (uid_t)-1; 1181 working->gid = (gid_t)-1; 1182 } 1183 1184 if (!sscanf(q, "%o", &working->permissions)) 1185 errx(1, "error in config file; bad permissions:\n%s", 1186 errline); 1187 1188 q = parse = missing_field(sob(++parse), errline); 1189 parse = son(parse); 1190 if (!*parse) 1191 errx(1, "malformed line (missing fields):\n%s", 1192 errline); 1193 *parse = '\0'; 1194 if (!sscanf(q, "%d", &working->numlogs) || working->numlogs < 0) 1195 errx(1, "error in config file; bad value for count of logs to save:\n%s", 1196 errline); 1197 1198 q = parse = missing_field(sob(++parse), errline); 1199 parse = son(parse); 1200 if (!*parse) 1201 errx(1, "malformed line (missing fields):\n%s", 1202 errline); 1203 *parse = '\0'; 1204 if (isdigitch(*q)) 1205 working->trsize = atoi(q); 1206 else if (strcmp(q, "*") == 0) 1207 working->trsize = -1; 1208 else { 1209 warnx("Invalid value of '%s' for 'size' in line:\n%s", 1210 q, errline); 1211 working->trsize = -1; 1212 } 1213 1214 working->flags = 0; 1215 working->compress = COMPRESS_NONE; 1216 q = parse = missing_field(sob(++parse), errline); 1217 parse = son(parse); 1218 eol = !*parse; 1219 *parse = '\0'; 1220 { 1221 char *ep; 1222 u_long ul; 1223 1224 ul = strtoul(q, &ep, 10); 1225 if (ep == q) 1226 working->hours = 0; 1227 else if (*ep == '*') 1228 working->hours = -1; 1229 else if (ul > INT_MAX) 1230 errx(1, "interval is too large:\n%s", errline); 1231 else 1232 working->hours = ul; 1233 1234 if (*ep == '\0' || strcmp(ep, "*") == 0) 1235 goto no_trimat; 1236 if (*ep != '@' && *ep != '$') 1237 errx(1, "malformed interval/at:\n%s", errline); 1238 1239 working->flags |= CE_TRIMAT; 1240 working->trim_at = ptime_init(NULL); 1241 ptm_opts = PTM_PARSE_ISO8601; 1242 if (*ep == '$') 1243 ptm_opts = PTM_PARSE_DWM; 1244 ptm_opts |= PTM_PARSE_MATCHDOM; 1245 res = ptime_relparse(working->trim_at, ptm_opts, 1246 ptimeget_secs(timenow), ep + 1); 1247 if (res == -2) 1248 errx(1, "nonexistent time for 'at' value:\n%s", 1249 errline); 1250 else if (res < 0) 1251 errx(1, "malformed 'at' value:\n%s", errline); 1252 } 1253no_trimat: 1254 1255 if (eol) 1256 q = NULL; 1257 else { 1258 q = parse = sob(++parse); /* Optional field */ 1259 parse = son(parse); 1260 if (!*parse) 1261 eol = 1; 1262 *parse = '\0'; 1263 } 1264 1265 for (; q && *q && !isspacech(*q); q++) { 1266 switch (tolowerch(*q)) { 1267 case 'b': 1268 working->flags |= CE_BINARY; 1269 break; 1270 case 'c': 1271 /* 1272 * XXX - Ick! Ugly! Remove ASAP! 1273 * We want `c' and `C' for "create". But we 1274 * will temporarily treat `c' as `g', because 1275 * FreeBSD releases <= 4.8 have a typo of 1276 * checking ('G' || 'c') for CE_GLOB. 1277 */ 1278 if (*q == 'c') { 1279 warnx("Assuming 'g' for 'c' in flags for line:\n%s", 1280 errline); 1281 warnx("The 'c' flag will eventually mean 'CREATE'"); 1282 working->flags |= CE_GLOB; 1283 break; 1284 } 1285 working->flags |= CE_CREATE; 1286 break; 1287 case 'd': 1288 working->flags |= CE_NODUMP; 1289 break; 1290 case 'g': 1291 working->flags |= CE_GLOB; 1292 break; 1293 case 'j': 1294 working->compress = COMPRESS_BZIP2; 1295 break; 1296 case 'n': 1297 working->flags |= CE_NOSIGNAL; 1298 break; 1299 case 'r': 1300 working->flags |= CE_PID2CMD; 1301 break; 1302 case 'u': 1303 working->flags |= CE_SIGNALGROUP; 1304 break; 1305 case 'w': 1306 /* Depreciated flag - keep for compatibility purposes */ 1307 break; 1308 case 'x': 1309 working->compress = COMPRESS_XZ; 1310 break; 1311 case 'z': 1312 working->compress = COMPRESS_GZIP; 1313 break; 1314 case '-': 1315 break; 1316 case 'f': /* Used by OpenBSD for "CE_FOLLOW" */ 1317 case 'm': /* Used by OpenBSD for "CE_MONITOR" */ 1318 case 'p': /* Used by NetBSD for "CE_PLAIN0" */ 1319 default: 1320 errx(1, "illegal flag in config file -- %c", 1321 *q); 1322 } 1323 } 1324 1325 if (eol) 1326 q = NULL; 1327 else { 1328 q = parse = sob(++parse); /* Optional field */ 1329 parse = son(parse); 1330 if (!*parse) 1331 eol = 1; 1332 *parse = '\0'; 1333 } 1334 1335 working->pid_cmd_file = NULL; 1336 if (q && *q) { 1337 if (*q == '/') 1338 working->pid_cmd_file = strdup(q); 1339 else if (isdigit(*q)) 1340 goto got_sig; 1341 else 1342 errx(1, 1343 "illegal pid file or signal number in config file:\n%s", 1344 errline); 1345 } 1346 if (eol) 1347 q = NULL; 1348 else { 1349 q = parse = sob(++parse); /* Optional field */ 1350 *(parse = son(parse)) = '\0'; 1351 } 1352 1353 working->sig = SIGHUP; 1354 if (q && *q) { 1355 if (isdigit(*q)) { 1356 got_sig: 1357 working->sig = atoi(q); 1358 } else { 1359 err_sig: 1360 errx(1, 1361 "illegal signal number in config file:\n%s", 1362 errline); 1363 } 1364 if (working->sig < 1 || working->sig >= NSIG) 1365 goto err_sig; 1366 } 1367 1368 /* 1369 * Finish figuring out what pid-file to use (if any) in 1370 * later processing if this logfile needs to be rotated. 1371 */ 1372 if ((working->flags & CE_NOSIGNAL) == CE_NOSIGNAL) { 1373 /* 1374 * This config-entry specified 'n' for nosignal, 1375 * see if it also specified an explicit pid_cmd_file. 1376 * This would be a pretty pointless combination. 1377 */ 1378 if (working->pid_cmd_file != NULL) { 1379 warnx("Ignoring '%s' because flag 'n' was specified in line:\n%s", 1380 working->pid_cmd_file, errline); 1381 free(working->pid_cmd_file); 1382 working->pid_cmd_file = NULL; 1383 } 1384 } else if (working->pid_cmd_file == NULL) { 1385 /* 1386 * This entry did not specify the 'n' flag, which 1387 * means it should signal syslogd unless it had 1388 * specified some other pid-file (and obviously the 1389 * syslog pid-file will not be for a process-group). 1390 * Also, we should only try to notify syslog if we 1391 * are root. 1392 */ 1393 if (working->flags & CE_SIGNALGROUP) { 1394 warnx("Ignoring flag 'U' in line:\n%s", 1395 errline); 1396 working->flags &= ~CE_SIGNALGROUP; 1397 } 1398 if (needroot) 1399 working->pid_cmd_file = strdup(path_syslogpid); 1400 } 1401 1402 /* 1403 * Add this entry to the appropriate list of entries, unless 1404 * it was some kind of special entry (eg: <default>). 1405 */ 1406 if (special) { 1407 ; /* Do not add to any list */ 1408 } else if (working->flags & CE_GLOB) { 1409 STAILQ_INSERT_TAIL(glob_p, working, cf_nextp); 1410 } else { 1411 STAILQ_INSERT_TAIL(work_p, working, cf_nextp); 1412 } 1413 } 1414 if (errline != NULL) 1415 free(errline); 1416} 1417 1418static char * 1419missing_field(char *p, char *errline) 1420{ 1421 1422 if (!p || !*p) 1423 errx(1, "missing field in config file:\n%s", errline); 1424 return (p); 1425} 1426 1427/* 1428 * In our sort we return it in the reverse of what qsort normally 1429 * would do, as we want the newest files first. If we have two 1430 * entries with the same time we don't really care about order. 1431 * 1432 * Support function for qsort() in delete_oldest_timelog(). 1433 */ 1434static int 1435oldlog_entry_compare(const void *a, const void *b) 1436{ 1437 const struct oldlog_entry *ola = a, *olb = b; 1438 1439 if (ola->t > olb->t) 1440 return (-1); 1441 else if (ola->t < olb->t) 1442 return (1); 1443 else 1444 return (0); 1445} 1446 1447/* 1448 * Delete the oldest logfiles, when using time based filenames. 1449 */ 1450static void 1451delete_oldest_timelog(const struct conf_entry *ent, const char *archive_dir) 1452{ 1453 char *logfname, *s, *dir, errbuf[80]; 1454 int dirfd, i, logcnt, max_logcnt, valid; 1455 struct oldlog_entry *oldlogs; 1456 size_t logfname_len; 1457 struct dirent *dp; 1458 const char *cdir; 1459 struct tm tm; 1460 DIR *dirp; 1461 int c; 1462 1463 oldlogs = malloc(MAX_OLDLOGS * sizeof(struct oldlog_entry)); 1464 max_logcnt = MAX_OLDLOGS; 1465 logcnt = 0; 1466 1467 if (archive_dir != NULL && archive_dir[0] != '\0') 1468 cdir = archive_dir; 1469 else 1470 if ((cdir = dirname(ent->log)) == NULL) 1471 err(1, "dirname()"); 1472 if ((dir = strdup(cdir)) == NULL) 1473 err(1, "strdup()"); 1474 1475 if ((s = basename(ent->log)) == NULL) 1476 err(1, "basename()"); 1477 if ((logfname = strdup(s)) == NULL) 1478 err(1, "strdup()"); 1479 logfname_len = strlen(logfname); 1480 if (strcmp(logfname, "/") == 0) 1481 errx(1, "Invalid log filename - became '/'"); 1482 1483 if (verbose > 2) 1484 printf("Searching for old logs in %s\n", dir); 1485 1486 /* First we create a 'list' of all archived logfiles */ 1487 if ((dirp = opendir(dir)) == NULL) 1488 err(1, "Cannot open log directory '%s'", dir); 1489 dirfd = dirfd(dirp); 1490 while ((dp = readdir(dirp)) != NULL) { 1491 if (dp->d_type != DT_REG) 1492 continue; 1493 1494 /* Ignore everything but files with our logfile prefix */ 1495 if (strncmp(dp->d_name, logfname, logfname_len) != 0) 1496 continue; 1497 /* Ignore the actual non-rotated logfile */ 1498 if (dp->d_namlen == logfname_len) 1499 continue; 1500 /* 1501 * Make sure we created have found a logfile, so the 1502 * postfix is valid, IE format is: '.<time>(.[bg]z)?'. 1503 */ 1504 if (dp->d_name[logfname_len] != '.') { 1505 if (verbose) 1506 printf("Ignoring %s which has unexpected " 1507 "extension '%s'\n", dp->d_name, 1508 &dp->d_name[logfname_len]); 1509 continue; 1510 } 1511 if ((s = strptime(&dp->d_name[logfname_len + 1], 1512 timefnamefmt, &tm)) == NULL) { 1513 /* 1514 * We could special case "old" sequentially 1515 * named logfiles here, but we do not as that 1516 * would require special handling to decide 1517 * which one was the oldest compared to "new" 1518 * time based logfiles. 1519 */ 1520 if (verbose) 1521 printf("Ignoring %s which does not " 1522 "match time format\n", dp->d_name); 1523 continue; 1524 } 1525 1526 for (c = 0; c < COMPRESS_TYPES; c++) 1527 if (strcmp(s, compress_type[c].suffix) == 0) 1528 valid = 1; 1529 if (valid != 1) { 1530 if (verbose) 1531 printf("Ignoring %s which has unexpected " 1532 "extension '%s'\n", dp->d_name, s); 1533 continue; 1534 } 1535 1536 /* 1537 * We should now have old an old rotated logfile, so 1538 * add it to the 'list'. 1539 */ 1540 if ((oldlogs[logcnt].t = timegm(&tm)) == -1) 1541 err(1, "Could not convert time string to time value"); 1542 if ((oldlogs[logcnt].fname = strdup(dp->d_name)) == NULL) 1543 err(1, "strdup()"); 1544 logcnt++; 1545 1546 /* 1547 * It is very unlikely we ever run out of space in the 1548 * logfile array from the default size, but lets 1549 * handle it anyway... 1550 */ 1551 if (logcnt >= max_logcnt) { 1552 max_logcnt *= 4; 1553 /* Detect integer overflow */ 1554 if (max_logcnt < logcnt) 1555 errx(1, "Too many old logfiles found"); 1556 oldlogs = realloc(oldlogs, 1557 max_logcnt * sizeof(struct oldlog_entry)); 1558 if (oldlogs == NULL) 1559 err(1, "realloc()"); 1560 } 1561 } 1562 1563 /* Second, if needed we delete oldest archived logfiles */ 1564 if (logcnt > 0 && logcnt >= ent->numlogs && ent->numlogs > 1) { 1565 oldlogs = realloc(oldlogs, logcnt * 1566 sizeof(struct oldlog_entry)); 1567 if (oldlogs == NULL) 1568 err(1, "realloc()"); 1569 1570 /* 1571 * We now sort the logs in the order of newest to 1572 * oldest. That way we can simply skip over the 1573 * number of records we want to keep. 1574 */ 1575 qsort(oldlogs, logcnt, sizeof(struct oldlog_entry), 1576 oldlog_entry_compare); 1577 for (i = ent->numlogs - 1; i < logcnt; i++) { 1578 if (noaction) 1579 printf("\trm -f %s/%s\n", dir, 1580 oldlogs[i].fname); 1581 else if (unlinkat(dirfd, oldlogs[i].fname, 0) != 0) { 1582 snprintf(errbuf, sizeof(errbuf), 1583 "Could not delet old logfile '%s'", 1584 oldlogs[i].fname); 1585 perror(errbuf); 1586 } 1587 } 1588 } else if (verbose > 1) 1589 printf("No old logs to delete for logfile %s\n", ent->log); 1590 1591 /* Third, cleanup */ 1592 closedir(dirp); 1593 for (i = 0; i < logcnt; i++) { 1594 assert(oldlogs[i].fname != NULL); 1595 free(oldlogs[i].fname); 1596 } 1597 free(oldlogs); 1598 free(logfname); 1599 free(dir); 1600} 1601 1602/* 1603 * Generate a log filename, when using clasic filenames. 1604 */ 1605static void 1606gen_clasiclog_fname(char *fname, size_t fname_sz, const char *archive_dir, 1607 const char *namepart, int numlogs_c) 1608{ 1609 1610 if (archive_dir[0] != '\0') 1611 (void) snprintf(fname, fname_sz, "%s/%s.%d", archive_dir, 1612 namepart, numlogs_c); 1613 else 1614 (void) snprintf(fname, fname_sz, "%s.%d", namepart, numlogs_c); 1615} 1616 1617/* 1618 * Delete a rotated logfiles, when using clasic filenames. 1619 */ 1620static void 1621delete_clasiclog(const char *archive_dir, const char *namepart, int numlog_c) 1622{ 1623 char file1[MAXPATHLEN], zfile1[MAXPATHLEN]; 1624 int c; 1625 1626 gen_clasiclog_fname(file1, sizeof(file1), archive_dir, namepart, 1627 numlog_c); 1628 1629 for (c = 0; c < COMPRESS_TYPES; c++) { 1630 (void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1, 1631 compress_type[c].suffix); 1632 if (noaction) 1633 printf("\trm -f %s\n", zfile1); 1634 else 1635 (void) unlink(zfile1); 1636 } 1637} 1638 1639/* 1640 * Only add to the queue if the file hasn't already been added. This is 1641 * done to prevent circular include loops. 1642 */ 1643static void 1644add_to_queue(const char *fname, struct ilist *inclist) 1645{ 1646 struct include_entry *inc; 1647 1648 STAILQ_FOREACH(inc, inclist, inc_nextp) { 1649 if (strcmp(fname, inc->file) == 0) { 1650 warnx("duplicate include detected: %s", fname); 1651 return; 1652 } 1653 } 1654 1655 inc = malloc(sizeof(struct include_entry)); 1656 if (inc == NULL) 1657 err(1, "malloc of inc"); 1658 inc->file = strdup(fname); 1659 1660 if (verbose > 2) 1661 printf("\t+ Adding %s to the processing queue.\n", fname); 1662 1663 STAILQ_INSERT_TAIL(inclist, inc, inc_nextp); 1664} 1665 1666/* 1667 * Search for logfile and return its compression suffix (if supported) 1668 * The suffix detection is first-match in the order of compress_types 1669 * 1670 * Note: if logfile without suffix exists (uncompressed, COMPRESS_NONE) 1671 * a zero-length string is returned 1672 */ 1673static const char * 1674get_logfile_suffix(const char *logfile) 1675{ 1676 struct stat st; 1677 char zfile[MAXPATHLEN]; 1678 int c; 1679 1680 for (c = 0; c < COMPRESS_TYPES; c++) { 1681 (void) strlcpy(zfile, logfile, MAXPATHLEN); 1682 (void) strlcat(zfile, compress_type[c].suffix, MAXPATHLEN); 1683 if (lstat(zfile, &st) == 0) 1684 return (compress_type[c].suffix); 1685 } 1686 return (NULL); 1687} 1688 1689static fk_entry 1690do_rotate(const struct conf_entry *ent) 1691{ 1692 char dirpart[MAXPATHLEN], namepart[MAXPATHLEN]; 1693 char file1[MAXPATHLEN], file2[MAXPATHLEN]; 1694 char zfile1[MAXPATHLEN], zfile2[MAXPATHLEN]; 1695 const char *logfile_suffix; 1696 char datetimestr[30]; 1697 int flags, numlogs_c; 1698 fk_entry free_or_keep; 1699 struct sigwork_entry *swork; 1700 struct stat st; 1701 struct tm tm; 1702 time_t now; 1703 1704 flags = ent->flags; 1705 free_or_keep = FREE_ENT; 1706 1707 if (archtodir) { 1708 char *p; 1709 1710 /* build complete name of archive directory into dirpart */ 1711 if (*archdirname == '/') { /* absolute */ 1712 strlcpy(dirpart, archdirname, sizeof(dirpart)); 1713 } else { /* relative */ 1714 /* get directory part of logfile */ 1715 strlcpy(dirpart, ent->log, sizeof(dirpart)); 1716 if ((p = rindex(dirpart, '/')) == NULL) 1717 dirpart[0] = '\0'; 1718 else 1719 *(p + 1) = '\0'; 1720 strlcat(dirpart, archdirname, sizeof(dirpart)); 1721 } 1722 1723 /* check if archive directory exists, if not, create it */ 1724 if (lstat(dirpart, &st)) 1725 createdir(ent, dirpart); 1726 1727 /* get filename part of logfile */ 1728 if ((p = rindex(ent->log, '/')) == NULL) 1729 strlcpy(namepart, ent->log, sizeof(namepart)); 1730 else 1731 strlcpy(namepart, p + 1, sizeof(namepart)); 1732 } else { 1733 /* 1734 * Tell utility functions we are not using an archive 1735 * dir. 1736 */ 1737 dirpart[0] = '\0'; 1738 strlcpy(namepart, ent->log, sizeof(namepart)); 1739 } 1740 1741 /* Delete old logs */ 1742 if (timefnamefmt != NULL) 1743 delete_oldest_timelog(ent, dirpart); 1744 else { 1745 /* 1746 * Handle cleaning up after legacy newsyslog where we 1747 * kept ent->numlogs + 1 files. This code can go away 1748 * at some point in the future. 1749 */ 1750 delete_clasiclog(dirpart, namepart, ent->numlogs); 1751 1752 if (ent->numlogs > 0) 1753 delete_clasiclog(dirpart, namepart, ent->numlogs - 1); 1754 1755 } 1756 1757 if (timefnamefmt != NULL) { 1758 /* If time functions fails we can't really do any sensible */ 1759 if (time(&now) == (time_t)-1 || 1760 localtime_r(&now, &tm) == NULL) 1761 bzero(&tm, sizeof(tm)); 1762 1763 strftime(datetimestr, sizeof(datetimestr), timefnamefmt, &tm); 1764 if (archtodir) 1765 (void) snprintf(file1, sizeof(file1), "%s/%s.%s", 1766 dirpart, namepart, datetimestr); 1767 else 1768 (void) snprintf(file1, sizeof(file1), "%s.%s", 1769 ent->log, datetimestr); 1770 1771 /* Don't run the code to move down logs */ 1772 numlogs_c = -1; 1773 } else { 1774 gen_clasiclog_fname(file1, sizeof(file1), dirpart, namepart, 1775 ent->numlogs - 1); 1776 numlogs_c = ent->numlogs - 2; /* copy for countdown */ 1777 } 1778 1779 /* Move down log files */ 1780 for (; numlogs_c >= 0; numlogs_c--) { 1781 (void) strlcpy(file2, file1, sizeof(file2)); 1782 1783 gen_clasiclog_fname(file1, sizeof(file1), dirpart, namepart, 1784 numlogs_c); 1785 1786 logfile_suffix = get_logfile_suffix(file1); 1787 if (logfile_suffix == NULL) 1788 continue; 1789 (void) strlcpy(zfile1, file1, MAXPATHLEN); 1790 (void) strlcpy(zfile2, file2, MAXPATHLEN); 1791 (void) strlcat(zfile1, logfile_suffix, MAXPATHLEN); 1792 (void) strlcat(zfile2, logfile_suffix, MAXPATHLEN); 1793 1794 if (noaction) 1795 printf("\tmv %s %s\n", zfile1, zfile2); 1796 else { 1797 /* XXX - Ought to be checking for failure! */ 1798 (void)rename(zfile1, zfile2); 1799 } 1800 change_attrs(zfile2, ent); 1801 } 1802 1803 if (ent->numlogs > 0) { 1804 if (noaction) { 1805 /* 1806 * Note that savelog() may succeed with using link() 1807 * for the archtodir case, but there is no good way 1808 * of knowing if it will when doing "noaction", so 1809 * here we claim that it will have to do a copy... 1810 */ 1811 if (archtodir) 1812 printf("\tcp %s %s\n", ent->log, file1); 1813 else 1814 printf("\tln %s %s\n", ent->log, file1); 1815 } else { 1816 if (!(flags & CE_BINARY)) { 1817 /* Report the trimming to the old log */ 1818 log_trim(ent->log, ent); 1819 } 1820 savelog(ent->log, file1); 1821 } 1822 change_attrs(file1, ent); 1823 } 1824 1825 /* Create the new log file and move it into place */ 1826 if (noaction) 1827 printf("Start new log...\n"); 1828 createlog(ent); 1829 1830 /* 1831 * Save all signalling and file-compression to be done after log 1832 * files from all entries have been rotated. This way any one 1833 * process will not be sent the same signal multiple times when 1834 * multiple log files had to be rotated. 1835 */ 1836 swork = NULL; 1837 if (ent->pid_cmd_file != NULL) 1838 swork = save_sigwork(ent); 1839 if (ent->numlogs > 0 && ent->compress > COMPRESS_NONE) { 1840 /* 1841 * The zipwork_entry will include a pointer to this 1842 * conf_entry, so the conf_entry should not be freed. 1843 */ 1844 free_or_keep = KEEP_ENT; 1845 save_zipwork(ent, swork, ent->fsize, file1); 1846 } 1847 1848 return (free_or_keep); 1849} 1850 1851static void 1852do_sigwork(struct sigwork_entry *swork) 1853{ 1854 struct sigwork_entry *nextsig; 1855 int kres, secs; 1856 char *tmp; 1857 1858 if (!(swork->sw_pidok) || swork->sw_pid == 0) 1859 return; /* no work to do... */ 1860 1861 /* 1862 * If nosignal (-s) was specified, then do not signal any process. 1863 * Note that a nosignal request triggers a warning message if the 1864 * rotated logfile needs to be compressed, *unless* -R was also 1865 * specified. We assume that an `-sR' request came from a process 1866 * which writes to the logfile, and as such, we assume that process 1867 * has already made sure the logfile is not presently in use. This 1868 * just sets swork->sw_pidok to a special value, and do_zipwork 1869 * will print any necessary warning(s). 1870 */ 1871 if (nosignal) { 1872 if (!rotatereq) 1873 swork->sw_pidok = -1; 1874 return; 1875 } 1876 1877 /* 1878 * Compute the pause between consecutive signals. Use a longer 1879 * sleep time if we will be sending two signals to the same 1880 * deamon or process-group. 1881 */ 1882 secs = 0; 1883 nextsig = SLIST_NEXT(swork, sw_nextp); 1884 if (nextsig != NULL) { 1885 if (swork->sw_pid == nextsig->sw_pid) 1886 secs = 10; 1887 else 1888 secs = 1; 1889 } 1890 1891 if (noaction) { 1892 printf("\tkill -%d %d \t\t# %s\n", swork->sw_signum, 1893 (int)swork->sw_pid, swork->sw_fname); 1894 if (secs > 0) 1895 printf("\tsleep %d\n", secs); 1896 return; 1897 } 1898 1899 if (swork->run_cmd) { 1900 asprintf(&tmp, "%s %d", swork->sw_fname, swork->sw_signum); 1901 if (tmp == NULL) { 1902 warn("can't allocate memory to run %s", 1903 swork->sw_fname); 1904 return; 1905 } 1906 if (verbose) 1907 printf("Run command: %s\n", tmp); 1908 kres = system(tmp); 1909 if (kres) { 1910 warnx("%s: returned non-zero exit code: %d", 1911 tmp, kres); 1912 } 1913 free(tmp); 1914 return; 1915 } 1916 1917 kres = kill(swork->sw_pid, swork->sw_signum); 1918 if (kres != 0) { 1919 /* 1920 * Assume that "no such process" (ESRCH) is something 1921 * to warn about, but is not an error. Presumably the 1922 * process which writes to the rotated log file(s) is 1923 * gone, in which case we should have no problem with 1924 * compressing the rotated log file(s). 1925 */ 1926 if (errno != ESRCH) 1927 swork->sw_pidok = 0; 1928 warn("can't notify %s, pid %d", swork->sw_pidtype, 1929 (int)swork->sw_pid); 1930 } else { 1931 if (verbose) 1932 printf("Notified %s pid %d = %s\n", swork->sw_pidtype, 1933 (int)swork->sw_pid, swork->sw_fname); 1934 if (secs > 0) { 1935 if (verbose) 1936 printf("Pause %d second(s) between signals\n", 1937 secs); 1938 sleep(secs); 1939 } 1940 } 1941} 1942 1943static void 1944do_zipwork(struct zipwork_entry *zwork) 1945{ 1946 const char *pgm_name, *pgm_path; 1947 int errsav, fcount, zstatus; 1948 pid_t pidzip, wpid; 1949 char zresult[MAXPATHLEN]; 1950 int c; 1951 1952 assert(zwork != NULL); 1953 pgm_path = NULL; 1954 strlcpy(zresult, zwork->zw_fname, sizeof(zresult)); 1955 if (zwork->zw_conf != NULL && 1956 zwork->zw_conf->compress > COMPRESS_NONE) 1957 for (c = 1; c < COMPRESS_TYPES; c++) { 1958 if (zwork->zw_conf->compress == c) { 1959 pgm_path = compress_type[c].path; 1960 (void) strlcat(zresult, 1961 compress_type[c].suffix, sizeof(zresult)); 1962 break; 1963 } 1964 } 1965 if (pgm_path == NULL) { 1966 warnx("invalid entry for %s in do_zipwork", zwork->zw_fname); 1967 return; 1968 } 1969 pgm_name = strrchr(pgm_path, '/'); 1970 if (pgm_name == NULL) 1971 pgm_name = pgm_path; 1972 else 1973 pgm_name++; 1974 1975 if (zwork->zw_swork != NULL && zwork->zw_swork->run_cmd == 0 && 1976 zwork->zw_swork->sw_pidok <= 0) { 1977 warnx( 1978 "log %s not compressed because daemon(s) not notified", 1979 zwork->zw_fname); 1980 change_attrs(zwork->zw_fname, zwork->zw_conf); 1981 return; 1982 } 1983 1984 if (noaction) { 1985 printf("\t%s %s\n", pgm_name, zwork->zw_fname); 1986 change_attrs(zresult, zwork->zw_conf); 1987 return; 1988 } 1989 1990 fcount = 1; 1991 pidzip = fork(); 1992 while (pidzip < 0) { 1993 /* 1994 * The fork failed. If the failure was due to a temporary 1995 * problem, then wait a short time and try it again. 1996 */ 1997 errsav = errno; 1998 warn("fork() for `%s %s'", pgm_name, zwork->zw_fname); 1999 if (errsav != EAGAIN || fcount > 5) 2000 errx(1, "Exiting..."); 2001 sleep(fcount * 12); 2002 fcount++; 2003 pidzip = fork(); 2004 } 2005 if (!pidzip) { 2006 /* The child process executes the compression command */ 2007 execl(pgm_path, pgm_path, "-f", zwork->zw_fname, (char *)0); 2008 err(1, "execl(`%s -f %s')", pgm_path, zwork->zw_fname); 2009 } 2010 2011 wpid = waitpid(pidzip, &zstatus, 0); 2012 if (wpid == -1) { 2013 /* XXX - should this be a fatal error? */ 2014 warn("%s: waitpid(%d)", pgm_path, pidzip); 2015 return; 2016 } 2017 if (!WIFEXITED(zstatus)) { 2018 warnx("`%s -f %s' did not terminate normally", pgm_name, 2019 zwork->zw_fname); 2020 return; 2021 } 2022 if (WEXITSTATUS(zstatus)) { 2023 warnx("`%s -f %s' terminated with a non-zero status (%d)", 2024 pgm_name, zwork->zw_fname, WEXITSTATUS(zstatus)); 2025 return; 2026 } 2027 2028 /* Compression was successful, set file attributes on the result. */ 2029 change_attrs(zresult, zwork->zw_conf); 2030} 2031 2032/* 2033 * Save information on any process we need to signal. Any single 2034 * process may need to be sent different signal-values for different 2035 * log files, but usually a single signal-value will cause the process 2036 * to close and re-open all of it's log files. 2037 */ 2038static struct sigwork_entry * 2039save_sigwork(const struct conf_entry *ent) 2040{ 2041 struct sigwork_entry *sprev, *stmp; 2042 int ndiff; 2043 size_t tmpsiz; 2044 2045 sprev = NULL; 2046 ndiff = 1; 2047 SLIST_FOREACH(stmp, &swhead, sw_nextp) { 2048 ndiff = strcmp(ent->pid_cmd_file, stmp->sw_fname); 2049 if (ndiff > 0) 2050 break; 2051 if (ndiff == 0) { 2052 if (ent->sig == stmp->sw_signum) 2053 break; 2054 if (ent->sig > stmp->sw_signum) { 2055 ndiff = 1; 2056 break; 2057 } 2058 } 2059 sprev = stmp; 2060 } 2061 if (stmp != NULL && ndiff == 0) 2062 return (stmp); 2063 2064 tmpsiz = sizeof(struct sigwork_entry) + strlen(ent->pid_cmd_file) + 1; 2065 stmp = malloc(tmpsiz); 2066 2067 stmp->run_cmd = 0; 2068 /* If this is a command to run we just set the flag and run command */ 2069 if (ent->flags & CE_PID2CMD) { 2070 stmp->run_cmd = 1; 2071 } else { 2072 set_swpid(stmp, ent); 2073 } 2074 stmp->sw_signum = ent->sig; 2075 strcpy(stmp->sw_fname, ent->pid_cmd_file); 2076 if (sprev == NULL) 2077 SLIST_INSERT_HEAD(&swhead, stmp, sw_nextp); 2078 else 2079 SLIST_INSERT_AFTER(sprev, stmp, sw_nextp); 2080 return (stmp); 2081} 2082 2083/* 2084 * Save information on any file we need to compress. We may see the same 2085 * file multiple times, so check the full list to avoid duplicates. The 2086 * list itself is sorted smallest-to-largest, because that's the order we 2087 * want to compress the files. If the partition is very low on disk space, 2088 * then the smallest files are the most likely to compress, and compressing 2089 * them first will free up more space for the larger files. 2090 */ 2091static struct zipwork_entry * 2092save_zipwork(const struct conf_entry *ent, const struct sigwork_entry *swork, 2093 int zsize, const char *zipfname) 2094{ 2095 struct zipwork_entry *zprev, *ztmp; 2096 int ndiff; 2097 size_t tmpsiz; 2098 2099 /* Compute the size if the caller did not know it. */ 2100 if (zsize < 0) 2101 zsize = sizefile(zipfname); 2102 2103 zprev = NULL; 2104 ndiff = 1; 2105 SLIST_FOREACH(ztmp, &zwhead, zw_nextp) { 2106 ndiff = strcmp(zipfname, ztmp->zw_fname); 2107 if (ndiff == 0) 2108 break; 2109 if (zsize > ztmp->zw_fsize) 2110 zprev = ztmp; 2111 } 2112 if (ztmp != NULL && ndiff == 0) 2113 return (ztmp); 2114 2115 tmpsiz = sizeof(struct zipwork_entry) + strlen(zipfname) + 1; 2116 ztmp = malloc(tmpsiz); 2117 ztmp->zw_conf = ent; 2118 ztmp->zw_swork = swork; 2119 ztmp->zw_fsize = zsize; 2120 strcpy(ztmp->zw_fname, zipfname); 2121 if (zprev == NULL) 2122 SLIST_INSERT_HEAD(&zwhead, ztmp, zw_nextp); 2123 else 2124 SLIST_INSERT_AFTER(zprev, ztmp, zw_nextp); 2125 return (ztmp); 2126} 2127 2128/* Send a signal to the pid specified by pidfile */ 2129static void 2130set_swpid(struct sigwork_entry *swork, const struct conf_entry *ent) 2131{ 2132 FILE *f; 2133 long minok, maxok, rval; 2134 char *endp, *linep, line[BUFSIZ]; 2135 2136 minok = MIN_PID; 2137 maxok = MAX_PID; 2138 swork->sw_pidok = 0; 2139 swork->sw_pid = 0; 2140 swork->sw_pidtype = "daemon"; 2141 if (ent->flags & CE_SIGNALGROUP) { 2142 /* 2143 * If we are expected to signal a process-group when 2144 * rotating this logfile, then the value read in should 2145 * be the negative of a valid process ID. 2146 */ 2147 minok = -MAX_PID; 2148 maxok = -MIN_PID; 2149 swork->sw_pidtype = "process-group"; 2150 } 2151 2152 f = fopen(ent->pid_cmd_file, "r"); 2153 if (f == NULL) { 2154 if (errno == ENOENT && enforcepid == 0) { 2155 /* 2156 * Warn if the PID file doesn't exist, but do 2157 * not consider it an error. Most likely it 2158 * means the process has been terminated, 2159 * so it should be safe to rotate any log 2160 * files that the process would have been using. 2161 */ 2162 swork->sw_pidok = 1; 2163 warnx("pid file doesn't exist: %s", ent->pid_cmd_file); 2164 } else 2165 warn("can't open pid file: %s", ent->pid_cmd_file); 2166 return; 2167 } 2168 2169 if (fgets(line, BUFSIZ, f) == NULL) { 2170 /* 2171 * Warn if the PID file is empty, but do not consider 2172 * it an error. Most likely it means the process has 2173 * has terminated, so it should be safe to rotate any 2174 * log files that the process would have been using. 2175 */ 2176 if (feof(f) && enforcepid == 0) { 2177 swork->sw_pidok = 1; 2178 warnx("pid/cmd file is empty: %s", ent->pid_cmd_file); 2179 } else 2180 warn("can't read from pid file: %s", ent->pid_cmd_file); 2181 (void)fclose(f); 2182 return; 2183 } 2184 (void)fclose(f); 2185 2186 errno = 0; 2187 linep = line; 2188 while (*linep == ' ') 2189 linep++; 2190 rval = strtol(linep, &endp, 10); 2191 if (*endp != '\0' && !isspacech(*endp)) { 2192 warnx("pid file does not start with a valid number: %s", 2193 ent->pid_cmd_file); 2194 } else if (rval < minok || rval > maxok) { 2195 warnx("bad value '%ld' for process number in %s", 2196 rval, ent->pid_cmd_file); 2197 if (verbose) 2198 warnx("\t(expecting value between %ld and %ld)", 2199 minok, maxok); 2200 } else { 2201 swork->sw_pidok = 1; 2202 swork->sw_pid = rval; 2203 } 2204 2205 return; 2206} 2207 2208/* Log the fact that the logs were turned over */ 2209static int 2210log_trim(const char *logname, const struct conf_entry *log_ent) 2211{ 2212 FILE *f; 2213 const char *xtra; 2214 2215 if ((f = fopen(logname, "a")) == NULL) 2216 return (-1); 2217 xtra = ""; 2218 if (log_ent->def_cfg) 2219 xtra = " using <default> rule"; 2220 if (log_ent->firstcreate) 2221 fprintf(f, "%s %s newsyslog[%d]: logfile first created%s\n", 2222 daytime, hostname, (int) getpid(), xtra); 2223 else if (log_ent->r_reason != NULL) 2224 fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s%s\n", 2225 daytime, hostname, (int) getpid(), log_ent->r_reason, xtra); 2226 else 2227 fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s\n", 2228 daytime, hostname, (int) getpid(), xtra); 2229 if (fclose(f) == EOF) 2230 err(1, "log_trim: fclose"); 2231 return (0); 2232} 2233 2234/* Return size in kilobytes of a file */ 2235static int 2236sizefile(const char *file) 2237{ 2238 struct stat sb; 2239 2240 if (stat(file, &sb) < 0) 2241 return (-1); 2242 return (kbytes(dbtob(sb.st_blocks))); 2243} 2244 2245/* Return the age of old log file (file.0) */ 2246static int 2247age_old_log(char *file) 2248{ 2249 struct stat sb; 2250 const char *logfile_suffix; 2251 char tmp[MAXPATHLEN + sizeof(".0") + COMPRESS_SUFFIX_MAXLEN + 1]; 2252 2253 if (archtodir) { 2254 char *p; 2255 2256 /* build name of archive directory into tmp */ 2257 if (*archdirname == '/') { /* absolute */ 2258 strlcpy(tmp, archdirname, sizeof(tmp)); 2259 } else { /* relative */ 2260 /* get directory part of logfile */ 2261 strlcpy(tmp, file, sizeof(tmp)); 2262 if ((p = rindex(tmp, '/')) == NULL) 2263 tmp[0] = '\0'; 2264 else 2265 *(p + 1) = '\0'; 2266 strlcat(tmp, archdirname, sizeof(tmp)); 2267 } 2268 2269 strlcat(tmp, "/", sizeof(tmp)); 2270 2271 /* get filename part of logfile */ 2272 if ((p = rindex(file, '/')) == NULL) 2273 strlcat(tmp, file, sizeof(tmp)); 2274 else 2275 strlcat(tmp, p + 1, sizeof(tmp)); 2276 } else { 2277 (void) strlcpy(tmp, file, sizeof(tmp)); 2278 } 2279 2280 strlcat(tmp, ".0", sizeof(tmp)); 2281 logfile_suffix = get_logfile_suffix(tmp); 2282 if (logfile_suffix == NULL) 2283 return (-1); 2284 (void) strlcat(tmp, logfile_suffix, sizeof(tmp)); 2285 if (stat(tmp, &sb) < 0) 2286 return (-1); 2287 return ((int)(ptimeget_secs(timenow) - sb.st_mtime + 1800) / 3600); 2288} 2289 2290/* Skip Over Blanks */ 2291static char * 2292sob(char *p) 2293{ 2294 while (p && *p && isspace(*p)) 2295 p++; 2296 return (p); 2297} 2298 2299/* Skip Over Non-Blanks */ 2300static char * 2301son(char *p) 2302{ 2303 while (p && *p && !isspace(*p)) 2304 p++; 2305 return (p); 2306} 2307 2308/* Check if string is actually a number */ 2309static int 2310isnumberstr(const char *string) 2311{ 2312 while (*string) { 2313 if (!isdigitch(*string++)) 2314 return (0); 2315 } 2316 return (1); 2317} 2318 2319/* Check if string contains a glob */ 2320static int 2321isglobstr(const char *string) 2322{ 2323 char chr; 2324 2325 while ((chr = *string++)) { 2326 if (chr == '*' || chr == '?' || chr == '[') 2327 return (1); 2328 } 2329 return (0); 2330} 2331 2332/* 2333 * Save the active log file under a new name. A link to the new name 2334 * is the quick-and-easy way to do this. If that fails (which it will 2335 * if the destination is on another partition), then make a copy of 2336 * the file to the new location. 2337 */ 2338static void 2339savelog(char *from, char *to) 2340{ 2341 FILE *src, *dst; 2342 int c, res; 2343 2344 res = link(from, to); 2345 if (res == 0) 2346 return; 2347 2348 if ((src = fopen(from, "r")) == NULL) 2349 err(1, "can't fopen %s for reading", from); 2350 if ((dst = fopen(to, "w")) == NULL) 2351 err(1, "can't fopen %s for writing", to); 2352 2353 while ((c = getc(src)) != EOF) { 2354 if ((putc(c, dst)) == EOF) 2355 err(1, "error writing to %s", to); 2356 } 2357 2358 if (ferror(src)) 2359 err(1, "error reading from %s", from); 2360 if ((fclose(src)) != 0) 2361 err(1, "can't fclose %s", to); 2362 if ((fclose(dst)) != 0) 2363 err(1, "can't fclose %s", from); 2364} 2365 2366/* create one or more directory components of a path */ 2367static void 2368createdir(const struct conf_entry *ent, char *dirpart) 2369{ 2370 int res; 2371 char *s, *d; 2372 char mkdirpath[MAXPATHLEN]; 2373 struct stat st; 2374 2375 s = dirpart; 2376 d = mkdirpath; 2377 2378 for (;;) { 2379 *d++ = *s++; 2380 if (*s != '/' && *s != '\0') 2381 continue; 2382 *d = '\0'; 2383 res = lstat(mkdirpath, &st); 2384 if (res != 0) { 2385 if (noaction) { 2386 printf("\tmkdir %s\n", mkdirpath); 2387 } else { 2388 res = mkdir(mkdirpath, 0755); 2389 if (res != 0) 2390 err(1, "Error on mkdir(\"%s\") for -a", 2391 mkdirpath); 2392 } 2393 } 2394 if (*s == '\0') 2395 break; 2396 } 2397 if (verbose) { 2398 if (ent->firstcreate) 2399 printf("Created directory '%s' for new %s\n", 2400 dirpart, ent->log); 2401 else 2402 printf("Created directory '%s' for -a\n", dirpart); 2403 } 2404} 2405 2406/* 2407 * Create a new log file, destroying any currently-existing version 2408 * of the log file in the process. If the caller wants a backup copy 2409 * of the file to exist, they should call 'link(logfile,logbackup)' 2410 * before calling this routine. 2411 */ 2412void 2413createlog(const struct conf_entry *ent) 2414{ 2415 int fd, failed; 2416 struct stat st; 2417 char *realfile, *slash, tempfile[MAXPATHLEN]; 2418 2419 fd = -1; 2420 realfile = ent->log; 2421 2422 /* 2423 * If this log file is being created for the first time (-C option), 2424 * then it may also be true that the parent directory does not exist 2425 * yet. Check, and create that directory if it is missing. 2426 */ 2427 if (ent->firstcreate) { 2428 strlcpy(tempfile, realfile, sizeof(tempfile)); 2429 slash = strrchr(tempfile, '/'); 2430 if (slash != NULL) { 2431 *slash = '\0'; 2432 failed = stat(tempfile, &st); 2433 if (failed && errno != ENOENT) 2434 err(1, "Error on stat(%s)", tempfile); 2435 if (failed) 2436 createdir(ent, tempfile); 2437 else if (!S_ISDIR(st.st_mode)) 2438 errx(1, "%s exists but is not a directory", 2439 tempfile); 2440 } 2441 } 2442 2443 /* 2444 * First create an unused filename, so it can be chown'ed and 2445 * chmod'ed before it is moved into the real location. mkstemp 2446 * will create the file mode=600 & owned by us. Note that all 2447 * temp files will have a suffix of '.z<something>'. 2448 */ 2449 strlcpy(tempfile, realfile, sizeof(tempfile)); 2450 strlcat(tempfile, ".zXXXXXX", sizeof(tempfile)); 2451 if (noaction) 2452 printf("\tmktemp %s\n", tempfile); 2453 else { 2454 fd = mkstemp(tempfile); 2455 if (fd < 0) 2456 err(1, "can't mkstemp logfile %s", tempfile); 2457 2458 /* 2459 * Add status message to what will become the new log file. 2460 */ 2461 if (!(ent->flags & CE_BINARY)) { 2462 if (log_trim(tempfile, ent)) 2463 err(1, "can't add status message to log"); 2464 } 2465 } 2466 2467 /* Change the owner/group, if we are supposed to */ 2468 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) { 2469 if (noaction) 2470 printf("\tchown %u:%u %s\n", ent->uid, ent->gid, 2471 tempfile); 2472 else { 2473 failed = fchown(fd, ent->uid, ent->gid); 2474 if (failed) 2475 err(1, "can't fchown temp file %s", tempfile); 2476 } 2477 } 2478 2479 /* Turn on NODUMP if it was requested in the config-file. */ 2480 if (ent->flags & CE_NODUMP) { 2481 if (noaction) 2482 printf("\tchflags nodump %s\n", tempfile); 2483 else { 2484 failed = fchflags(fd, UF_NODUMP); 2485 if (failed) { 2486 warn("log_trim: fchflags(NODUMP)"); 2487 } 2488 } 2489 } 2490 2491 /* 2492 * Note that if the real logfile still exists, and if the call 2493 * to rename() fails, then "neither the old file nor the new 2494 * file shall be changed or created" (to quote the standard). 2495 * If the call succeeds, then the file will be replaced without 2496 * any window where some other process might find that the file 2497 * did not exist. 2498 * XXX - ? It may be that for some error conditions, we could 2499 * retry by first removing the realfile and then renaming. 2500 */ 2501 if (noaction) { 2502 printf("\tchmod %o %s\n", ent->permissions, tempfile); 2503 printf("\tmv %s %s\n", tempfile, realfile); 2504 } else { 2505 failed = fchmod(fd, ent->permissions); 2506 if (failed) 2507 err(1, "can't fchmod temp file '%s'", tempfile); 2508 failed = rename(tempfile, realfile); 2509 if (failed) 2510 err(1, "can't mv %s to %s", tempfile, realfile); 2511 } 2512 2513 if (fd >= 0) 2514 close(fd); 2515} 2516 2517/* 2518 * Change the attributes of a given filename to what was specified in 2519 * the newsyslog.conf entry. This routine is only called for files 2520 * that newsyslog expects that it has created, and thus it is a fatal 2521 * error if this routine finds that the file does not exist. 2522 */ 2523static void 2524change_attrs(const char *fname, const struct conf_entry *ent) 2525{ 2526 int failed; 2527 2528 if (noaction) { 2529 printf("\tchmod %o %s\n", ent->permissions, fname); 2530 2531 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) 2532 printf("\tchown %u:%u %s\n", 2533 ent->uid, ent->gid, fname); 2534 2535 if (ent->flags & CE_NODUMP) 2536 printf("\tchflags nodump %s\n", fname); 2537 return; 2538 } 2539 2540 failed = chmod(fname, ent->permissions); 2541 if (failed) { 2542 if (errno != EPERM) 2543 err(1, "chmod(%s) in change_attrs", fname); 2544 warn("change_attrs couldn't chmod(%s)", fname); 2545 } 2546 2547 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) { 2548 failed = chown(fname, ent->uid, ent->gid); 2549 if (failed) 2550 warn("can't chown %s", fname); 2551 } 2552 2553 if (ent->flags & CE_NODUMP) { 2554 failed = chflags(fname, UF_NODUMP); 2555 if (failed) 2556 warn("can't chflags %s NODUMP", fname); 2557 } 2558} 2559