summaryrefslogtreecommitdiffstats
path: root/usr.sbin/newsyslog/newsyslog.c
blob: 4d23f80fbb0b07c091e2b35703b1449145575141 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
/*
 * This file contains changes from the Open Software Foundation.
 */

/*

Copyright 1988, 1989 by the Massachusetts Institute of Technology

Permission to use, copy, modify, and distribute this software
and its documentation for any purpose and without fee is
hereby granted, provided that the above copyright notice
appear in all copies and that both that copyright notice and
this permission notice appear in supporting documentation,
and that the names of M.I.T. and the M.I.T. S.I.P.B. not be
used in advertising or publicity pertaining to distribution
of the software without specific, written prior permission.
M.I.T. and the M.I.T. S.I.P.B. make no representations about
the suitability of this software for any purpose.  It is
provided "as is" without express or implied warranty.

*/

/*
 *      newsyslog - roll over selected logs at the appropriate time,
 *              keeping the a specified number of backup files around.
 *
 *      $Source: /home/ncvs/src/usr.sbin/newsyslog/newsyslog.c,v $
 *      $Author: jkh $
 */

#ifndef lint
static char rcsid[] = "$FreeBSD$";
#endif /* not lint */

#ifndef CONF
#define CONF "/etc/athena/newsyslog.conf" /* Configuration file */
#endif
#ifndef PIDFILE
#define PIDFILE "/etc/syslog.pid"
#endif
#ifndef COMPRESS_PATH
#define COMPRESS_PATH "/usr/ucb/compress" /* File compression program */
#endif
#ifndef COMPRESS_PROG
#define COMPRESS_PROG "compress"
#endif
#ifndef COMPRESS_POSTFIX
#define COMPRESS_POSTFIX ".Z"
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <signal.h>
#include <pwd.h>
#include <grp.h>
#include <fcntl.h>
#include <unistd.h>
#include <err.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <sys/wait.h>

#define kbytes(size)  (((size) + 1023) >> 10)
#ifdef _IBMR2
/* Calculates (db * DEV_BSIZE) */
#define dbtob(db)  ((unsigned)(db) << UBSHIFT) 
#endif

#define CE_COMPACT 1            /* Compact the achived log files */
#define CE_BINARY  2            /* Logfile is in binary, don't add */
                                /* status messages */
#define NONE -1
        
struct conf_entry {
        char    *log;           /* Name of the log */
        int     uid;            /* Owner of log */
        int     gid;            /* Group of log */
        int     numlogs;        /* Number of logs to keep */
        int     size;           /* Size cutoff to trigger trimming the log */
        int     hours;          /* Hours between log trimming */
        int     permissions;    /* File permissions on the log */
        int     flags;          /* Flags (CE_COMPACT & CE_BINARY)  */
        struct conf_entry       *next; /* Linked list pointer */
};

char    *progname;              /* contains argv[0] */
int     verbose = 0;            /* Print out what's going on */
int     needroot = 1;           /* Root privs are necessary */
int     noaction = 0;           /* Don't do anything, just show it */
char    *conf = CONF;           /* Configuration file to use */
time_t  timenow;
int     syslog_pid;             /* read in from /etc/syslog.pid */
#define MIN_PID		3
#define MAX_PID		30000   /* was 65534, see /usr/include/sys/proc.h */
char    hostname[MAXHOSTNAMELEN+1]; /* hostname */
char    *daytime;               /* timenow in human readable form */

#ifndef OSF
char *strdup(char *strp);
#endif

static struct conf_entry *parse_file();
static char *sob(char *p);
static char *son(char *p);
static char *missing_field(char *p,char *errline);
static void do_entry(struct conf_entry *ent);
static void PRS(int argc,char **argv);
static void usage();
static void dotrim(char *log,int numdays,int falgs,int perm, int owner_uid,int group_gid);
static int log_trim(char *log);
static void compress_log(char *log);
static int sizefile(char *file);
static int age_old_log(char *file);

int main(argc,argv)
        int argc;
        char **argv;
{
        struct conf_entry *p, *q;
        
        PRS(argc,argv);
        if (needroot && getuid() && geteuid()) {
                fprintf(stderr,"%s: must have root privs\n",progname);
                return(1);
        }
        p = q = parse_file();
        while (p) {
                do_entry(p);
                p=p->next;
                free((char *) q);
                q=p;
        }
        return(0);
}

