File: logfetch.c

package info (click to toggle)
xymon 4.3.30-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 11,288 kB
  • sloc: ansic: 69,112; sh: 3,595; makefile: 857; javascript: 452; perl: 48
file content (1503 lines) | stat: -rw-r--r-- 47,396 bytes parent folder | download | duplicates (2)
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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
/*----------------------------------------------------------------------------*/
/* Xymon client logfile collection tool.                                      */
/* This tool retrieves data from logfiles. If run continuously, it will pick  */
/* out the data stored in the logfile over the past 6 runs (30 minutes with   */
/* the default Xymon client polling frequency) and send these data to stdout  */
/* for inclusion in the Xymon "client" message.                               */
/*                                                                            */
/* Copyright (C) 2006-2011 Henrik Storner <henrik@hswn.dk>                    */
/*                                                                            */
/* This program is released under the GNU General Public License (GPL),       */
/* version 2. See the file "COPYING" for details.                             */
/*                                                                            */
/*----------------------------------------------------------------------------*/

static char rcsid[] = "$Id: logfetch.c 8046 2019-04-09 09:33:47Z jccleaver $";

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <limits.h>
#include <errno.h>
#include <regex.h>
#include <glob.h>
#include <pwd.h>
#include <grp.h>

/* Some systems do not have the S_ISSOCK macro for stat() */
#ifdef SCO_SV
#include <cpio.h>
#define S_ISSOCK(m)   (((m) & S_IFMT) == C_ISSOCK)
#endif

#include "libxymon.h"

/* Set via xgetenv */
static char skiptxt[512];
static char curpostxt[512];

/* Is it ok for these to be hardcoded ? */
#define MAXCHECK   102400U   /* When starting, don't look at more than 100 KB of data */
#define MAXMINUTES 30
#define POSCOUNT ((MAXMINUTES / 5) + 1)		/* 0 = current run */
#define DEFAULTSCROLLBACK (POSCOUNT - 1)	/* How far back to begin processing data, in runs */
#define LINES_AROUND_TRIGGER 5

/* Default = use default */
int scrollback = -1;

static int allowexec = 1;

typedef enum { C_NONE, C_LOG, C_FILE, C_DIR, C_COUNT } checktype_t;

typedef struct logdef_t {
#ifdef _LARGEFILE_SOURCE
	off_t lastpos[POSCOUNT];
	off_t maxbytes;
#else
	long lastpos[POSCOUNT];
	long maxbytes;
#endif
	char **trigger;
	int triggercount;
	char **ignore;
	int ignorecount;
	char **deltacountpatterns;
	char **deltacountnames;
	int deltacountcount;
	int *deltacountcounts;
} logdef_t;

typedef struct filedef_t {
	int domd5, dosha1, dosha256, dosha512, dosha224, dosha384, dormd160;
} filedef_t;

typedef struct countdef_t {
	int patterncount;
	char **patternnames;
	char **patterns;
	int *counts;
} countdef_t;

typedef struct checkdef_t {
	char *filename;
	checktype_t checktype;
	struct checkdef_t *next;
	union {
		logdef_t logcheck;
		filedef_t filecheck;
		countdef_t countcheck;
	} check;
} checkdef_t;

checkdef_t *checklist = NULL;


FILE *fileopen(char *filename, int *err)
{
	/* Open a file */
	FILE *fd;

#ifdef BIG_SECURITY_HOLE
	get_root();
#endif

	fd = fopen(filename, "r");
	if (err) *err = errno;

#ifdef BIG_SECURITY_HOLE
	drop_root();
#endif

	return fd;
}

/*
 * A wrapper for fgets() which eats embedded 0x00 characters in the stream.
 */
char *fgets_nonull(char *buf, size_t size, FILE *stream) {
	char *in, *out, *end;

	if (fgets(buf, size - 1, stream) == NULL) 
	        return NULL;

	end = memchr(buf, '\n', size - 1); 

	if (end == NULL) 
	        end = buf + (size - 1); 
	else 
	        end++;

	for (in = out = buf; in < end; in++) {
	        if (*in != '\0') 
		       *out++ = *in;
	}

	*out = '\0';

	return buf;
}