static void do_entry(ent)
        struct conf_entry       *ent;
        
{
        int     size, modtime;
        
        if (verbose) {
                if (ent->flags & CE_COMPACT)
                        printf("%s <%dZ>: ",ent->log,ent->numlogs);
                else
                        printf("%s <%d>: ",ent->log,ent->numlogs);
        }
        size = sizefile(ent->log);
        modtime = age_old_log(ent->log);
        if (size < 0) {
                if (verbose)
                        printf("does not exist.\n");
        } else {
                if (verbose && (ent->size > 0))
                        printf("size (Kb): %d [%d] ", size, ent->size);
                if (verbose && (ent->hours > 0))
                        printf(" age (hr): %d [%d] ", modtime, ent->hours);
                if (((ent->size > 0) && (size >= ent->size)) ||
                    ((ent->hours > 0) && ((modtime >= ent->hours)
                                        || (modtime < 0)))) {
                        if (verbose)
                                printf("--> trimming log....\n");
                        if (noaction && !verbose) {
                                if (ent->flags & CE_COMPACT)
                                        printf("%s <%dZ>: trimming",
                                               ent->log,ent->numlogs);
                                else
                                        printf("%s <%d>: trimming",
                                               ent->log,ent->numlogs);
                        }
                        dotrim(ent->log, ent->numlogs, ent->flags,
                               ent->permissions, ent->uid, ent->gid);
                } else {
                        if (verbose)
                                printf("--> skipping\n");
                }
        }
}

static void PRS(argc,argv)
        int argc;
        char **argv;
{
        int     c;
        FILE    *f;
        char    line[BUFSIZ];
	char	*p;

        progname = argv[0];
        timenow = time((time_t *) 0);
        daytime = ctime(&timenow) + 4;
        daytime[15] = '\0';

        /* Let's find the pid of syslogd */
        syslog_pid = 0;
        f = fopen(PIDFILE,"r");
        if (f && fgets(line,BUFSIZ,f))
                syslog_pid = atoi(line);
	if (f)
		(void)fclose(f);

        /* Let's get our hostname */
        (void) gethostname(hostname, sizeof(hostname));

	/* Truncate domain */
	if ((p = strchr(hostname, '.'))) {
		*p = '\0';
	}

        optind = 1;             /* Start options parsing */
        while ((c=getopt(argc,argv,"nrvf:t:")) != EOF)
                switch (c) {
                case 'n':
                        noaction++; /* This implies needroot as off */
                        /* fall through */
                case 'r':
                        needroot = 0;
                        break;
                case 'v':
                        verbose++;
                        break;
                case 'f':
                        conf = optarg;
                        break;
                default:
                        usage();
                }
        }

static void usage()
{
        fprintf(stderr,
                "Usage: %s <-nrv> <-f config-file>\n", progname);
        exit(1);
}

/* Parse a configuration file and return a linked list of all the logs
 * to process
 */
static struct conf_entry *parse_file()
{
        FILE    *f;
        char    line[BUFSIZ], *parse, *q;
        char    *errline, *group;
        struct conf_entry *first = NULL;
        struct conf_entry *working = NULL;
        struct passwd *pass;
        struct group *grp;