char *logdata(char *filename, logdef_t *logdef)
{
	static char *buf, *replacement = NULL;
	char *startpos, *fillpos, *triggerstartpos, *triggerendpos, *curpos = NULL;
	FILE *fd;
	struct stat st;
	size_t bytesread, bytesleft;
	int openerr, i, status, triggerlinecount, done;
	char *linepos[2*LINES_AROUND_TRIGGER+1];
	int lpidx;
	size_t byteslast, bytestocurrent, bytesin = 0;
	regex_t *deltaexpr = NULL, *ignexpr = NULL, *trigexpr = NULL;
#ifdef _LARGEFILE_SOURCE
	off_t bufsz;
#else
	long bufsz;
#endif

	char *(*triggerptrs)[2] = NULL;
	unsigned int triggerptrs_count = 0;

	dbgprintf("logfetch: -> logdata (%s)\n", filename);

	if (buf) free(buf);
	buf = NULL;

	if (replacement) free(replacement);
	replacement = NULL;

	fd = fileopen(filename, &openerr);
	if (fd == NULL) {
		buf = (char *)malloc(1024 + strlen(filename));
		sprintf(buf, "Cannot open logfile %s : %s\n", filename, strerror(openerr));
		return buf;
	}

	if (debug) {
		for (i = 0; (i < POSCOUNT); i++) dbgprintf(" - fn: %s, pos %d, loc %lu\n", filename, i, logdef->lastpos[i]);
	}

	/*
	 * See how large the file is, and decide where to start reading.
	 * Save the last POSCOUNT positions so we can scrap 5 minutes of data
	 * from one run to the next.
	 */
	fstat(fileno(fd), &st);
	if ((st.st_size < logdef->lastpos[0]) || (st.st_size < logdef->lastpos[POSCOUNT-1])) {
		/*
		 * Logfile shrank - probably it was rotated.
		 * Start from beginning of file.
		 */
		errprintf("logfetch: File %s shrank from >=%zu to %zu bytes in size. Probably rotated; clearing position state\n", filename, logdef->lastpos[POSCOUNT-1], st.st_size);
		for (i=0; (i < POSCOUNT); i++) logdef->lastpos[i] = 0;
	}

	/* Go to the position we were at scrollback times ago (default corresponds to 6 -- 30 minutes when 5m per run) */
#ifdef _LARGEFILE_SOURCE
	fseeko(fd, logdef->lastpos[scrollback], SEEK_SET);
	bufsz = st.st_size - ftello(fd);
	if (bufsz > MAXCHECK) {
		/*
		 * Too much data for us. We have to skip some of the old data.
		 */
		errprintf("logfetch: %s delta %jd bytes exceeds max buffer size %u; skipping some data\n", filename, (intmax_t)bufsz, MAXCHECK);
		logdef->lastpos[scrollback] = st.st_size - MAXCHECK;
		fseeko(fd, logdef->lastpos[scrollback], SEEK_SET);
		bufsz = st.st_size - ftello(fd);
	}
#else
	fseek(fd, logdef->lastpos[scrollback], SEEK_SET);
	bufsz = st.st_size - ftell(fd);
	if (bufsz > MAXCHECK) {
		/*
		 * Too much data for us. We have to skip some of the old data.
		 */
		errprintf("logfetch: %s delta %zu bytes exceeds max buffer size %u; skipping some data\n", filename, bufsz, MAXCHECK);
		logdef->lastpos[scrollback] = st.st_size - MAXCHECK;
		fseek(fd, logdef->lastpos[scrollback], SEEK_SET);
		bufsz = st.st_size - ftell(fd);
	}
#endif

	/* Calculate delta between scrollback (where going to start looking at data) and end of the most recent run.
	 * This is where we place our "CURRENT" marker */
	byteslast = logdef->lastpos[scrollback];
	/* If lastpos[0] is 0, then all of the positions are 0 because we rotated above */
	bytestocurrent = logdef->lastpos[0] - byteslast;

	/* Shift position markers one down for the next round */
	/* lastpos[1] is the previous end location, lastpos[0] will be the end of this run */
	for (i=POSCOUNT-1; (i > 0); i--) logdef->lastpos[i] = logdef->lastpos[i-1];
	logdef->lastpos[0] = st.st_size;

	dbgprintf("logfetch: Current size (ending): %zu bytes. Last end was %zu. Looking %d spots before that, which is %zu. bytestocurrent: %zu\n",
		logdef->lastpos[0], logdef->lastpos[1], scrollback, byteslast, bytestocurrent);

	/*
	 * Get our read buffer.
	 *
	 * NB: fgets() need some extra room in the input buffer.
	 *     If it is missing, we will never detect end-of-file 
	 *     because fgets() will read 0 bytes, but having read that
	 *     it still hasnt reached end-of-file status.
	 *     At least, on some platforms (Solaris, FreeBSD).
	 */
	bufsz += 1023 + strlen(curpostxt);
	startpos = buf = (char *)malloc(bufsz + 1);
	if (buf == NULL) {
		/* Couldnt allocate the buffer */
		return "Out of memory";
	}

	/* Compile the regex patterns */
	if (logdef->deltacountcount) {
		int i, realcount = 0;

		deltaexpr = (regex_t *) malloc(logdef->deltacountcount * sizeof(regex_t));
		for (i=0; (i < logdef->deltacountcount); i++) {
			dbgprintf(" - compiling DELTACOUNT regex: %s\n", logdef->deltacountpatterns[i]);
			status = regcomp(&deltaexpr[realcount++], logdef->deltacountpatterns[i], REG_EXTENDED|REG_ICASE|REG_NOSUB);
			if (status != 0) {
				char regbuf[1000];
				regerror(status, &deltaexpr[--realcount], regbuf, sizeof(regbuf));	/* re-decrement realcount here */
				errprintf("logfetch: could not compile deltacount regex '%s': %s\n", logdef->deltacountpatterns[i], regbuf);
				logdef->deltacountpatterns[i] = logdef->deltacountnames[i] = NULL;
			}
		}
		logdef->deltacountcount = realcount;
	}
	if (logdef->ignorecount) {
               int i, realcount = 0;
		ignexpr = (regex_t *) malloc(logdef->ignorecount * sizeof(regex_t));
		for (i=0; (i < logdef->ignorecount); i++) {
			dbgprintf(" - compiling IGNORE regex: %s\n", logdef->ignore[i]);
			status = regcomp(&ignexpr[realcount++], logdef->ignore[i], REG_EXTENDED|REG_ICASE|REG_NOSUB);
			if (status != 0) {
				char regbuf[1000];
				regerror(status, &ignexpr[--realcount], regbuf, sizeof(regbuf));	/* re-decrement realcount here */
				errprintf("logfetch: could not compile ignore regex '%s': %s\n", logdef->ignore[i], regbuf);
				logdef->ignore[i] = NULL;
			}
		}
		logdef->ignorecount = realcount;
	}
	if (logdef->triggercount) {
		int i, realcount = 0;
		trigexpr = (regex_t *) malloc(logdef->triggercount * sizeof(regex_t));
		for (i=0; (i < logdef->triggercount); i++) {
			dbgprintf(" - compiling TRIGGER regex: %s\n", logdef->trigger[i]);
			status = regcomp(&trigexpr[realcount++], logdef->trigger[i], REG_EXTENDED|REG_ICASE|REG_NOSUB);
			if (status != 0) {
				char regbuf[1000];
				regerror(status, &trigexpr[--realcount], regbuf, sizeof(regbuf));	/* re-decrement realcount here */
				errprintf("logfetch: could not compile trigger regex '%s': %s\n", logdef->trigger[i], regbuf);
				logdef->trigger[i] = NULL;
			}
		}
		logdef->triggercount = realcount;
	}
	triggerstartpos = triggerendpos = NULL;
	triggerlinecount = 0;
	memset(linepos, 0, sizeof(linepos)); lpidx = 0;

	/* 
	 * Read data.
	 * Discard the ignored lines as we go.
	 * Remember the last trigger line we see.
	 */
	fillpos = buf;
	bytesleft = bufsz;
	done = 0;
	while (!ferror(fd) && (bytesleft > 0) && !done && (fgets_nonull(fillpos, bytesleft, fd) != NULL)) {
		int force_trigger = 0;

		/* Mark where we left off */
		bytesin += strlen(fillpos);
		if (!curpos && (bytesin > bytestocurrent)) {
			char *t;

			dbgprintf(" - Last position was %u, found curpos location at %u in current buffer.\n", logdef->lastpos[1], bytesin);
			t = strdup(fillpos);	/* need shuffle about to insert before this line */
			strncpy(fillpos, curpostxt, strlen(curpostxt));		/* add in the CURRENT + \n */
			strncpy(fillpos+strlen(curpostxt), t, strlen(t));	/* add in whatever this line originally was */
			*(fillpos+strlen(curpostxt)+strlen(t)) = '\0';		/* and terminate it */
			xfree(t);						/* free temp */
			curpos = fillpos;					/* leave curpos to the beginning of the CURRENT flag */
			force_trigger = 1;					/* We'll force this to be saved as a trigger later on, so it always gets printed */
		}

		if (*fillpos == '\0') {
			/*
			 * fgets() can return an empty buffer without flagging
			 * end-of-file. It should not happen anymore now that
			 * we have extended the buffer to have room for the
			 * terminating \0 byte, but if it does then we will
			 * catch it here.
			 */
			dbgprintf(" - empty buffer returned; assuming eof\n");
			done = 1;
			continue;
		}

		/* Begin counting lines once we've reached the end of the last run */
		if (curpos && logdef->deltacountcount) {
			int i, match = 0;

			for (i=0; (i < logdef->deltacountcount); i++) {
				match = (regexec(&deltaexpr[i], fillpos, 0, NULL, 0) == 0);
				if (match) { logdef->deltacountcounts[i]++; dbgprintf(" - line matched deltacount %d: %s", i, fillpos); } // fgets stores the newline in
			}
		}

		/* Check ignore pattern */
		if (logdef->ignorecount) {
			int i, match = 0;

			for (i=0; ((i < logdef->ignorecount) && !match); i++) {
				match = (regexec(&ignexpr[i], fillpos, 0, NULL, 0) == 0);
				if (match) dbgprintf(" - line matched ignore %d: %s", i, fillpos); // fgets stores the newline in
			}

			if (force_trigger) {
				/* Oops. We actually wanted this line poked through */
				/* At the moment, we're only entering this state when we've added 'CURRENT\n' to the existing line */
				/* Since we're guaranteeing to downstream users that we're ignoring this, just skip the line */
				/* until the first newline. If we start using force_trigger for other purposes, we might have to change */
				/* the logic here. */
				char *eoln;

				eoln = strchr(fillpos, '\n'); if (eoln && *(eoln + 1)) fillpos = eoln + 1;	// skip first line
			}
			else if (match) continue;
		}

		linepos[lpidx] = fillpos;

		/* See if this is a trigger line */
		if (force_trigger || logdef->triggercount) {
			int i, match = 0;

			if (force_trigger) { match = 1; dbgprintf(" - line forced as a trigger: %s", fillpos); }
			else {
			    for (i=0; ((i < logdef->triggercount) && !match); i++) {
				match = (regexec(&trigexpr[i], fillpos, 0, NULL, 0) == 0);
				if (match) dbgprintf(" - line matched trigger %d: %s", i, fillpos); // fgets stores the newline in
			    }
			}

			if (match) {
				int sidx;
				
				sidx = lpidx - LINES_AROUND_TRIGGER; 
				if (sidx < 0) sidx += (2*LINES_AROUND_TRIGGER + 1);
				triggerstartpos = linepos[sidx]; if (!triggerstartpos) triggerstartpos = buf;
				triggerlinecount = LINES_AROUND_TRIGGER;

				if (triggerptrs == NULL || (triggerptrs_count > 0 && triggerptrs[triggerptrs_count - 1][1] != NULL)) {
					dbgprintf(" - %s trigger line encountered; preparing trigger START & END positioning store\n", ((triggerptrs_count == 0) ? "first" : "additional")); 

					/* Create or resize the trigger pointer array to contain another pair of anchors */
   					triggerptrs = realloc(triggerptrs, (sizeof(char *) * 2) * (++triggerptrs_count));
					if (triggerptrs == NULL) return "Out of memory";

					/* Save the current triggerstartpos as our first anchor in the pair */
					triggerptrs[triggerptrs_count - 1][0] = triggerstartpos;
					triggerptrs[triggerptrs_count - 1][1] = NULL;

					if (triggerptrs_count > 1 && (triggerstartpos <= triggerptrs[triggerptrs_count - 2][1])) {
						/* Whoops! This trigger's LINES_AROUND_TRIGGER bleeds into the prior's LINES_AROUND_TRIGGER */
						triggerptrs[triggerptrs_count - 1][0] = triggerptrs[triggerptrs_count - 2][1];
						dbgprintf("Current trigger START (w/ prepended LINES_AROUND_TRIGGER) would overlap with prior trigger's END. Adjusting.\n");
					}

					dbgprintf(" - new trigger anchor START position set\n");
		               } 
		               else {
					/* Do nothing. Merge the two trigger lines into a single start and end pair by extending the existing */
					dbgprintf("Additional trigger line encountered. Previous trigger START has no set END yet. Compressing anchors.\n");
				}
			}
		}


		/* We want this line */
		lpidx = ((lpidx + 1) % (2*LINES_AROUND_TRIGGER+1));
		fillpos += strlen(fillpos);

		/* Save the current end-position if we had a trigger within the past LINES_AFTER_TRIGGER lines */
		if (triggerlinecount) {
			triggerlinecount--;
			triggerendpos = fillpos;

			if (triggerlinecount == 0) {
				/* Terminate the current trigger anchor pair by aligning the end pointer */
				dbgprintf(" - trigger END position set\n");
				triggerptrs[triggerptrs_count - 1][1] = triggerendpos;
			}
		}

		bytesleft = (bufsz - (fillpos - buf));
		// dbgprintf(" -- bytesleft: %zu\n", bytesleft);
	}

	if (triggerptrs != NULL) {
	        dbgprintf("Marked %i pairs of START and END anchors for consideration.\n", triggerptrs_count);

		/* Ensure that a premature EOF before the last trigger end postion doesn't blow up */
		if (triggerptrs[triggerptrs_count - 1][1] == NULL) triggerptrs[triggerptrs_count -1][1] = fillpos;
	}

	/* Was there an error reading the file? */
	if (ferror(fd)) {
		buf = (char *)malloc(1024 + strlen(filename));
		sprintf(buf, "Error while reading logfile %s : %s\n", filename, strerror(errno));
		startpos = buf;
		goto cleanup;
	}

	bytesread = (fillpos - startpos);
	*(buf + bytesread) = '\0';

	if (bytesread > logdef->maxbytes) {

	        if (triggerptrs != NULL) {
		       size_t triggerbytes, nontriggerbytes, skiptxtbytes, lasttriggeroffset;
		       char *pos, *lasttriggerptr;
		       size_t size;

		       /* Sum the number of bytes required to hold all the trigger content (start -> end anchors) */
		       for (i = 0, triggerbytes = 0, skiptxtbytes = 0; i < triggerptrs_count; i++) {
		           triggerbytes += strlen(triggerptrs[i][0]) - strlen(triggerptrs[i][1]);
		           skiptxtbytes += strlen(skiptxt) * 2;
		       }
	  
		       /* Find the remaining bytes allowed for non-trigger content (and prevent size_t underflow wrap ) */
			nontriggerbytes = (logdef->maxbytes < triggerbytes) ? 0 : (logdef->maxbytes - triggerbytes);
			lasttriggerptr = triggerptrs[triggerptrs_count - 1][1];
			lasttriggeroffset = (fillpos - lasttriggerptr);

		       dbgprintf("Found %zu bytes of trigger data, %zu bytes available space for non-trigger data; last trigger ended %zu bytes from end. Max bytes allowed is %zu.\n", triggerbytes, nontriggerbytes, lasttriggeroffset, logdef->maxbytes);

		       /* Allocate a new buffer, reduced to what we actually can hold */
		       replacement = malloc(sizeof(char) * (triggerbytes + skiptxtbytes + nontriggerbytes + 1));
		       if (replacement == NULL) return "Out of memory";

		       dbgprintf("Staging replacement buffer, %zu bytes.\n", (triggerbytes + skiptxtbytes + nontriggerbytes));

		       /* Iterate each trigger anchor pair, copying into the replacement */
		       for (i = 0, pos = replacement; i < triggerptrs_count; i++) {
		               dbgprintf("Copying buffer content for trigger %i.\n", (i + 1));

		               strncpy(pos, skiptxt, strlen(skiptxt));
		               pos += strlen(skiptxt);

		               size = strlen(triggerptrs[i][0]) - strlen(triggerptrs[i][1]);
		               strncpy(pos, triggerptrs[i][0], size);
		               pos += size;
		       }

		       /* At this point, all the required trigger lines are present */
			*(pos) = '\0';

		       if (nontriggerbytes > 0) {
				char *finalstartptr;

				/* Append non-trigger, up to the allowed byte size remaining, of remaining log content, starting backwards */

				/* Figure out where to start copying from */
				finalstartptr = (fillpos - nontriggerbytes);
				if (finalstartptr < lasttriggerptr) {
					/* 
					 * FIXME: We could have included inter-trigger data here too.
					 * At the moment, duplicate lines are the worse of two evils, so just start from there.
					 */
					finalstartptr = lasttriggerptr;
					nontriggerbytes = (fillpos - finalstartptr);
					dbgprintf("logfetch: More space was available than between last trigger and eof; reducing to %zu bytes\n", nontriggerbytes);
				}

				/* We're already skipping content; so don't send a partial line. Be sure to decrement the subsequent length we feed to strncpy */
				while (*(finalstartptr-1) != '\n') {
					finalstartptr += 1; nontriggerbytes -= 1;
				}

				dbgprintf("logfetch: Delta from end of final trigger to beginning of final section: %zu bytes\n", (finalstartptr - lasttriggerptr) );

				if (finalstartptr > lasttriggerptr) {
					/* Add the final skip for completeness */
					strncpy(pos, skiptxt, strlen(skiptxt));
					pos += strlen(skiptxt);
				}

				/* And copy the the rest of the original buffer content */
				dbgprintf("Copying %zu final bytes of non-trigger content\n", nontriggerbytes);
				strncpy(pos, finalstartptr, nontriggerbytes);
				*(pos + nontriggerbytes) = '\0';	/* re-terminate */
		       }

		       /* Prune out the last line to prevent sending a partial */
		       if (*(pos = &replacement[strlen(replacement) - 1]) != '\n') {
		               while (*pos != '\n') {
		                       pos -= 1;
		               }
		               *(++pos) = '\0';
		       }

		       startpos = replacement;
		       bytesread = strlen(startpos);          
	        }
		else {
			/* Just drop what is too much -- buf+bytesread was terminated above */
			startpos += (bytesread - logdef->maxbytes);
			memcpy(startpos, skiptxt, strlen(skiptxt));
			bytesread = logdef->maxbytes;
		}
	}

	/* Avoid sending a '[' as the first char on a line */
	{
		char *p;

		p = startpos;
		while (p) {
			if (*p == '[') *p = '.';
			p = strstr(p, "\n[");
			if (p) p++;
		}
	}

cleanup:
	if (fd) fclose(fd);

	{
		int i;

		if (logdef->deltacountcount) {
			for (i=0; (i < logdef->deltacountcount); i++) {
				if (logdef->deltacountpatterns[i]) regfree(&deltaexpr[i]);
			}
			xfree(deltaexpr);
		}

		if (logdef->ignorecount) {
			for (i=0; (i < logdef->ignorecount); i++) {
				if (logdef->ignore[i]) regfree(&ignexpr[i]);
			}
			xfree(ignexpr);
		}

		if (logdef->triggercount) {
			for (i=0; (i < logdef->triggercount); i++) {
				if (logdef->trigger[i]) regfree(&trigexpr[i]);
			}
			xfree(trigexpr);
		}

		if (triggerptrs) xfree(triggerptrs);
	}

	if (debug) {
		for (i = 0; (i < POSCOUNT); i++) dbgprintf(" -- fn: %s, pos %d, loc %lu\n", filename, i, logdef->lastpos[i]);
	}

	dbgprintf("logfetch: <- logdata (%s)\n", filename);
	return startpos;
}

char *ftypestr(unsigned int mode, char *symlink)
{
	static char *result = NULL;
	char *s = "unknown";

	if (S_ISREG(mode)) s = "file";
	if (S_ISDIR(mode)) s = "directory";
	if (S_ISCHR(mode)) s = "char-device";
	if (S_ISBLK(mode)) s = "block-device";
	if (S_ISFIFO(mode)) s = "FIFO";
	if (S_ISSOCK(mode)) s = "socket";

	if (symlink == NULL) return s;

	/* Special handling for symlinks */
	if (result) free(result);

	result = (char *)malloc(strlen(s) + strlen(symlink) + 100);
	sprintf(result, "%s, symlink -> %s", s, symlink);
	return result;
}

char *fmodestr(unsigned int mode)
{
	static char modestr[11];

	if (S_ISREG(mode)) modestr[0] = '-';
	else if (S_ISDIR(mode)) modestr[0] = 'd';
	else if (S_ISCHR(mode)) modestr[0] = 'c';
	else if (S_ISBLK(mode)) modestr[0] = 'b';
	else if (S_ISFIFO(mode)) modestr[0] = 'p';
	else if (S_ISLNK(mode)) modestr[0] = 'l';
	else if (S_ISSOCK(mode)) modestr[0] = 's';
	else modestr[0] = '?';

	modestr[1] = ((mode & S_IRUSR) ? 'r' : '-');
	modestr[2] = ((mode & S_IWUSR) ? 'w' : '-');
	modestr[3] = ((mode & S_IXUSR) ? 'x' : '-');
	modestr[4] = ((mode & S_IRGRP) ? 'r' : '-');
	modestr[5] = ((mode & S_IWGRP) ? 'w' : '-');
	modestr[6] = ((mode & S_IXGRP) ? 'x' : '-');
	modestr[7] = ((mode & S_IROTH) ? 'r' : '-');
	modestr[8] = ((mode & S_IWOTH) ? 'w' : '-');
	modestr[9] = ((mode & S_IXOTH) ? 'x' : '-');

	if ((mode & S_ISUID)) modestr[3] = 's';
	if ((mode & S_ISGID)) modestr[6] = 's';

	modestr[10] = '\0';

	return modestr;
}