        if (strcmp(conf,"-"))
                f = fopen(conf,"r");
        else
                f = stdin;
        if (!f)
                err(1, "%s", conf);
        while (fgets(line,BUFSIZ,f)) {
                if ((line[0]== '\n') || (line[0] == '#'))
                        continue;
                errline = strdup(line);
                if (!first) {
                        working = (struct conf_entry *) malloc(sizeof(struct conf_entry));
                        first = working;
                } else {
                        working->next = (struct conf_entry *) malloc(sizeof(struct conf_entry));
                        working = working->next;
                }

                q = parse = missing_field(sob(line),errline);
                *(parse = son(line)) = '\0';
                working->log = strdup(q);

                q = parse = missing_field(sob(++parse),errline);
                *(parse = son(parse)) = '\0';
                if ((group = strchr(q, '.')) != NULL) {
                    *group++ = '\0';
                    if (*q) {
                        if (!(isnumber(*q))) {
                            if ((pass = getpwnam(q)) == NULL)
                                errx(1, 
                                  "Error in config file; unknown user:\n%s",
                                  errline);
                            working->uid = pass->pw_uid;
                        } else
                            working->uid = atoi(q);
                    } else
                        working->uid = NONE;
                    
                    q = group;
                    if (*q) {
                        if (!(isnumber(*q))) {
                            if ((grp = getgrnam(q)) == NULL)
                                errx(1,
                                  "Error in config file; unknown group:\n%s",
                                  errline);
                            working->gid = grp->gr_gid;
                        } else
                            working->gid = atoi(q);
                    } else
                        working->gid = NONE;
                    
                    q = parse = missing_field(sob(++parse),errline);
                    *(parse = son(parse)) = '\0';
                }
                else 
                    working->uid = working->gid = NONE;

                if (!sscanf(q,"%o",&working->permissions))
                        errx(1, "Error in config file; bad permissions:\n%s",
                          errline);

                q = parse = missing_field(sob(++parse),errline);
                *(parse = son(parse)) = '\0';
                if (!sscanf(q,"%d",&working->numlogs))
                        errx(1, "Error in config file; bad number:\n%s",
                          errline);

                q = parse = missing_field(sob(++parse),errline);
                *(parse = son(parse)) = '\0';
                if (isdigit(*q))
                        working->size = atoi(q);
                else
                        working->size = -1;
                
                q = parse = missing_field(sob(++parse),errline);
                *(parse = son(parse)) = '\0';
                if (isdigit(*q))
                        working->hours = atoi(q);
                else
                        working->hours = -1;

                q = parse = sob(++parse); /* Optional field */
                *(parse = son(parse)) = '\0';
                working->flags = 0;
                while (q && *q && !isspace(*q)) {
                        if ((*q == 'Z') || (*q == 'z'))
                                working->flags |= CE_COMPACT;
                        else if ((*q == 'B') || (*q == 'b'))
                                working->flags |= CE_BINARY;
                        else
                           errx(1, "Illegal flag in config file -- %c", *q);
                        q++;
                }
                
                free(errline);
        }
        if (working)
                working->next = (struct conf_entry *) NULL;
        (void) fclose(f);
        return(first);
}

static char *missing_field(p,errline)
        char    *p,*errline;
{
        if (!p || !*p)
            errx(1, "Missing field in config file:\n%s", errline);
        return(p);
}