char *timestr(time_t tstamp)
{
	static char result[20];

	strftime(result, sizeof(result), "%Y/%m/%d-%H:%M:%S", localtime(&tstamp));
	return result;
}

char *filesum(char *fn, char *dtype)
{
	static char *result = NULL;
	digestctx_t *ctx;
	FILE *fd;
	unsigned char buf[8192];
	int openerr, buflen;

        if ((ctx = digest_init(dtype)) == NULL) return "";

	fd = fileopen(fn, &openerr); 
	if (fd == NULL) return "";
	while ((buflen = fread(buf, 1, sizeof(buf), fd)) > 0) digest_data(ctx, buf, buflen);
	fclose(fd);

	if (result) xfree(result);
	result = strdup(digest_done(ctx));

	return result;
}

void printfiledata(FILE *fd, char *fn, int domd5, int dosha1, int dosha256, int dosha512, int dosha224, int dosha384, int dormd160)
{
	struct stat st;
	struct passwd *pw;
	struct group *gr;
	int staterror;
	char linknam[PATH_MAX];
	time_t now = getcurrenttime(NULL);

	*linknam = '\0';
	staterror = lstat(fn, &st);
	if ((staterror == 0) && S_ISLNK(st.st_mode)) {
		int n = readlink(fn, linknam, sizeof(linknam)-1);
		if (n == -1) n = 0;
		linknam[n] = '\0';
		staterror = stat(fn, &st);
	}

	if (staterror == -1) {
		fprintf(fd, "ERROR: %s\n", strerror(errno));
	}
	else {
		char *stsizefmt;

		pw = getpwuid(st.st_uid);
		gr = getgrgid(st.st_gid);

		fprintf(fd, "type:%o (%s)\n", 
			(unsigned int)(st.st_mode & S_IFMT), 
			ftypestr(st.st_mode, (*linknam ? linknam : NULL)));
		fprintf(fd, "mode:%o (%s)\n", 
			(unsigned int)(st.st_mode & (S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO)), 
			fmodestr(st.st_mode));
		fprintf(fd, "linkcount:%d\n", (int)st.st_nlink);
		fprintf(fd, "owner:%u (%s)\n", (unsigned int)st.st_uid, (pw ? pw->pw_name : ""));
		fprintf(fd, "group:%u (%s)\n", (unsigned int)st.st_gid, (gr ? gr->gr_name : ""));

		if (sizeof(st.st_size) == sizeof(long long int)) stsizefmt = "size:%lld\n";
		else stsizefmt = "size:%ld\n";
		fprintf(fd, stsizefmt,         st.st_size);

		fprintf(fd, "clock:%u (%s)\n", (unsigned int)now, timestr(now));
		fprintf(fd, "atime:%u (%s)\n", (unsigned int)st.st_atime, timestr(st.st_atime));
		fprintf(fd, "ctime:%u (%s)\n", (unsigned int)st.st_ctime, timestr(st.st_ctime));
		fprintf(fd, "mtime:%u (%s)\n", (unsigned int)st.st_mtime, timestr(st.st_mtime));
		if (S_ISREG(st.st_mode)) {
			if      (domd5) fprintf(fd, "%s\n", filesum(fn, "md5"));
			else if (dosha1) fprintf(fd, "%s\n", filesum(fn, "sha1"));
			else if (dosha256) fprintf(fd, "%s\n", filesum(fn, "sha256"));
			else if (dosha512) fprintf(fd, "%s\n", filesum(fn, "sha512"));
			else if (dosha224) fprintf(fd, "%s\n", filesum(fn, "sha224"));
			else if (dosha384) fprintf(fd, "%s\n", filesum(fn, "sha384"));
			else if (dormd160) fprintf(fd, "%s\n", filesum(fn, "rmd160"));
		}
	}

	fprintf(fd, "\n");
}

void printdirdata(FILE *fd, char *fn)
{
	char *ducmd;
	FILE *cmdfd;
	char *cmd;
	char buf[4096];
	int buflen;
	struct stat st;
	int staterror;

	ducmd = xgetenv("DU");

	staterror = stat(fn, &st);
	if (staterror == -1) {
		fprintf(fd, "ERROR: %s\n", strerror(errno));
		return;
	}
	else if (!S_ISDIR(st.st_mode)) {
		fprintf(fd, "ERROR: Not a directory\n");
		return;
	}

	/* Cannot handle filenames with a quote in them (insecure) */
	if (strchr(fn, '\'')) return;

	cmd = (char *)malloc(strlen(ducmd) + strlen(fn) + 10);
	sprintf(cmd, "%s '%s' 2>&1", ducmd, fn);

	cmdfd = popen(cmd, "r");
	xfree(cmd);
	if (cmdfd == NULL) return;

	while ((buflen = fread(buf, 1, sizeof(buf), cmdfd)) > 0) fwrite(buf, 1, buflen, fd);
	pclose(cmdfd);

	fprintf(fd, "\n");
}

void printcountdata(FILE *fd, checkdef_t *cfg)
{
	int openerr, idx;
	FILE *logfd;
	regex_t *exprs;
	regmatch_t pmatch[1];
	int *counts;
	char l[8192];
	
	logfd = fileopen(cfg->filename, &openerr); 
	if (logfd == NULL) {
		fprintf(fd, "ERROR: Cannot open file %s: %s\n", cfg->filename, strerror(openerr));
		return;
	}

	counts = (int *)calloc(cfg->check.countcheck.patterncount, sizeof(int));
	exprs = (regex_t *)calloc(cfg->check.countcheck.patterncount, sizeof(regex_t));
	for (idx = 0; (idx < cfg->check.countcheck.patterncount); idx++) {
		int status;

		status = regcomp(&exprs[idx], cfg->check.countcheck.patterns[idx], REG_EXTENDED|REG_NOSUB);
		if (status != 0) { /* ... */ };
	}

	while (fgets(l, sizeof(l), logfd)) {
		for (idx = 0; (idx < cfg->check.countcheck.patterncount); idx++) {
			if (regexec(&exprs[idx], l, 1, pmatch, 0) == 0) counts[idx] += 1;
		}
	}

	fclose(logfd);

	for (idx = 0; (idx < cfg->check.countcheck.patterncount); idx++) {
		fprintf(fd, "%s: %d\n", 
			cfg->check.countcheck.patternnames[idx], counts[idx]);

		regfree(&exprs[idx]);
	}

	free(counts);
	free(exprs);
}