static void dotrim(log,numdays,flags,perm,owner_uid,group_gid)
        char    *log;
        int     numdays;
        int     flags;
        int     perm;
        int     owner_uid;
        int     group_gid;
{
        char    file1 [MAXPATHLEN+1], file2 [MAXPATHLEN+1];
        char    zfile1[MAXPATHLEN+1], zfile2[MAXPATHLEN+1];
        int     fd, _numdays;
        struct  stat st;

#ifdef _IBMR2
/* AIX 3.1 has a broken fchown- if the owner_uid is -1, it will actually */
/* change it to be owned by uid -1, instead of leaving it as is, as it is */
/* supposed to. */
                if (owner_uid == -1)
                  owner_uid = geteuid();
#endif

        /* Remove oldest log */
        (void) sprintf(file1,"%s.%d",log,numdays);
        (void) strcpy(zfile1, file1);
        (void) strcat(zfile1, COMPRESS_POSTFIX);

        if (noaction) {
                printf("rm -f %s\n", file1);
                printf("rm -f %s\n", zfile1);
        } else {
                (void) unlink(file1);
                (void) unlink(zfile1);
        }

        /* Move down log files */
	_numdays = numdays;	/* preserve */
        while (numdays--) {
                (void) strcpy(file2,file1);
                (void) sprintf(file1,"%s.%d",log,numdays);
                (void) strcpy(zfile1, file1);
                (void) strcpy(zfile2, file2);
                if (lstat(file1, &st)) {
                        (void) strcat(zfile1, COMPRESS_POSTFIX);
                        (void) strcat(zfile2, COMPRESS_POSTFIX);
                        if (lstat(zfile1, &st)) continue;
                }
                if (noaction) {
                        printf("mv %s %s\n",zfile1,zfile2);
                        printf("chmod %o %s\n", perm, zfile2);
                        printf("chown %d.%d %s\n",
                               owner_uid, group_gid, zfile2);
                } else {
                        (void) rename(zfile1, zfile2);
                        (void) chmod(zfile2, perm);
                        (void) chown(zfile2, owner_uid, group_gid);
                }
        }
        if (!noaction && !(flags & CE_BINARY))
                (void) log_trim(log);  /* Report the trimming to the old log */

	if (!_numdays) {
		if (noaction)
			printf("rm %s\n",log);
		else
			(void)unlink(log);
	}
	else {
		if (noaction)
			printf("mv %s to %s\n",log,file1);
		else
			(void)rename(log, file1);
	}

        if (noaction) 
                printf("Start new log...");
        else {
                fd = creat(log,perm);
                if (fd < 0)
                        err(1, "can't start new log");
                if (fchown(fd, owner_uid, group_gid))
                        err(1, "can't chmod new log file");
                (void) close(fd);
                if (!(flags & CE_BINARY))
                        if (log_trim(log))    /* Add status message */
                             err(1, "can't add status message to log");
        }
        if (noaction)
                printf("chmod %o %s...",perm,log);
        else
                (void) chmod(log,perm);
        if (noaction)
                printf("kill -HUP %d (syslogd)\n",syslog_pid);
        else
	if (syslog_pid < MIN_PID || syslog_pid > MAX_PID) {
		warnx("preposterous process number: %d", syslog_pid);
        } else if (kill(syslog_pid,SIGHUP))
                warn("could not restart syslogd");
        if (flags & CE_COMPACT) {
                if (noaction)
                        printf("Compress %s.0\n",log);
                else
                        compress_log(log);
        }
}

/* Log the fact that the logs were turned over */
static int log_trim(log)
        char    *log;
{
        FILE    *f;
        if ((f = fopen(log,"a")) == NULL)
                return(-1);
        fprintf(f,"%s %s newsyslog[%d]: logfile turned over\n",
                daytime, hostname, (int)getpid());
        if (fclose(f) == EOF)
                err(1, "log_trim: fclose:");
        return(0);
}

/* Fork of /usr/ucb/compress to compress the old log file */
static void compress_log(log)
        char    *log;
{
        int     pid;
        char    tmp[128];
        
        pid = fork();
        (void) sprintf(tmp,"%s.0",log);
        if (pid < 0)
                err(1, "fork");
        else if (!pid) {
                (void) execl(COMPRESS_PATH,COMPRESS_PROG,"-f",tmp,0);
                err(1, COMPRESS_PATH);
        }
}

/* Return size in kilobytes of a file */
static int sizefile(file)
        char    *file;
{
        struct stat sb;

        if (stat(file,&sb) < 0)
                return(-1);
        return(kbytes(dbtob(sb.st_blocks)));
}

/* Return the age of old log file (file.0) */
static int age_old_log(file)
        char    *file;
{
        struct stat sb;
        char tmp[MAXPATHLEN+sizeof(".0")+sizeof(COMPRESS_POSTFIX)+1];

        (void) strcpy(tmp,file);
        if (stat(strcat(tmp,".0"),&sb) < 0)
            if (stat(strcat(tmp,COMPRESS_POSTFIX), &sb) < 0)
                return(-1);
        return( (int) (timenow - sb.st_mtime + 1800) / 3600);
}


#ifndef OSF
/* Duplicate a string using malloc */

char *strdup(strp)
register char   *strp;
{
        register char *cp;

        if ((cp = malloc((unsigned) strlen(strp) + 1)) == NULL)
                abort();
        return(strcpy (cp, strp));
}
#endif

/* Skip Over Blanks */
char *sob(p)
        register char   *p;
{
        while (p && *p && isspace(*p))
                p++;
        return(p);
}

/* Skip Over Non-Blanks */
char *son(p)
        register char   *p;
{
        while (p && *p && !isspace(*p))
                p++;
        return(p);
}
OpenPOWER on IntegriCloud