int loadconfig(char *cfgfn)
{
	FILE *fd;
	char l[PATH_MAX + 1024];
	checkdef_t *currcfg = NULL;
	checkdef_t *firstpipeitem = NULL;

	/* Config items are in the form:
	 *    log:filename:maxbytes
	 *    ignore ignore-regexp (optional)
	 *    trigger trigger-regexp (optional)
	 *    deltacount label deltacount-regexp (optional)
	 *
	 *    file:filename
	 */
	fd = fopen(cfgfn, "r"); if (fd == NULL) return 1;
	while (fgets(l, sizeof(l), fd) != NULL) {
		checktype_t checktype;
		char *bol, *filename;
		int maxbytes, domd5, dosha1, dosha256, dosha512, dosha224, dosha384, dormd160;

		{ char *p = strchr(l, '\n'); if (p) *p = '\0'; }

		bol = l + strspn(l, " \t");
		if ((*bol == '\0') || (*bol == '#')) continue;

		if      (strncmp(bol, "log:", 4) == 0) checktype = C_LOG;
		else if (strncmp(bol, "file:", 5) == 0) checktype = C_FILE;
		else if (strncmp(bol, "dir:", 4) == 0) checktype = C_DIR;
		else if (strncmp(bol, "linecount:", 10) == 0) checktype = C_COUNT;
		else checktype = C_NONE;

		if (checktype != C_NONE) {
			char *tok;

			filename = NULL; maxbytes = -1; domd5 = dosha1 = dosha256 = dosha512 = dosha224 = dosha384 = dormd160 = 0;

			/* Skip the initial keyword token */
			tok = strtok(l, ":"); filename = strtok(NULL, ":");
			switch (checktype) {
			  case C_LOG:
				tok = (filename ? strtok(NULL, ":") : NULL);
				if (tok) maxbytes = atoi(tok);
				break;

			  case C_FILE:
				maxbytes = 0; /* Needed to get us into the put-into-list code */
				tok = (filename ? strtok(NULL, ":") : NULL);
				if (tok) {
					if (strcasecmp(tok, "md5") == 0) domd5 = 1;
					else if (strcasecmp(tok, "sha1") == 0) dosha1 = 1;
					else if (strcasecmp(tok, "sha256") == 0) dosha256 = 1;
					else if (strcasecmp(tok, "sha512") == 0) dosha512 = 1;
					else if (strcasecmp(tok, "sha224") == 0) dosha224 = 1;
					else if (strcasecmp(tok, "sha384") == 0) dosha384 = 1;
					else if (strcasecmp(tok, "rmd160") == 0) dormd160 = 1;
				}
				break;

			  case C_DIR:
				maxbytes = 0; /* Needed to get us into the put-into-list code */
				break;

			  case C_COUNT:
				maxbytes = 0; /* Needed to get us into the put-into-list code */
				break;

			  case C_NONE:
				break;
			}

			if ((filename != NULL) && (maxbytes != -1)) {
				checkdef_t *newitem;

				firstpipeitem = NULL;

				if (*filename == '`') {
					/* Run the command to get filenames */
					char *p;
					char *cmd;
					FILE *fd = NULL;

					cmd = filename+1;
					p = strchr(cmd, '`'); if (p) *p = '\0';
					if (allowexec) fd = popen(cmd, "r");
					else fprintf(stderr, "logfetch given --noexec option but config told to run command '%s'\n", cmd);

					if (fd) {
						char pline[PATH_MAX+1];

						while (fgets(pline, sizeof(pline), fd)) {
							checkdef_t *cwalk = NULL;

							p = pline + strcspn(pline, "\r\n"); *p = '\0';
							for (cwalk = checklist; (cwalk); cwalk = cwalk->next) {
								if ((cwalk->checktype == checktype) && (strcmp(cwalk->filename, pline) == 0)) {
									dbgprintf("logfetch: file %s already seen in config; ignoring this entry\n", cwalk->filename);
									break;
								}
							}
							if (cwalk) continue;

							newitem = calloc(sizeof(checkdef_t), 1);

							newitem->checktype = checktype;
							newitem->filename = strdup(pline);

							switch (checktype) {
					  		  case C_LOG:
								newitem->check.logcheck.maxbytes = maxbytes;
								break;
							  case C_FILE:
								newitem->check.filecheck.domd5 = domd5;
								newitem->check.filecheck.dosha1 = dosha1;
								newitem->check.filecheck.dosha256 = dosha256;
								newitem->check.filecheck.dosha512 = dosha512;
								newitem->check.filecheck.dosha224 = dosha224;
								newitem->check.filecheck.dosha384 = dosha384;
								newitem->check.filecheck.dormd160 = dormd160;
								break;
							  case C_DIR:
								break;
							  case C_COUNT:
								newitem->check.countcheck.patterncount = 0;
								newitem->check.countcheck.patternnames = calloc(1, sizeof(char *));
								newitem->check.countcheck.patterns = calloc(1, sizeof(char *));
								break;
					  		  case C_NONE:
								break;
							}

							newitem->next = checklist;
							checklist = newitem;

							/*
							 * Since we insert new items at the head of the list,
							 * currcfg points to the first item in the list of
							 * these log configs. firstpipeitem points to the
							 * last item inside the list which is part of this
							 * configuration.
							 */
							currcfg = newitem;
							if (!firstpipeitem) firstpipeitem = newitem;
						}

						if (fd) pclose(fd);
					}
				}
				else if (*filename == '<') {
					/* Resolve the glob to get filenames */
					char *p;
					char *fileglob;
					glob_t globbuf;
					int n, i;

					fileglob = filename+1;
					p = strchr(fileglob, '>'); if (p) *p = '\0';
					dbgprintf(" - searching file glob: %s\n", fileglob);
/* Some of these are GNU extensions */
#if !defined(HAVE_GLOB_NOMAGIC) || !defined(HAVE_GLOB_BRACE)
					n = glob(fileglob, GLOB_MARK | GLOB_NOCHECK , NULL, &globbuf);
#else
					n = glob(fileglob, GLOB_MARK | GLOB_NOCHECK | GLOB_BRACE | GLOB_NOMAGIC , NULL, &globbuf);
#endif

					if (n) errprintf("Error searching glob pattern '%s': %s\n", fileglob, strerror(errno));
					else {

						for (i = 0; (globbuf.gl_pathv[i] && (*(globbuf.gl_pathv[i]))) ; i++) {
							checkdef_t *cwalk = NULL;

							dbgprintf(" -- found matching path: %s\n", globbuf.gl_pathv[i]);

							for (cwalk = checklist; (cwalk); cwalk = cwalk->next) {
								if ((cwalk->checktype == checktype) && (strcmp(cwalk->filename, globbuf.gl_pathv[i]) == 0)) {
									dbgprintf("logfetch: file %s already seen in config; ignoring this entry\n", cwalk->filename);
									break;
								}
							}
							if (cwalk) continue;

							newitem = calloc(sizeof(checkdef_t), 1);

							newitem->checktype = checktype;
							newitem->filename = strdup(globbuf.gl_pathv[i]);

							switch (checktype) {
					  		  case C_LOG:
								newitem->check.logcheck.maxbytes = maxbytes;
								break;
							  case C_FILE:
								newitem->check.filecheck.domd5 = domd5;
								newitem->check.filecheck.dosha1 = dosha1;
								newitem->check.filecheck.dosha256 = dosha256;
								newitem->check.filecheck.dosha512 = dosha512;
								newitem->check.filecheck.dosha224 = dosha224;
								newitem->check.filecheck.dosha384 = dosha384;
								newitem->check.filecheck.dormd160 = dormd160;
								break;
							  case C_DIR:
								break;
							  case C_COUNT:
								newitem->check.countcheck.patterncount = 0;
								newitem->check.countcheck.patternnames = calloc(1, sizeof(char *));
								newitem->check.countcheck.patterns = calloc(1, sizeof(char *));
								break;
					  		  case C_NONE:
								break;
							}

							newitem->next = checklist;
							checklist = newitem;

							/*
							 * Since we insert new items at the head of the list,
							 * currcfg points to the first item in the list of
							 * these log configs. firstpipeitem points to the
							 * last item inside the list which is part of this
							 * configuration.
							 */
							currcfg = newitem;
							if (!firstpipeitem) firstpipeitem = newitem;
						}

					}
					globfree(&globbuf);
				}
				else {
					checkdef_t *cwalk = NULL;

					for (cwalk = checklist; (cwalk); cwalk = cwalk->next) {
						if ((cwalk->checktype == checktype) && (strcmp(cwalk->filename, filename) == 0)) {
							dbgprintf("logfetch: file %s already seen in config; ignoring this entry\n", cwalk->filename);
							break;
						}
					}

				     if (!cwalk) {
					newitem = calloc(sizeof(checkdef_t), 1);
					newitem->filename = strdup(filename);
					newitem->checktype = checktype;

					switch (checktype) {
					  case C_LOG:
						newitem->check.logcheck.maxbytes = maxbytes;
						break;
					  case C_FILE:
						newitem->check.filecheck.domd5 = domd5;
						newitem->check.filecheck.dosha1 = dosha1;
						newitem->check.filecheck.dosha256 = dosha256;
						newitem->check.filecheck.dosha512 = dosha512;
						newitem->check.filecheck.dosha224 = dosha224;
						newitem->check.filecheck.dosha384 = dosha384;
						newitem->check.filecheck.dormd160 = dormd160;
						break;
					  case C_DIR:
						break;
					  case C_COUNT:
						newitem->check.countcheck.patterncount = 0;
						newitem->check.countcheck.patternnames = calloc(1, sizeof(char *));
						newitem->check.countcheck.patterns = calloc(1, sizeof(char *));
						break;
					  case C_NONE:
						break;
					}

					newitem->next = checklist;
					checklist = newitem;

					currcfg = newitem;
				     }
				}
			}
			else {
				currcfg = NULL;
				firstpipeitem = NULL;
			}
		}
		else if (currcfg && (currcfg->checktype == C_LOG)) {
			if (strncmp(bol, "ignore ", 7) == 0) {
				char *p; 

				p = bol + 7; p += strspn(p, " \t");

				if (firstpipeitem) {
					/* Fill in this ignore expression on all items in this pipe set */
					checkdef_t *walk = currcfg;

					do {
						walk->check.logcheck.ignorecount++;
						if (walk->check.logcheck.ignore == NULL) {
							walk->check.logcheck.ignore = (char **)malloc(sizeof(char *));
						}
						else {
							walk->check.logcheck.ignore = 
								(char **)realloc(walk->check.logcheck.ignore, 
										 walk->check.logcheck.ignorecount * sizeof(char **));
						}

						walk->check.logcheck.ignore[walk->check.logcheck.ignorecount-1] = strdup(p);

						walk = walk->next;
					} while (walk && (walk != firstpipeitem->next));
				}
				else {
					currcfg->check.logcheck.ignorecount++;
					if (currcfg->check.logcheck.ignore == NULL) {
						currcfg->check.logcheck.ignore = (char **)malloc(sizeof(char *));
					}
					else {
						currcfg->check.logcheck.ignore = 
							(char **)realloc(currcfg->check.logcheck.ignore, 
									 currcfg->check.logcheck.ignorecount * sizeof(char **));
					}

					currcfg->check.logcheck.ignore[currcfg->check.logcheck.ignorecount-1] = strdup(p);
				}
			}
			else if (strncmp(bol, "trigger ", 8) == 0) {
				char *p; 

				p = bol + 8; p += strspn(p, " \t");

				if (firstpipeitem) {
					/* Fill in this trigger expression on all items in this pipe set */
					checkdef_t *walk = currcfg;

					do {
						walk->check.logcheck.triggercount++;
						if (walk->check.logcheck.trigger == NULL) {
							walk->check.logcheck.trigger = (char **)malloc(sizeof(char *));
						}
						else {
							walk->check.logcheck.trigger = 
								(char **)realloc(walk->check.logcheck.trigger, 
										 walk->check.logcheck.triggercount * sizeof(char **));
						}

						walk->check.logcheck.trigger[walk->check.logcheck.triggercount-1] = strdup(p);

						walk = walk->next;
					} while (walk && (walk != firstpipeitem->next));
				}
				else {
					currcfg->check.logcheck.triggercount++;
					if (currcfg->check.logcheck.trigger == NULL) {
						currcfg->check.logcheck.trigger = (char **)malloc(sizeof(char *));
					}
					else {
						currcfg->check.logcheck.trigger = 
							(char **)realloc(currcfg->check.logcheck.trigger, 
									 currcfg->check.logcheck.triggercount * sizeof(char **));
					}

					currcfg->check.logcheck.trigger[currcfg->check.logcheck.triggercount-1] = strdup(p);
				}
			}
			else if (strncmp(bol, "deltacount ", 11) == 0) {
				char *p; 

				p = bol + 11; p += strspn(p, " \t");

				if (firstpipeitem) {
					/* Fill in this trigger expression on all items in this pipe set */
					checkdef_t *walk = currcfg;
					char *name, *ptn = NULL;

					name = strtok(p, " :");
					if (name) ptn = strtok(NULL, "\n");

					if (name && ptn) {
					    do {
						walk->check.logcheck.deltacountcount++;

						walk->check.logcheck.deltacountnames = 
							realloc(walk->check.logcheck.deltacountnames,
								(walk->check.logcheck.deltacountcount)*sizeof(char *));

						walk->check.logcheck.deltacountpatterns = 
							realloc(walk->check.logcheck.deltacountpatterns,
								(walk->check.logcheck.deltacountcount)*sizeof(char *));

						walk->check.logcheck.deltacountnames[walk->check.logcheck.deltacountcount-1] = strdup(name);
						walk->check.logcheck.deltacountpatterns[walk->check.logcheck.deltacountcount-1] = strdup(ptn);

						walk = walk->next;

					    } while (walk && (walk != firstpipeitem->next));

					    /* Initialize buckets since we may not re-walk this later */
					    if (walk->check.logcheck.deltacountcount) walk->check.logcheck.deltacountcounts = (int *)calloc(walk->check.logcheck.deltacountcount, sizeof(int));
					}
				}
				else {
					char *name, *ptn = NULL;

					name = strtok(p, " :");
					if (name) ptn = strtok(NULL, "\n");

					if (name && ptn) {
						currcfg->check.logcheck.deltacountcount++;

						currcfg->check.logcheck.deltacountnames = 
							realloc(currcfg->check.logcheck.deltacountnames,
								(currcfg->check.logcheck.deltacountcount)*sizeof(char *));

						currcfg->check.logcheck.deltacountpatterns = 
							realloc(currcfg->check.logcheck.deltacountpatterns,
								(currcfg->check.logcheck.deltacountcount)*sizeof(char *));

						currcfg->check.logcheck.deltacountnames[currcfg->check.logcheck.deltacountcount-1] = strdup(name);
						currcfg->check.logcheck.deltacountpatterns[currcfg->check.logcheck.deltacountcount-1] = strdup(ptn);
					}

					/* Initialize buckets since we may not re-walk this later */
					if (currcfg->check.logcheck.deltacountcount) currcfg->check.logcheck.deltacountcounts = (int *)calloc(currcfg->check.logcheck.deltacountcount, sizeof(int));
				}
			}
		}
		else if (currcfg && (currcfg->checktype == C_FILE)) {
			/* Nothing */
		}
		else if (currcfg && (currcfg->checktype == C_DIR)) {
			/* Nothing */
		}
		else if (currcfg && (currcfg->checktype == C_COUNT)) {
			int idx;
			char *name, *ptn = NULL;

			name = strtok(l, " :");
			if (name) ptn = strtok(NULL, "\n");
			idx = currcfg->check.countcheck.patterncount;

			if (name && ptn) {
				currcfg->check.countcheck.patterncount += 1;

				currcfg->check.countcheck.patternnames = 
					realloc(currcfg->check.countcheck.patternnames,
						(currcfg->check.countcheck.patterncount+1)*sizeof(char *));

				currcfg->check.countcheck.patterns = 
					realloc(currcfg->check.countcheck.patterns,
						(currcfg->check.countcheck.patterncount+1)*sizeof(char *));

				currcfg->check.countcheck.patternnames[idx] = strdup(name);
				currcfg->check.countcheck.patterns[idx] = strdup(ptn);
			}
		}
		else if (currcfg && (currcfg->checktype == C_NONE)) {
			/* Nothing */
		}
		else {
			currcfg = NULL;
			firstpipeitem = NULL;
		}
	}

	fclose(fd);
	return 0;
}

void loadlogstatus(char *statfn)
{
	FILE *fd;
	char l[PATH_MAX + 1024];

	fd = fopen(statfn, "r");
	if (!fd) return;

	while (fgets(l, sizeof(l), fd)) {
		char *fn, *tok;
		checkdef_t *walk;
		int i;

		tok = strtok(l, ":"); if (!tok) continue;
		fn = tok;
		for (walk = checklist; (walk && ((walk->checktype != C_LOG) || (strcmp(walk->filename, fn) != 0))); walk = walk->next) ;
		if (!walk) continue;

		for (i=0; (tok && (i < POSCOUNT)); i++) {
			tok = strtok(NULL, ":\n");
#ifdef _LARGEFILE_SOURCE
			if (tok) walk->check.logcheck.lastpos[i] = (off_t)str2ll(tok, NULL);
#else
			if (tok) walk->check.logcheck.lastpos[i] = atol(tok);
#endif

			/* Sanity check */
			if (walk->check.logcheck.lastpos[i] < 0) walk->check.logcheck.lastpos[i] = 0;
		}
	}

	fclose(fd);
}

void savelogstatus(char *statfn)
{
	FILE *fd;
	checkdef_t *walk;

	fd = fopen(statfn, "w");
	if (fd == NULL) return;

	for (walk = checklist; (walk); walk = walk->next) {
		int i;
		char *fmt;

		if (walk->checktype != C_LOG) continue;


		if (sizeof(walk->check.logcheck.lastpos[i]) == sizeof(long long int)) fmt = ":%lld";
		else fmt = ":%ld";

		fprintf(fd, "%s", walk->filename);
		for (i = 0; (i < POSCOUNT); i++) fprintf(fd, fmt, walk->check.logcheck.lastpos[i]);
		fprintf(fd, "\n");
	}
	fclose(fd);
}

int main(int argc, char *argv[])
{
	char *cfgfn = NULL, *statfn = NULL;
	int i;
	checkdef_t *walk;

#ifdef BIG_SECURITY_HOLE
	drop_root();
#else
	drop_root_and_removesuid(argv[0]);
#endif

	for (i=1; (i<argc); i++) {
		if (strncmp(argv[i], "--debug", 7) == 0) {
			char *delim = strchr(argv[i], '=');
			debug = 1;
			if (delim) set_debugfile(delim+1, 0);
		}
		else if (strncmp(argv[i], "--noexec", 8) == 0) {
			allowexec = 0;
		}
		else if (strcmp(argv[i], "--clock") == 0) {
			struct timeval tv;
			struct timezone tz;
			struct tm *tm;
			char timestr[50];

			gettimeofday(&tv, &tz);
			printf("epoch: %ld.%06ld\n", (long int)tv.tv_sec, (long int)tv.tv_usec);

			/*
			 * OpenBSD mistakenly has struct timeval members defined as "long",
			 * but requires localtime and gmtime to have a "time_t *" argument.
			 * Figures ...
			 */
			tm = localtime((time_t *)&tv.tv_sec);
			strftime(timestr, sizeof(timestr), "local: %Y-%m-%d %H:%M:%S %Z", tm);
			printf("%s\n", timestr);

			tm = gmtime((time_t *)&tv.tv_sec);
			strftime(timestr, sizeof(timestr), "UTC: %Y-%m-%d %H:%M:%S %Z", tm);
			printf("%s\n", timestr);
			return 0;
		}
		else if ((*(argv[i]) == '-') && (strlen(argv[i]) > 1)) {
			fprintf(stderr, "Unknown option %s\n", argv[i]);
		}
		else {
			/* Not an option -- should have two arguments left: our config and status file */
			if (cfgfn == NULL) cfgfn = argv[i];
			else if (statfn == NULL) statfn = argv[i];
			else fprintf(stderr, "Unknown argument '%s'\n", argv[i]);
		}
	}


	if (scrollback == -1) {
		char *p;

		p = getenv("LOGFETCHSCROLLBACK");
		if (!p) p = getenv("LOGFETCH_SCROLLBACK"); /* compat */
		if (!p || (strlen(p) == 0) ) scrollback = DEFAULTSCROLLBACK;
		else {
			int scroll;
			scroll = atoi(p);

			/* Don't use DEFAULTSCROLLBACK here in case we change or lower the default in the future */
			if ((scroll < 0) || (scroll > (POSCOUNT-1)) ) {
				errprintf("Scrollback requested (%d) is greater than max saved (%d)\n", scroll, (POSCOUNT - 1) );
				scrollback = DEFAULTSCROLLBACK;
			}
			else {
				dbgprintf("logfetch: setting scrollback to %d\n", scroll);
				scrollback = scroll;
			}
		}
	}


	if ((cfgfn == NULL) || (statfn == NULL)) {
		fprintf(stderr, "Missing config or status file arguments\n");
		return 1;
	}

	if (loadconfig(cfgfn) != 0) return 1;
	loadlogstatus(statfn);

	snprintf(skiptxt, sizeof(skiptxt), "%s\n", xgetenv("LOGFETCHSKIPTEXT"));
	snprintf(curpostxt, sizeof(curpostxt), "%s\n", xgetenv("LOGFETCHCURRENTTEXT"));

	for (walk = checklist; (walk); walk = walk->next) {
		int idx;
		char *data;
		checkdef_t *fwalk;

		switch (walk->checktype) {
		  case C_LOG:
			data = logdata(walk->filename, &walk->check.logcheck);
			fprintf(stdout, "[msgs:%s]\n", walk->filename);
			fprintf(stdout, "%s\n", data);

			if (walk->check.logcheck.deltacountcount) fprintf(stdout, "[deltacount:%s]\n", walk->filename);
			for (idx = 0; (idx < walk->check.logcheck.deltacountcount); idx++) {
				fprintf(stdout, "%s: %d\n", walk->check.logcheck.deltacountnames[idx], walk->check.logcheck.deltacountcounts[idx]);
			}

			/* See if there's a special "file:" entry for this logfile */
			for (fwalk = checklist; (fwalk && ((fwalk->checktype != C_FILE) || (strcmp(fwalk->filename, walk->filename) != 0))); fwalk = fwalk->next) ;
			if (fwalk == NULL) {
				/* No specific file: entry, so make sure the logfile metadata is available */
				fprintf(stdout, "[logfile:%s]\n", walk->filename);
				printfiledata(stdout, walk->filename, 0, 0, 0, 0, 0, 0, 0);
			}
			break;

		  case C_FILE:
			fprintf(stdout, "[file:%s]\n", walk->filename);
			printfiledata(stdout, walk->filename, 
					walk->check.filecheck.domd5, 
					walk->check.filecheck.dosha1,
					walk->check.filecheck.dosha256,
					walk->check.filecheck.dosha512,
					walk->check.filecheck.dosha224,
					walk->check.filecheck.dosha384,
					walk->check.filecheck.dormd160);
			break;

		  case C_DIR:
			fprintf(stdout, "[dir:%s]\n", walk->filename);
			printdirdata(stdout, walk->filename);
			break;

		  case C_COUNT:
			fprintf(stdout, "[linecount:%s]\n", walk->filename);
			printcountdata(stdout, walk);
			break;

		  case C_NONE:
			break;
		}
	}

	savelogstatus(statfn);

	return 0;
}