File: mlogc.c

package info (click to toggle)
modsecurity-apache 2.9.11-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 10,436 kB
  • sloc: ansic: 53,590; sh: 5,249; perl: 2,340; cpp: 1,930; makefile: 618; xml: 6
file content (2444 lines) | stat: -rw-r--r-- 78,079 bytes parent folder | download
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
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
/*
* ModSecurity for Apache 2.x, http://www.modsecurity.org/
* Copyright (c) 2004-2022 Trustwave Holdings, Inc. (http://www.trustwave.com/)
*
* You may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* If any of the files related to licensing are missing or if you have any
* other questions related to licensing please contact Trustwave Holdings, Inc.
* directly using the email address security@modsecurity.org.
*/

#include <apr.h>
#include <apr_errno.h>
#include <apr_general.h>
#include <apr_file_io.h>
#include <apr_file_info.h>
#include <apr_hash.h>
#include <apr_lib.h>
#include <apr_strings.h>
#include <apr_signal.h>
#include <apr_thread_proc.h>
#include <apr_global_mutex.h>
#include <apr_getopt.h>
#include <apr_version.h>
#if APR_HAVE_UNISTD_H
#include <unistd.h>         /* for getpid() */
#endif
#ifndef WITH_PCRE
#define PCRE2_CODE_UNIT_WIDTH 8
#include <pcre2.h>
#else
#include <pcre.h>
#endif
#include <curl/curl.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>

#include "msc_release.h"

static void logc_shutdown(int rc);
static void create_new_worker(int lock);
static void error_log(int level, void *thread,
                      const char *text, ...) PRINTF_ATTRIBUTE(3,4);


/* -- Constants -- */

/* Error log levels. */
#define LOG_ERROR           1
#define LOG_WARNING         2
#define LOG_NOTICE          3
#define LOG_DEBUG           4
#define LOG_DEBUG2          5

/* The management thread will wake up every five seconds. */
#define MANAGER_SLEEP       5000000
#define MANAGER_SUBSLEEP    10000

/* Hack to allow multiple mlogc with single delete */
#define KEEP_ENTRIES_REMOVE_HACK   2600
#define KEEP_ENTRIES_REMOVE_TIME   0l
#ifdef TEST_HACK
#define TEST_WITH_RAND_SLEEP(n) \
do { \
    int sec = rand()/(RAND_MAX/n); \
    error_log(LOG_DEBUG2, NULL, "TEST_HACK: Sleeping for %ds", sec); \
    apr_sleep(apr_time_from_sec(sec)); \
} while(0)
#else
#define TEST_WITH_RAND_SLEEP(n)
#endif

#define CAPTUREVECTORSIZE   60
#define PIPE_BUF_SIZE       65536
#define MEMALLOC_ERROR_MSG  "Memory allocation failed!"
#define VERSION             MODSEC_VERSION

#define CMDLINE_OPTS        "fvh"

#define TXIN            0
#define TXOUT           1

#define STATUSBUF_SIZE      256

#define ISHEXCHAR(X) (   ((X >= '0')&&(X <= '9')) \
                      || ((X >= 'a')&&(X <= 'f')) \
                      || ((X >= 'A')&&(X <= 'F')) )

/* -- Regex Patterns -- */

/**
 * This regular expression is used to parse the entire
 * log line we receive from Apache. The REQUEST_LINE is
 * treated as a single parameter to allow for invalid
 * requests.
 */
static const char logline_pattern[] =
    "^(\\S+)"
    "\\ (\\S+)\\ (\\S+)\\ (\\S+)"
    "\\ \\[([^:]+):(\\d+:\\d+:\\d+(?:[.]\\d+)?)\\ ([^\\]]+)\\]"
    "\\ \"(.*)\""
    "\\ (\\d+)\\ (\\S+)"
    "\\ \"(.*)\"\\ \"(.*)\""
    "\\ (\\S+)\\ \"(.*)\""
    "\\ /?(\\S+)\\ (\\d+)\\ (\\d+)"
    "\\ (\\S+)"
    "(.*)$";


/**
 * This regular expression can be used to parse
 * a REQUEST_LINE field into method, URI, and
 * protocol.
 */
static const char requestline_pattern[] =
    "(\\S+)\\ (.*?)\\ (\\S+)";


/* -- Structures -- */

typedef struct {
    unsigned long int        id;
    const char              *line;
    apr_size_t               line_size;
} entry_t;


/* -- Global variables -- */

static pid_t                  logc_pid = 0;
static const char            *conffile = NULL;
static const char            *lockfile = NULL;
static int                    have_read_data = 0;
static int                    checkpoint_interval = 60;
static apr_time_t             checkpoint_time_last = 0;
static const char            *collector_root = NULL;
static apr_table_t           *conf = NULL;
static const char            *console_uri = NULL;
static apr_array_header_t    *curl_handles = NULL;
static int                    current_workers = 0;
static int                    management_thread_active = 0;
static unsigned long int      entry_counter = 1;
static const char            *error_log_path = NULL;
static apr_file_t            *error_log_fd = NULL;
static int                    error_log_level = 2;
static apr_hash_t            *in_progress = NULL;
static int                    keep_alive = 150;           /* Not used yet. */
static int                    keep_alive_timeout = 300;   /* Not used yet. */
static int                    keep_entries = 0;
static const char            *log_repository = NULL;
#ifndef WITH_PCRE
static pcre2_code            *logline_regex = NULL;
static pcre2_code            *requestline_regex = NULL;
#else
static void                  *logline_regex = NULL;
static void                  *requestline_regex = NULL;
#endif
static int                    max_connections = 10;
static int                    max_worker_requests = 1000;
static apr_global_mutex_t    *gmutex = NULL;
static apr_thread_mutex_t    *mutex = NULL;
static apr_pool_t            *pool = NULL;
static apr_pool_t            *thread_pool = NULL;
static apr_pool_t            *recv_pool = NULL;
static apr_array_header_t    *queue = NULL;
static const char            *queue_path = NULL;
static int                    ssl_validation = 0;
static int                    tlsprotocol = 1;
static curl_version_info_data* curlversion = NULL;
/* static apr_time_t             queue_time = 0; */
static int                    running = 0;
static const char            *sensor_password = NULL;
static const char            *sensor_username = NULL;
static int                    server_error = 0;
static apr_time_t             server_error_last_check_time = 0;
static int                    server_error_timeout = 60;
static int                    startup_delay = 100;
static int                    transaction_delay = 100;
static const char            *transaction_log_path = NULL;
static apr_file_t            *transaction_log_fd = NULL;


/* -- Commandline opts -- */
static int                    opt_force = 0;

/* -- Code -- */

static char *_log_escape(apr_pool_t *mp, const char *input,
                         apr_size_t input_len)
{
    static const char c2x_table[] = "0123456789abcdef";
    unsigned char *d = NULL;
    char *ret = NULL;
    unsigned long int i;

    if (input == NULL) return NULL;

    ret = apr_palloc(mp, input_len * 4 + 1);
    if (ret == NULL) return NULL;
    d = (unsigned char *)ret;

    i = 0;
    while(i < input_len) {
        switch(input[i]) {
            case '"' :
                *d++ = '\\';
                *d++ = '"';
                break;
            case '\b' :
                *d++ = '\\';
                *d++ = 'b';
                break;
            case '\n' :
                *d++ = '\\';
                *d++ = 'n';
                break;
            case '\r' :
                *d++ = '\\';
                *d++ = 'r';
                break;
            case '\t' :
                *d++ = '\\';
                *d++ = 't';
                break;
            case '\v' :
                *d++ = '\\';
                *d++ = 'v';
                break;
            case '\\' :
                *d++ = '\\';
                *d++ = '\\';
                break;
            default :
                if ((input[i] <= 0x1f)||(input[i] >= 0x7f)) {
                    *d++ = '\\';
                    *d++ = 'x';
                    *d++ = c2x_table[input[i] >> 4];
                    *d++ = c2x_table[input[i] & 0x0f];
                } else {
                    *d++ = input[i];
                }
                break;
        }

        i++;
    }

    *d = 0;

    return ret;
}

/**
 * Converts a byte given as its hexadecimal representation
 * into a proper byte. Handles uppercase and lowercase letters
 * but does not check for overflows.
 */
static unsigned char x2c(unsigned char *what) {
    register unsigned char digit;

    digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A') + 10 : (what[0] - '0'));
    digit *= 16;
    digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A') + 10 : (what[1] - '0'));

    return digit;
}

/**
 * URL Decodes a string in-place
 */
static int urldecode_inplace(unsigned char *input, apr_size_t input_len) {
    unsigned char *d = (unsigned char *)input;
    apr_size_t i;

    if (input == NULL) return 0;

    i = 0;
    while (i < input_len) {
        if (input[i] == '%') {
            /* Character is a percent sign. */

            /* Are there enough bytes available? */
            if (i + 2 < input_len) {
                char c1 = input[i + 1];
                char c2 = input[i + 2];

                if (ISHEXCHAR(c1) && ISHEXCHAR(c2)) {
                    /* Valid encoding - decode it. */
                    *d++ = x2c(&input[i + 1]);
                    i += 3;
                } else {
                    /* Not a valid encoding, skip this % */
                    *d++ = input[i++];
                }
            } else {
                /* Not enough bytes available, copy the raw bytes. */
                *d++ = input[i++];
            }
        } else {
            /* Character is not a percent sign. */
            if (input[i] == '+') {
                *d++ = ' ';
            } else {
                *d++ = input[i];
            }
            i++;
        }
    }

    *d = '\0';

    return 1;
}

/**
 * Detect a relative path and merge it with the collector root
 * path. Leave absolute paths as they are.
 */
static const char *file_path(const char *path)
{
    char *newpath = NULL;
    apr_status_t rc;

    if (path == NULL) return NULL;

    rc = apr_filepath_merge(&newpath, collector_root,
                            path, APR_FILEPATH_TRUENAME, pool);
    if ((newpath != NULL) && (rc == APR_SUCCESS || APR_STATUS_IS_EPATHWILD(rc)
        || APR_STATUS_IS_ENOENT(rc) || APR_STATUS_IS_ENOTDIR(rc)))
    {
        return newpath;
    }
    else {
        return NULL;
    }
}


/**
 * Returns the current datetime as a string.
 */
static char *current_logtime(char *dest, int dlen)
{
    apr_time_exp_t t;
    apr_size_t len;

    apr_time_exp_lt(&t, apr_time_now());
    apr_strftime(dest, &len, dlen, "%a %b %d %H:%M:%S %Y", &t);

    return dest;
}


/**
 * Logs error to the error log (if available) or
 * to the stderr.
 */
static void error_log(int level, void *thread, const char *text, ...)
{
    char msg1[4096] = "";
    char msg2[4096] = "";
    char datetime[100];
    va_list ap;

    if (level > error_log_level) return;

    va_start(ap, text);

    apr_vsnprintf(msg1, sizeof(msg1), text, ap);
    apr_snprintf(msg2, sizeof(msg2), "[%s] [%d] [%" APR_PID_T_FMT "/%pp] %s\n",
                 current_logtime(datetime, sizeof(datetime)),
                 level, logc_pid, (thread ? thread : 0), msg1);

    if (error_log_fd != NULL) {
        apr_size_t nbytes_written;
        apr_size_t nbytes = strlen(msg2);
        apr_file_write_full(error_log_fd, msg2, nbytes, &nbytes_written);
    }
    else {
        fprintf(stderr, "%s", msg2);
    }

    va_end(ap);
}


/**
 * Adds one entry to the internal queue. It will (optionally) start
 * a new thread to handle it.
 */
static void add_entry(const char *data, int start_worker)
{
    entry_t *entry = NULL;

    entry = (entry_t *)malloc(sizeof(entry_t));
    entry->id = 0;
    entry->line = strdup(data);
    entry->line_size = strlen(entry->line);

    error_log(LOG_DEBUG, NULL, "Queue locking thread mutex.");
    if (APR_STATUS_IS_EBUSY(apr_thread_mutex_trylock(mutex))) {
        error_log(LOG_DEBUG, NULL, "Queue waiting on thread mutex.");
        apr_thread_mutex_lock(mutex);
    }

    /* Assign unique ID to this log entry. */
    entry->id = entry_counter++;

    /* Add the new audit log entry to the queue. */
    *(entry_t **)apr_array_push(queue) = entry;

    /* Create a new worker if we can, but not if there is a
     * known problem with the server.
     */
    if (   (start_worker != 0)
        && (current_workers < max_connections)&&(server_error == 0))
    {
        create_new_worker(0);
    }

    error_log(LOG_DEBUG, NULL, "Queue unlocking thread mutex.");
    apr_thread_mutex_unlock(mutex);
}


/**
 * Read the queue entries.
 */
static int read_queue_entries(apr_file_t *fd, apr_time_t *queue_time)
{
    char linebuf[4100];
    int line_count = -1;
    int line_size = 0;
    apr_status_t rc = 0;
    char *p = NULL;

    for(;;) {
        memset(linebuf, 0, 4100);
        rc = apr_file_gets(linebuf, 4096, fd);

        if (rc == APR_EOF) break;
        if (rc != APR_SUCCESS) {
            error_log(LOG_ERROR, NULL, "Error reading from the queue file.");
            logc_shutdown(1);
        }

        if (line_count < 0) {
            /* First line contains the queue time. */
            *queue_time = (apr_time_t)apr_atoi64(linebuf);
            line_count = 0;
            continue;
        }

        p = &linebuf[0];
        line_size = strlen(p);

        /* Remove the \n from the end of the line. */
        while(*p != '\0' && line_size > 0) {
            if (*p == '\n') {
                *p = '\0';
                break;
            }
            p++;
            line_size--;
        }

        if (linebuf[0] == '#') { /* Ignore comments. */
            continue;
        }

        add_entry((const char *)&linebuf, 0);

        line_count++;
    }

    apr_file_close(fd);

    return line_count;
}


/**
 * Initialise the transaction log. This code should be
 * executed only once at startup.
 */
static void transaction_log_init(void)
{
    /* ENH: These big enough? */
    char new_queue_path[256];
    char old_queue_path[256];
    apr_file_t *queue_fd = NULL;
    apr_time_t queue_time;

    apr_snprintf(new_queue_path, sizeof(new_queue_path), "%s.new", queue_path);
    apr_snprintf(old_queue_path, sizeof(old_queue_path), "%s.old", queue_path);

    /* Put a lock in place to ensure exclusivity. */
    error_log(LOG_DEBUG, NULL,
              "Transaction initialization locking global mutex.");
    if (APR_STATUS_IS_EBUSY(apr_global_mutex_trylock(gmutex))) {
        error_log(LOG_DEBUG, NULL,
                  "Transaction initialization waiting on global mutex.");
        apr_global_mutex_lock(gmutex);
    }

    error_log(LOG_DEBUG, NULL, "Transaction initialization started.");

    /* Delete .new file if there is one. */
    apr_file_remove(new_queue_path, pool);

    /* Read in the data from the queue. */
    if (apr_file_open(&queue_fd, queue_path, APR_READ | APR_FILE_NOCLEANUP,
        0, pool) == APR_SUCCESS)
    {
        int line_count = read_queue_entries(queue_fd, &queue_time);

        apr_file_close(queue_fd);

        if (line_count > 0) {
            error_log(LOG_NOTICE, NULL,
                      "Loaded %d entries from the queue file.", line_count);
        }
    }
    /* Try the old queue file. */
    else if (apr_file_open(&queue_fd, old_queue_path,
                           APR_READ | APR_FILE_NOCLEANUP,
                           0, pool) == APR_SUCCESS)
    {
        int line_count = read_queue_entries(queue_fd, &queue_time);
        apr_file_close(queue_fd);
        error_log(LOG_NOTICE, NULL,
                  "Loaded %d entries from the OLD queue file.", line_count);
        apr_file_rename(old_queue_path, queue_path, pool);
    }
    else {
        error_log(LOG_NOTICE, NULL,
                  "Queue file not found. New one will be created.");
    }

    /* Delete the old queue file. */
    apr_file_remove(old_queue_path, pool);

    checkpoint_time_last = apr_time_now();

    /* Start fresh with the transaction log. Do note that
     * we do not truncate the transaction log on purpose. Apache
     * will start copies of piped logging binaries during configuration
     * testing. Truncating would erase the log of a currently running
     * instance.
     */
    if (apr_file_open(&transaction_log_fd, transaction_log_path,
                      APR_WRITE | APR_CREATE | APR_APPEND | APR_XTHREAD,
                      APR_OS_DEFAULT, pool) != APR_SUCCESS)
    {
        error_log(LOG_ERROR, NULL,
                  "Failed to open the transaction log: %s\n",
                  transaction_log_path);
        error_log(LOG_DEBUG, NULL,
                  "Transaction initialization unlocking global mutex.");
        apr_global_mutex_unlock(gmutex);
        logc_shutdown(1);
    }

    error_log(LOG_DEBUG, NULL, "Transaction initialization completed.");

    /* Unlock */
    error_log(LOG_DEBUG, NULL,
              "Transaction initialization unlocking global mutex.");
    apr_global_mutex_unlock(gmutex);
}


/**
 * Log entry event (incoming or outgoing) to the transaction log.
 */
static void transaction_log(int direction, const char *entry)
{
    apr_size_t nbytes, nbytes_written;
    char msg[8196] = "";

    apr_snprintf(msg, sizeof(msg), "%u %s: %s\n",
                 (unsigned int)apr_time_sec(apr_time_now()),
        (direction == TXIN ? "IN" : "OUT"), entry);
    nbytes = strlen(msg);
    apr_file_write_full(transaction_log_fd, msg, nbytes, &nbytes_written);
}


/**
 * Executes a checkpoint, which causes the current queue to be
 * written to a file and the transaction log to be truncated.
 */
static void transaction_checkpoint(void)
{
    /* ENH: These big enough? */
    char new_queue_path[256];
    char old_queue_path[256];
    apr_file_t *queue_fd = NULL;
    apr_hash_index_t *hi = NULL;
    char msg[256];
    int i;
    apr_pool_t *cpool;

    apr_snprintf(new_queue_path, sizeof(new_queue_path), "%s.new", queue_path);
    apr_snprintf(old_queue_path, sizeof(old_queue_path), "%s.old", queue_path);
    apr_snprintf(msg, sizeof(msg), "%u\n",
                 (unsigned int)apr_time_sec(apr_time_now()));

    if (! have_read_data) {
        error_log(LOG_DEBUG, NULL, "Checkpoint not required.");
        return;
    }

    /* Put a lock in place to ensure exclusivity. */
    error_log(LOG_DEBUG, NULL, "Checkpoint locking global mutex.");
    if (APR_STATUS_IS_EBUSY(apr_global_mutex_trylock(gmutex))) {
        error_log(LOG_DEBUG, NULL, "Checkpoint waiting on global mutex.");
        apr_global_mutex_lock(gmutex);
    }

    error_log(LOG_DEBUG, NULL, "Checkpoint started.");

    apr_pool_create(&cpool, NULL);

    /* Dump active entries into a new queue file. */
    if (apr_file_open(&queue_fd, new_queue_path,
                      APR_WRITE | APR_CREATE | APR_EXCL |
                      APR_TRUNCATE | APR_FILE_NOCLEANUP,
                      APR_OS_DEFAULT, cpool) != APR_SUCCESS)
    {
        error_log(LOG_ERROR, NULL, "Failed to create file: %s", new_queue_path);
        error_log(LOG_DEBUG, NULL, "Checkpoint unlocking global mutex.");
        apr_pool_destroy(cpool);
        apr_global_mutex_unlock(gmutex);
        return;
    }

    /* Write the time first. */
    apr_file_write_full(queue_fd, msg, strlen(msg), NULL);

    /* Dump the entries sitting in the queue first. */
    for (i = 0; i < queue->nelts; i++) {
        entry_t *entry = ((entry_t **)queue->elts)[i];
        apr_file_write_full(queue_fd, entry->line, entry->line_size, NULL);
        apr_file_write_full(queue_fd, &"\n", 1, NULL);
    }
    error_log(LOG_DEBUG2, NULL,
              "Checkpoint wrote %d queued entries to new queue.", i);

    /* Then dump the ones that are currently being processed. */
    i = 0;
    for (hi = apr_hash_first(NULL, in_progress);
         hi != NULL; hi = apr_hash_next(hi))\
    {
        void *e;
        entry_t *entry = NULL;

        i++;
        apr_hash_this(hi, NULL, NULL, &e);
        entry = e; /* quiet type-punned warning */
        apr_file_write_full(queue_fd, entry->line, entry->line_size, NULL);
        apr_file_write_full(queue_fd, &"\n", 1, NULL);
    }
    error_log(LOG_DEBUG2, NULL,
              "Checkpoint wrote %d additional entries to new queue.", i);

    apr_file_close(queue_fd);

    /* Switch the files and truncate the transaction log file. */
    apr_file_remove(old_queue_path, cpool);
    apr_file_rename(queue_path, old_queue_path, cpool);
    apr_file_rename(new_queue_path, queue_path, cpool);
    apr_file_remove(old_queue_path, cpool);
    apr_file_trunc(transaction_log_fd, 0);

    error_log(LOG_DEBUG, NULL, "Checkpoint completed.");

    apr_pool_destroy(cpool);

    /* Unlock and exit. */
    error_log(LOG_DEBUG, NULL, "Checkpoint unlocking global mutex.");
    apr_global_mutex_unlock(gmutex);
}


/**
 * Parse one confguration line and add it to the
 * configuration table.
 */
static void parse_configuration_line(const char *line, int line_count)
{
    char *start = NULL, *command = NULL;
    char *p = NULL;

    /* Remove the trailing newline character. */
    p = (char *)line;
    while(*p != '\0') p++;
    if ((p > start)&&(*(p - 1) == '\n')) *(p - 1) = '\0';

    p = (char *)line;
    /* Ignore whitespace at the beginning of the line. */
    while(apr_isspace(*p)) p++;

    /* Ignore empty lines and comments. */
    if ((*p == '\0')||(*p == '#')) return;

    start = p;
    while(!apr_isspace(*p)&&(*p != '\0')) p++;

    command = apr_pstrmemdup(pool, start, p - start);

    while(apr_isspace(*p)) p++;

    /* Remove whitespace at the end. */
    start = p;
    while(*p != '\0') p++;
    if (p > start) {
        p--;
        while(apr_isspace(*p)) {
            *p-- = '\0';
        }
    }

    /* Remove quotes, but only if we have matching */
    if ((*start == '"') && (p > start) && (*p == '"')) {
        start++;
        *p-- = '\0';
    }

    /* Take the last directive */
    /* ENH: Error on dup directives? */
    apr_table_set(conf, command, start);
}


/**
 * Reads configuration from a file.
 */
static void read_configuration(void)
{
    char linebuf[4096];
    apr_status_t rc;
    apr_file_t *fd;
    int line_count;

    conf = apr_table_make(pool, 32);
    if (conf == NULL) {
        error_log(LOG_ERROR, NULL, MEMALLOC_ERROR_MSG);
        logc_shutdown(1);
    }

    rc = apr_file_open(&fd, conffile, APR_READ | APR_FILE_NOCLEANUP, 0, pool);
    if (rc != APR_SUCCESS) {
        error_log(LOG_ERROR, NULL,
                  "Unable to open configuration file: %s", conffile);
        logc_shutdown(1);
    }

    line_count = 0;
    for(;;) {
        rc = apr_file_gets(linebuf, 4096, fd);
        if (rc == APR_EOF) return;
        if (rc != APR_SUCCESS) {
            error_log(LOG_ERROR, NULL,
                      "Error reading from the configuration file.");
            logc_shutdown(1);
        }

        line_count++;
        parse_configuration_line(linebuf, line_count);
    }

    apr_file_close(fd);
}


/**
 * Initialize the configuration.
 */
static void init_configuration(void)
{
    char errstr[1024];
    apr_status_t rc = 0;
    const char *s = NULL;

    /* Other values may be based off the collector root. */
    s = apr_table_get(conf, "CollectorRoot");
    if (s != NULL) {
        collector_root = s;
    }

    /* Error Log */
    s = apr_table_get(conf, "ErrorLog");
    if (s != NULL) {
        error_log_path = file_path(s);
    }

    s = apr_table_get(conf, "ErrorLogLevel");
    if (s != NULL) {
        error_log_level = atoi(s);
    }

    if ((rc = apr_file_open(&error_log_fd, error_log_path,
                            APR_WRITE | APR_CREATE | APR_APPEND,
                            APR_OS_DEFAULT, pool)) != APR_SUCCESS)
    {
        error_log(LOG_ERROR, NULL, "Failed to open the error log %s: %s\n",
            error_log_path, apr_strerror(rc, errstr, 1024));
        logc_shutdown(1);
    }

    error_log(LOG_NOTICE, NULL,
              "Configuring ModSecurity Audit Log Collector %s.", VERSION);

    /* Startup Delay */
    s = apr_table_get(conf, "StartupDelay");
    if (s != NULL) {
        startup_delay = atoi(s);
    }

    /* TLS Protocol - TLSv1(0) TLSv1.1(1) TLSv1.2(2) (SSLv3 not supported) */
    s = apr_table_get(conf, "TLSProtocol");
    if (s != NULL) {
    	int num = atoi(s);
    	switch (num) {
    	case 0:
    		tlsprotocol = 0;
    		break;
    	case 1:
    		tlsprotocol = 1;
    		break;
    	case 2:
    		tlsprotocol = 2;
    		break;
    	default:
    		tlsprotocol = 2; /* Default is TLSv1.2 */
    	}
    }
    curlversion = curl_version_info(CURLVERSION_NOW);

    if ( startup_delay > 0 ) {
        error_log(LOG_NOTICE, NULL,
                  "Delaying execution for %dms.", startup_delay);
        apr_sleep(startup_delay * 1000);
        error_log(LOG_DEBUG, NULL,
                  "Continuing execution after %dms delay.", startup_delay);
    }

    /* Remaining Configuration */

    error_log(LOG_DEBUG2, NULL, "CollectorRoot=%s", collector_root);
    error_log(LOG_DEBUG2, NULL, "ErrorLog=%s", error_log_path);
    error_log(LOG_DEBUG2, NULL, "ErrorLogLevel=%d", error_log_level);
    error_log(LOG_DEBUG2, NULL, "StartupDelay=%d", startup_delay);
    error_log(LOG_DEBUG2, NULL, "TLSProtocol=%d", tlsprotocol);
    error_log(LOG_DEBUG2, NULL, "cURL version=%s",  curlversion->version);

    s = apr_table_get(conf, "CheckpointInterval");
    if (s != NULL) {
        checkpoint_interval = atoi(s);
        error_log(LOG_DEBUG2, NULL,
                  "CheckpointInterval=%d", checkpoint_interval);
    }

    s = apr_table_get(conf, "InsecureNoCheckCert");
    if (s != NULL) {
        int num = atoi(s);
        if (num)
        {
            ssl_validation = 0;
        }
        else
        {
            ssl_validation = 1;
        }
        error_log(LOG_DEBUG2, NULL, "InsecureNoCheckCert=%d", num);
    }

    s = apr_table_get(conf, "QueuePath");
    if (s != NULL) {
        queue_path = file_path(s);
        error_log(LOG_DEBUG2, NULL, "QueuePath=%s", queue_path);
    }
    else {
        error_log(LOG_ERROR, NULL,
                  "QueuePath not defined in the configuration file.");
        logc_shutdown(1);
    }

    s = apr_table_get(conf, "LockFile");
    if (s != NULL) {
        lockfile = file_path(s);
        error_log(LOG_DEBUG2, NULL, "LockFile=%s", lockfile);
    }

    s = apr_table_get(conf, "ServerErrorTimeout");
    if (s != NULL) {
        server_error_timeout = atoi(s);
        error_log(LOG_DEBUG2, NULL,
                  "ServerErrorTimeout=%d", server_error_timeout);
    }

    s = apr_table_get(conf, "TransactionDelay");
    if (s != NULL) {
        transaction_delay = atoi(s);
        error_log(LOG_DEBUG2, NULL, "TransactionDelay=%d", transaction_delay);
    }

    s = apr_table_get(conf, "TransactionLog");
    if (s != NULL) {
        transaction_log_path = file_path(s);
        error_log(LOG_DEBUG2, NULL, "TransactionLog=%s", transaction_log_path);
    }

    s = apr_table_get(conf, "MaxConnections");
    if (s != NULL) {
        int v = atoi(s);
        if (v >= 0) max_connections = v;
        error_log(LOG_DEBUG2, NULL, "MaxConnections=%d", max_connections);
    }

    s = apr_table_get(conf, "MaxWorkerRequests");
    if (s != NULL) {
        int v = atoi(s);
        if (v >= 0) max_worker_requests = v;
        error_log(LOG_DEBUG2, NULL,
                  "MaxWorkerRequests=%d", max_worker_requests);
    }

    s = apr_table_get(conf, "KeepAlive");
    if (s != NULL) {
        int v = atoi(s);
        if (v >= 0) keep_alive = v;
        error_log(LOG_DEBUG2, NULL, "KeepAlive=%d", keep_alive);
    }

    s = apr_table_get(conf, "KeepAliveTimeout");
    if (s != NULL) {
        int v = atoi(s);
        if (v >= 0) keep_alive_timeout = v;
        error_log(LOG_DEBUG2, NULL, "KeepAliveTimeout=%d", keep_alive_timeout);
    }

    s = apr_table_get(conf, "LogStorageDir");
    if (s != NULL) {
        log_repository = file_path(s);
        error_log(LOG_DEBUG2, NULL, "LogStorageDir=%s", log_repository);
    }
    else {
        error_log(LOG_ERROR, NULL,
                  "Missing mandatory parameter LogStorageDir.\n");
        logc_shutdown(1);
    }

    s = apr_table_get(conf, "ConsoleURI");
    if (s != NULL) {
        console_uri = s;
        error_log(LOG_DEBUG2, NULL, "ConsoleURI=%s", console_uri);
    }
    else {
        error_log(LOG_ERROR, NULL, "Missing mandatory parameter ConsoleURI.\n");
        logc_shutdown(1);
    }

    s = apr_table_get(conf, "SensorUsername");
    if (s != NULL) {
        sensor_username = s;
        error_log(LOG_DEBUG2, NULL, "SensorUsername=%s", sensor_username);
    }
    else {
        error_log(LOG_ERROR, NULL,
                  "Missing mandatory parameter SensorUsername.\n");
        logc_shutdown(1);
    }

    s = apr_table_get(conf, "SensorPassword");
    if (s != NULL) {
        sensor_password = s;
        error_log(LOG_DEBUG2, NULL, "SensorPassword=%s", sensor_password);
    }
    else {
        error_log(LOG_ERROR, NULL,
                  "Missing mandatory parameter SensorPassword.\n");
        logc_shutdown(1);
    }

    s = apr_table_get(conf, "KeepEntries");
    if (s != NULL) {
        keep_entries = atoi(s);
    }
    else {
        keep_entries = 0;
    }
    error_log(LOG_DEBUG2, NULL, "KeepEntries=%d", keep_entries);
}


/**
 * Clean-up resources before process shutdown.
 */
static void logc_cleanup(void)
{
    curl_global_cleanup();
}


/**
 * Shutdown the logger.
 */
static void logc_shutdown(int rc)
{
    /* Tell the threads to shut down. */
    running = 0;

    error_log(LOG_DEBUG, NULL, "Shutting down");

    /* Wait for the management thread to stop */
    /* ENH: Need a fixed timeout if this never happens */
    while(management_thread_active != 0) {
        apr_sleep(10 * 1000);
    }

    if (rc == 0) {
        error_log(LOG_NOTICE, NULL,
                  "ModSecurity Audit Log Collector %s terminating normally.",
                  VERSION);
    }
    else {
        error_log(LOG_NOTICE, NULL,
                  "ModSecurity Audit Log Collector %s "
                  "terminating with error %d", VERSION, rc);
    }

    if (error_log_fd != NULL) {
        apr_file_flush(error_log_fd);
    }

    exit(rc);
}


/**
 * Handle signals.
 */
static int handle_signals(int signum)
{
    switch (signum) {
        case SIGINT:
            error_log(LOG_NOTICE, NULL, "Caught SIGINT, shutting down.");
            logc_shutdown(0);
        case SIGTERM:
            error_log(LOG_NOTICE, NULL, "Caught SIGTERM, shutting down.");
            logc_shutdown(0);
#ifndef WIN32
        case SIGHUP:
            error_log(LOG_NOTICE, NULL, "Caught SIGHUP, ignored.");
            /* ENH: reload config? */
            return 0;
        case SIGALRM:
            error_log(LOG_DEBUG, NULL, "Caught SIGALRM, ignored.");
            return 0;
        case SIGTSTP:
            error_log(LOG_DEBUG, NULL, "Caught SIGTSTP, ignored.");
            return 0;
#endif /* WIN32 */
    }
#ifndef WIN32
    error_log(LOG_NOTICE, NULL,
              "Caught unexpected signal %d: %s",
              signum, apr_signal_description_get(signum));
#else
    error_log(LOG_NOTICE, NULL, "Caught unexpected signal %d", signum);
#endif /* WIN32 */
    logc_shutdown(1);

    return 0; /* should never reach */
}

#ifdef WIN32
/**
 * This function is invoked by Curl to read the source file on Windows
 */
static size_t curl_readfunction(void *ptr, size_t size,
                                 size_t nmemb, void *stream)
{
        return fread(ptr, size, nmemb, (FILE *)stream);
}
#endif

/**
 * This function is invoked by Curl to read the response
 * body. Since we don't care about the response body the function
 * pretends it is retrieving data where it isn't.
 */
static size_t curl_writefunction(void *ptr, size_t size,
                                 size_t nmemb, void *stream)
{
    unsigned char *data = (unsigned char *)ptr;
    unsigned char *status = (unsigned char *)stream;

    /* Grab the status line text from the first line of output */
    if ((status[0] == 0) && (status[1] == 1)) {
        apr_size_t i, j;
        int ismsg = 0;

        status[1] = 0; /* reset hidden init flag */

        for (i = 0, j = 0; i < STATUSBUF_SIZE; i++) {
            /* We found a line ending so we are done */
            if ( data[i] == '\r' ) {
                break;
            }
            /* Skip to after the first space (where msg is) */
            if (ismsg < 3) {
                if ((ismsg == 1) && !isspace(data[i])) {
                    ismsg++;
                }
                else if (isspace(data[i])) {
                    ismsg++;
                }
                continue;
            }

            /* Copy data (msg) from data to status */
            status[j++] = data[i];
        }
        status[j] = '\0';
        urldecode_inplace(status, j);
    }

    /* do nothing */
    return (size * nmemb);
}


/**
 * This function is invoked by Curl whenever it has something
 * to say. We forward its messages to the error log at level
 * DEBUG or DEBUG2 depending on the verbosity.
 */
static int curl_debugfunction(CURL *curl, curl_infotype infotype,
                              char *data, size_t datalen, void *ourdata)
{
    apr_size_t i, effectivelen;
    apr_thread_t *thread = (apr_thread_t *)ourdata;

    if (error_log_level < LOG_DEBUG) return 0;

    effectivelen = datalen;
    for(i = 0; i < datalen; i++) {
        if ((data[i] == 0x0a)||(data[i] == 0x0d)) {
            effectivelen = i;
            break;
        }
    }

    switch (infotype) {
        case CURLINFO_TEXT:
            /* More verbose data starts with an indent */
            if (apr_isspace(data[0])) {
                char *dataptr = data + 1;
                
                /* Skip initial whitespace (indent) */
                while (   ((size_t)(dataptr - data) > datalen)
                       && apr_isspace(*dataptr)) dataptr++;
                dataptr++;
                error_log(LOG_DEBUG2, thread, "CURL: %s",
                          _log_escape(apr_thread_pool_get(thread), dataptr,
                                      effectivelen - (dataptr - data)));
            }
            else {
                error_log(LOG_DEBUG, thread, "CURL: %s",
                          _log_escape(apr_thread_pool_get(thread), data,
                                      effectivelen));
            }
            break;
        case CURLINFO_HEADER_IN:
            error_log(LOG_DEBUG, thread, "CURL: HEADER_IN %s",
                      _log_escape(apr_thread_pool_get(thread), data,
                                  effectivelen));
            break;
        case CURLINFO_HEADER_OUT:
            error_log(LOG_DEBUG, thread, "CURL: HEADER_OUT %s",
                      _log_escape(apr_thread_pool_get(thread), data,
                                  effectivelen));
            break;
        case CURLINFO_DATA_IN:
            error_log(LOG_DEBUG2, thread, "CURL: DATA_IN %s",
                      _log_escape(apr_thread_pool_get(thread), data,
                                  effectivelen));
            break;
        case CURLINFO_DATA_OUT:
            error_log(LOG_DEBUG2, thread, "CURL: DATA_OUT %s",
                      _log_escape(apr_thread_pool_get(thread), data,
                                  effectivelen));
            break;
        default:
            /* Ignore anything else */
            break;
    }

    return 0;
}


/**
 * Initialise the necessary resources and structures.
 */
static void logc_init(void)
{
    char errstr[1024];
    apr_status_t rc = 0;
    const char *errptr = NULL;
    int i, erroffset;
    /* cURL major, minor and patch version */
    short cmaj, cmin, cpat = 0;
#ifndef WITH_PCRE
    int pcre2_errorcode = 0;
    PCRE2_SIZE pcre2_erroffset = 0;
#endif

    queue = apr_array_make(pool, 64, sizeof(entry_t *));
    if (queue == NULL) {
        error_log(LOG_ERROR, NULL, MEMALLOC_ERROR_MSG);
        logc_shutdown(1);
    }

    in_progress = apr_hash_make(pool);
    if (in_progress == NULL) {
        error_log(LOG_ERROR, NULL, MEMALLOC_ERROR_MSG);
        logc_shutdown(1);
    }

    if ((rc = apr_global_mutex_create(&gmutex, lockfile,
                                      APR_LOCK_DEFAULT, pool)) != APR_SUCCESS)
    {
        error_log(LOG_ERROR, NULL, "Failed to create global mutex: %s",
            apr_strerror(rc, errstr, 1024));
        logc_shutdown(1);
    }

    if ((rc = apr_thread_mutex_create(&mutex, APR_THREAD_MUTEX_UNNESTED,
                                      pool)) != APR_SUCCESS)
    {
        error_log(LOG_ERROR, NULL, "Failed to create thread mutex: %s",
            apr_strerror(rc, errstr, 1024));
        logc_shutdown(1);
    }

    entry_counter = 1;

    curl_handles = apr_array_make(pool, max_connections, sizeof(CURL *));
    if (curl_handles == NULL) {
        error_log(LOG_ERROR, NULL, MEMALLOC_ERROR_MSG);
        logc_shutdown(1);
    }

    /* Initialise a number of Curl handles. */
    for(i = 0; i < max_connections; i++) {
        CURL *curl = NULL;

        /* Create cURL handle. */
        curl = curl_easy_init();

        /* Pre-configure the handle. */
        curl_easy_setopt(curl, CURLOPT_UPLOAD, TRUE);
        curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, (char *)NULL);
        curl_easy_setopt(curl, CURLOPT_URL, console_uri);
        curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

        if (ssl_validation)
        {
            curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1);
            curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 1);
        }
        else
        {
            curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
        }


        /* Seems like CURL_SSLVERSION_TLSv1_2 is not supported on libcurl
         * < v7.34.0
         *
         * version_num is a 24 bit number created like this:
         * <8 bits major number> | <8 bits minor number> | <8 bits patch number>.
         */
        switch (tlsprotocol) {
        case 0:
        	curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_0);
        	break;
        case 1:
        	curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_1);
        	break;
        case 2:
        	curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
        	break;
        default:
        	curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
        	break;
        }
        cmaj = curlversion->version_num >> 16;
        cmin = (curlversion->version_num & 0x00ff00) >> 8;
        cpat = (curlversion->version_num & 0x0000ff);
        /* If cURL version < v7.34.0, use TLS v1.x */
        if (cmaj <= 7 && cmin < 34) {
        	curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
        }

        curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 15);
        curl_easy_setopt(curl, CURLOPT_NOSIGNAL, TRUE);
        curl_easy_setopt(curl, CURLOPT_HEADER, TRUE);

        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_writefunction);

        *(CURL **)apr_array_push(curl_handles) = curl;
    }

    if (cmaj <= 7 && cmin < 34) {
    	error_log(LOG_DEBUG2, NULL, "TLSv1.2 is unsupported in cURL %d.%d.%d",  cmaj, cmin, cpat);
    }

#ifndef WITH_PCRE
    logline_regex = pcre2_compile(logline_pattern, PCRE2_ZERO_TERMINATED, PCRE2_CASELESS,
                                 &pcre2_errorcode, &pcre2_erroffset, NULL);
#else
    logline_regex = pcre_compile(logline_pattern, PCRE_CASELESS,
                                 &errptr, &erroffset, NULL);
#endif
    if (logline_regex == NULL) {
        error_log(LOG_ERROR, NULL,
                  "Failed to compile pattern: %s\n", logline_pattern);
        logc_shutdown(1);
    }

#ifndef WITH_PCRE
    requestline_regex = pcre2_compile(requestline_pattern, PCRE2_ZERO_TERMINATED, PCRE2_CASELESS,
                                     &pcre2_errorcode, &pcre2_erroffset, NULL);
#else
    requestline_regex = pcre_compile(requestline_pattern, PCRE_CASELESS,
                                     &errptr, &erroffset, NULL);
#endif
    if (requestline_regex == NULL) {
        error_log(LOG_ERROR, NULL,
                  "Failed to compile pattern: %s\n", requestline_pattern);
        logc_shutdown(1);
    }
}


/**
 * HACK: To allow two mlogcs running against a single dataset we use the
 * mtime as a flag for deletion.
 *
 *  1) Check file date.
 *  2) If it is KEEP_ENTRIES_REMOVE_TIME, then remove the file.
 *  3) Otherwise set the date and let the other mlogc remove it.
 */
static void keep_entries_hack(apr_pool_t *mp,
                              apr_thread_t *thread, const char *fn)
{
    apr_file_t *f = NULL;
    apr_finfo_t finfo;
    char errstr[1024];
    apr_status_t rc;

    /* Opening for write as required for exclusive lock */
    if ((rc = apr_file_open(&f, fn,
                            APR_READ|APR_WRITE|APR_APPEND,
                            APR_OS_DEFAULT, mp)) != APR_SUCCESS)
    {
        error_log(LOG_ERROR, thread,
                  "Could not open \"%s\": %s",
                  fn, apr_strerror(rc, errstr, 1024));
        return;
    }

    if ((rc = apr_file_lock(f,
                  APR_FLOCK_EXCLUSIVE|APR_FLOCK_NONBLOCK)) != APR_SUCCESS)
    {
        error_log(LOG_DEBUG2, thread,
                  "Waiting for lock on \"%s\": %s",
                  fn, apr_strerror(rc, errstr, 1024));
        if ((rc = apr_file_lock(f, APR_FLOCK_EXCLUSIVE)) != APR_SUCCESS) {
            error_log(LOG_ERROR, thread,
                      "Could not lock \"%s\": %s",
                      fn, apr_strerror(rc, errstr, 1024));
            apr_file_close(f);
            return;
        }
    }
    error_log(LOG_DEBUG2, thread, "Locked: %s", fn);

    /* For testing only */
    TEST_WITH_RAND_SLEEP(2);

    if ((rc = apr_stat(&finfo, fn, APR_FINFO_MIN, mp)) != APR_SUCCESS) {
        error_log(LOG_ERROR, thread,
                  "Could not stat \"%s\": %s",
                  fn, apr_strerror(rc, errstr, 1024));
        error_log(LOG_DEBUG2, thread, "Unlocked: %s", fn);
        apr_file_close(f);
        return;
    }

    if (error_log_level >= LOG_DEBUG) {
        error_log(LOG_DEBUG, thread,
                  "STAT \"%s\" {"
                  "uid=%d; gid=%d; size=%" APR_OFF_T_FMT "; "
                  "csize=%" APR_OFF_T_FMT "; atime=%" APR_TIME_T_FMT "; "
                  "ctime=%" APR_TIME_T_FMT "; mtime=%" APR_TIME_T_FMT
                  "}",
                  fn, finfo.user, finfo.group, finfo.size,
                  finfo.csize, finfo.atime, finfo.ctime, finfo.mtime);
    }

    if (finfo.mtime != KEEP_ENTRIES_REMOVE_TIME) {
        error_log(LOG_DEBUG2, thread, "Set mtime: %s", fn);
        if ((rc = apr_file_mtime_set(fn,
                        (apr_time_t)KEEP_ENTRIES_REMOVE_TIME, mp))
                  != APR_SUCCESS)
        {
            error_log(LOG_ERROR, thread,
                      "Could not set mtime on \"%s\": %s",
                      fn, apr_strerror(rc, errstr, 1024));
        }
        error_log(LOG_DEBUG2, thread, "Unlocked: %s", fn);
        apr_file_close(f);
        return;
    }


    error_log(LOG_DEBUG, thread, "Removing: %s", fn);
    error_log(LOG_DEBUG2, thread, "Unlocked: %s", fn);
    apr_file_close(f);
    apr_file_remove(fn, mp);
}


/**
 * Worker thread. Works in a loop, fetching jobs from the queue,
 * until the queue is empty or it is otherwise told to quit.
 */
static void * APR_THREAD_FUNC thread_worker(apr_thread_t *thread, void *data)
{
    unsigned int loop_count = 0;
    CURL *curl = (CURL *)data;
    entry_t **entryptr = NULL;
    entry_t *entry = NULL;
    apr_status_t rc;
    apr_finfo_t finfo;
    int capturevector[CAPTUREVECTORSIZE];
#ifndef WITH_PCRE
    pcre2_match_data *pcre2_match_data = NULL;
#endif
    int take_new = 1;
    apr_pool_t *tpool;
    struct curl_slist *headerlist = NULL;
    char curl_error_buffer[CURL_ERROR_SIZE] = "";
    int num_requests = 0;

    /* There is no need to do the sleep if this was an invalid entry
     * as the sleep is just to protect flooding the console server
     * with rapid requests.  With an invalid entry we never hit the
     * server, so we should not delay processing the next event.
     */
    int nodelay = 0;


    error_log(LOG_DEBUG, thread, "Worker thread starting.");

    /* Each worker uses its own pool to manage memory. To avoid
     * memory leaks the pool is cleared after each processed
     * entry.
     */
    apr_pool_create(&tpool, thread_pool);

    /* Process jobs in a queue until there are no more jobs to process. */
    for(;;) {
        nodelay = 0;

        /* Do we need to shut down? */
        if (running == 0) {
            error_log(LOG_DEBUG, thread, "We were told to shut down.");
            goto THREAD_SHUTDOWN;
        }

        /* Is there a problem with the server? We need
         * to shut down if there is. Except that we don't
         * want to shut down if we were launched to investigate
         * if the server came back online (loop_count will be
         * zero in that case).
         */
        if ((server_error == 1)&&(loop_count != 0)) {
            error_log(LOG_DEBUG, thread, "Shutting down due to server error.");
            goto THREAD_SHUTDOWN;
        }

        loop_count++;

        /* Get a new entry, but only if we need one. */
        if (take_new) {
            error_log(LOG_DEBUG, thread, "Worker fetch locking thread mutex.");
            if (APR_STATUS_IS_EBUSY(apr_thread_mutex_trylock(mutex))) {
                error_log(LOG_DEBUG, thread,
                          "Worker fetch waiting on thread mutex.");
                apr_thread_mutex_lock(mutex);
            }

            error_log(LOG_DEBUG, thread, "Worker fetch started.");

            /* Deal with the previous entry. */
            if (entry != NULL) {
                error_log(LOG_DEBUG, thread,
                          "Removing previous entry from storage.");
                transaction_log(TXOUT, entry->line);

                /* Remove previous entry from storage. */
                apr_hash_set(in_progress, &entry->id, sizeof(entry->id), NULL);

                /* Release the memory it used to occupy. */
                free((void *)entry->line);
                free(entry);
                entry = NULL;
            }

            error_log(LOG_DEBUG, thread, "Getting one entry from the queue.");

            /* Get one entry. */
            entryptr = (entry_t **)apr_array_pop(queue);
            if (entryptr == NULL) {
                error_log(LOG_DEBUG, thread,
                          "Worker fetch unlocking thread mutex.");
                apr_thread_mutex_unlock(mutex);
                error_log(LOG_DEBUG, thread,
                          "No more work for this thread, exiting.");

                goto THREAD_SHUTDOWN;
            }

            entry = *entryptr;
            apr_hash_set(in_progress, &entry->id, sizeof(entry->id), entry);

            error_log(LOG_DEBUG, thread, "Worker fetch completed.");

            error_log(LOG_DEBUG, thread,
                      "Worker fetch unlocking thread mutex.");
            apr_thread_mutex_unlock(mutex);
        }

        /* Send one entry. */

        error_log(LOG_DEBUG, thread, "Processing entry.");
        take_new = 0;

        /* Keep track of requests processed if we need to */
        if (max_worker_requests > 0) {
            num_requests++;
        }

#ifndef WITH_PCRE
        pcre2_match_data  = pcre2_match_data_create_from_pattern(logline_regex, NULL);
        rc = pcre2_match(logline_regex, entry->line, entry->line_size, 0, 0,
            pcre2_match_data, NULL);
	if (rc > 0) {
            PCRE2_SIZE *pcre2_ovector = pcre2_get_ovector_pointer(pcre2_match_data);
            for (int i = 0; i < rc; i++) {
                capturevector[2*i] = pcre2_ovector[2*i];
                capturevector[2*i+1] = pcre2_ovector[2*i+1];
            }
        }
        pcre2_match_data_free(pcre2_match_data);
        if (rc == PCRE2_ERROR_NOMATCH) {
#else
        rc = pcre_exec(logline_regex, NULL, entry->line, entry->line_size, 0, 0,
            capturevector, CAPTUREVECTORSIZE);
        if (rc == PCRE_ERROR_NOMATCH) {
#endif
            error_log(LOG_WARNING, thread,
                      "Invalid entry (failed to match regex): %s",
                      _log_escape(tpool, entry->line, entry->line_size));
            take_new = 1;
            nodelay = 1;
        }
        else if (rc < 0) { /* Error condition. */
            error_log(LOG_WARNING, thread,
                      "Invalid entry (PCRE error %d): %s",
                      rc, _log_escape(tpool, entry->line, entry->line_size));
            take_new = 1;
            nodelay = 1;
        }
        else { /* We have a match. */
            char *uniqueid = NULL;
            char *auditlogentry = NULL;
            char *hash = NULL;
            char *summary = NULL;
            char *credentials = NULL;

            error_log(LOG_DEBUG, thread, "Regular expression matched.");

            /* For testing only */
            TEST_WITH_RAND_SLEEP(2);

            uniqueid = apr_psprintf(tpool, "%.*s",
                (capturevector[2*13+1] - capturevector[2*13]),
                (entry->line + capturevector[2*13]));
            auditlogentry = apr_psprintf(tpool, "%s/%.*s", log_repository,
                (capturevector[2*15+1] - capturevector[2*15]),
                (entry->line + capturevector[2*15]));
            hash = apr_psprintf(tpool, "X-Content-Hash: %.*s",
                (capturevector[2*18+1] - capturevector[2*15]),
                (entry->line + capturevector[2*18]));
            summary = apr_psprintf(tpool, "X-ForensicLog-Summary: %s",
                    entry->line);
            credentials = apr_psprintf(tpool, "%s:%s",
                                       sensor_username, sensor_password);

            rc = apr_stat(&finfo, auditlogentry, APR_FINFO_SIZE, tpool);
            if (rc == APR_SUCCESS) {
                FILE *hd_src;
                char response_buf[STATUSBUF_SIZE];
                CURLcode res;

                if (error_log_level >= LOG_DEBUG) {
                    error_log(LOG_DEBUG, thread,
                              "STAT \"%s\" {"
                              "uid=%d; gid=%d; size=%" APR_OFF_T_FMT "; "
                              "csize=%" APR_OFF_T_FMT "; "
                              "atime=%" APR_TIME_T_FMT "; "
                              "ctime=%" APR_TIME_T_FMT "; "
                              "mtime=%" APR_TIME_T_FMT
                              "}",
                              auditlogentry, finfo.user, finfo.group,
                              finfo.size, finfo.csize, finfo.atime,
                              finfo.ctime, finfo.mtime);
                }

                /* Initialize the respone buffer with a hidden value */
                response_buf[0] = 0;
                response_buf[1] = 1;

                if (finfo.size == 0) {
                    error_log(LOG_WARNING, thread,
                              "File found (%" APR_OFF_T_FMT
                              " bytes), skipping.", finfo.size);
                    take_new = 1;
                    nodelay = 1;
                    goto THREAD_CLEANUP;
                }
                else {
                    error_log(LOG_DEBUG, thread,
                              "File found (%" APR_OFF_T_FMT
                              " bytes), activating cURL.", finfo.size);
                }


                curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
                curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
                                 curl_debugfunction);
                curl_easy_setopt(curl, CURLOPT_DEBUGDATA, thread);
                curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_error_buffer);
                curl_easy_setopt(curl, CURLOPT_USERPWD, credentials);
                curl_easy_setopt(curl, CURLOPT_WRITEDATA, (char *)response_buf);

                headerlist = curl_slist_append(headerlist, "Expect:");
                headerlist = curl_slist_append(headerlist, hash);
                headerlist = curl_slist_append(headerlist, summary);
                curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);

                hd_src = fopen(auditlogentry, "rb");
                if (hd_src == NULL) {
                    error_log(LOG_WARNING, thread,
                              "Invalid entry (failed to open file for "
                              "reading): %s", auditlogentry);
                    take_new = 1;
                    nodelay = 1;
                    goto THREAD_CLEANUP;
                }

                curl_easy_setopt(curl, CURLOPT_READDATA, hd_src);
                curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, finfo.size);

#ifdef WIN32
                /* Mandatory on win32 */
                curl_easy_setopt(curl, CURLOPT_READFUNCTION, curl_readfunction);
#endif

                res = curl_easy_perform(curl);

                fclose(hd_src);

                if (res == 0) {
                    long response_code = 0;

                    res = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE,
                                            &response_code);
                    error_log(LOG_DEBUG, thread,
                              "Request returned with status \"%ld %s\": %s",
                              response_code, response_buf, uniqueid);


                    if (response_code == 0) {
                        /* Assume problem with connection */
                        error_log(LOG_WARNING, thread,
                                  "Flagging server as errored after failure "
                                  "to retrieve response code for entry %s "
                                  "(cURL code %d): Possible SSL negotiation "
                                  "error",
                                  uniqueid, res);
                        apr_sleep(1000 * 1000);
                        take_new = 0;
                        server_error = 1;
                        server_error_last_check_time = apr_time_now();
                    }
                    else if (res != 0) {
                        error_log(LOG_WARNING, thread,
                                  "Flagging server as errored after failure "
                                  "to retrieve response code for entry %s "
                                  "(cURL code %d): %s",
                                  uniqueid, res, curl_error_buffer);
                        apr_sleep(1000 * 1000);
                        take_new = 0;
                        server_error = 1;
                        server_error_last_check_time = apr_time_now();
                    }
                    else {
                        if (response_code == 200) {
                            double total_time, upload_size;

                            if (server_error == 1) {
                                error_log(LOG_NOTICE, thread,
                                          "Clearing the server error flag "
                                          "after successful entry "
                                          "submission: %s", uniqueid);
                            }
                            server_error = 0;
                            server_error_last_check_time = 0;

                            curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME,
                                              &total_time);
                            curl_easy_getinfo(curl, CURLINFO_SIZE_UPLOAD,
                                              &upload_size);

                            if (!keep_entries) {
                                error_log(LOG_DEBUG, thread,
                                          "Removing: %s", auditlogentry);
                                apr_file_remove(auditlogentry, tpool);
                            }
                            else if (keep_entries == KEEP_ENTRIES_REMOVE_HACK)
                            {
                                keep_entries_hack(tpool, thread, auditlogentry);
                            }

                            error_log(LOG_NOTICE, thread,
                                      "Entry completed (%.3f seconds, %.0f "
                                      "bytes): %s",
                                      total_time, upload_size,
                                      uniqueid);
                            take_new = 1;
                        }
                        else if (response_code == 409) {
                            /* Assume problem with audit log entry. */
                            error_log(LOG_WARNING, thread,
                                      "Failed to submit entry with "
                                      "\"409 %s\": %s",
                                      response_buf, uniqueid);
                            take_new = 1;
                        }
                        else {
                            /* Assume problem with server. */
                            error_log(LOG_WARNING, thread,
                                      "Flagging server as errored after "
                                      "failure to submit entry %s with "
                                      "HTTP response code %ld: %s",
                                      uniqueid, response_code, response_buf);
                            server_error = 1;
                            server_error_last_check_time = apr_time_now();
                            take_new = 0;
                        }
                    }
                }
                else { /* Something isn't right. */
                    error_log(LOG_WARNING, thread,
                              "Flagging server as errored after "
                              "failure to submit entry %s "
                              "(cURL code %d): %s",
                              uniqueid, res, curl_error_buffer);
                    server_error = 1;
                    server_error_last_check_time = apr_time_now();
                    take_new = 0;

                }
            }
            else {
                error_log(LOG_WARNING, thread,
                          "Invalid entry (file not found %d): %s",
                          rc, auditlogentry);
                take_new = 1;
                nodelay = 1;
            }

            /* If we are tracking num_requests, then shutdown if we are
             * over our threshold.
             */
            if (num_requests && (num_requests >= max_worker_requests)) {
                error_log(LOG_NOTICE, thread,
                          "Reached max requests (%d) for this worker, exiting.",
                          max_worker_requests);

                goto THREAD_SHUTDOWN;
            }
        }

        THREAD_CLEANUP:

        /* Sleep if we sent data to the server so we do not flood */
        /* ENH: Need to sleep for 1ms in a loop checking for shutdown */
        if ((nodelay == 0) && (transaction_delay > 0)) {
            error_log(LOG_DEBUG, thread,
                      "Sleeping for %d msec.", transaction_delay);
            apr_sleep(transaction_delay * 1000);
        }

        if (headerlist != NULL) {
            curl_slist_free_all(headerlist);
            headerlist = NULL;
        }

        apr_pool_clear(tpool);

        error_log(LOG_DEBUG, thread, "Worker processing completed.");
    }

    THREAD_SHUTDOWN:

    error_log(LOG_DEBUG, thread, "Worker shutdown locking thread mutex.");
    if (APR_STATUS_IS_EBUSY(apr_thread_mutex_trylock(mutex))) {
        error_log(LOG_DEBUG, thread,
                  "Worker shutdown waiting on thread mutex.");
        apr_thread_mutex_lock(mutex);
    }

    /* Deal with the previous entry, if any. */
    if (entry != NULL) {
        apr_hash_set(in_progress, &entry->id, sizeof(entry->id), NULL);

        if (take_new == 0) { /* Not done. */
            *(entry_t **)apr_array_push(queue) = entry;
        }
        else {
            transaction_log(TXOUT, entry->line);
            free((void *)entry->line);
            free(entry);
        }

        entry = NULL;
    }

    /* Return curl handle to the pool for reuse. */
    *(CURL **)apr_array_push(curl_handles) = curl;

    /* No more work, exit. */
    current_workers--;

    error_log(LOG_DEBUG, thread, "Worker shutdown unlocking thread mutex.");
    apr_thread_mutex_unlock(mutex);

    apr_pool_destroy(tpool);

    error_log(LOG_DEBUG, thread, "Worker thread completed.");

    apr_thread_exit(thread, 0);

    return NULL;
}


/**
 * Creates one new worker, giving it one of the available
 * Curl handles to work with.
 */
static void create_new_worker(int lock)
{
    apr_thread_t *thread = NULL;
    CURL **curlptr = NULL;

    if (lock) {
        error_log(LOG_DEBUG, NULL, "Worker creation locking thread mutex.");
        if (APR_STATUS_IS_EBUSY(apr_thread_mutex_trylock(mutex))) {
            error_log(LOG_DEBUG, NULL,
                      "Worker creation waiting on thread mutex.");
            apr_thread_mutex_lock(mutex);
        }
    }

    error_log(LOG_DEBUG, NULL, "Worker creation started.");

    /* A sanity check: this part executes under lock and
     * we want to make *sure* we don't create more threads
     * than we are allowed.
     */
    if (current_workers >= max_connections) {
        if (lock) {
            error_log(LOG_DEBUG, NULL,
                      "Worker creation unlocking thread mutex.");
            apr_thread_mutex_unlock(mutex);
        }
        return;
    }

    /* Cleanup thread pool when idle */
    if (current_workers <= 0)  {
        if (thread_pool != NULL) {
            error_log(LOG_DEBUG, NULL, "Destroying thread_pool.");
            apr_pool_destroy(thread_pool);
            thread_pool = NULL;
        }
        error_log(LOG_DEBUG, NULL, "Creating thread_pool.");
        apr_pool_create(&thread_pool, NULL);
    }

    curlptr = (CURL **)apr_array_pop(curl_handles);
    if (curlptr != NULL) {
        apr_threadattr_t *thread_attrs;
        apr_status_t rc;

        apr_threadattr_create(&thread_attrs, thread_pool);
        apr_threadattr_detach_set(thread_attrs, 1);
        apr_threadattr_stacksize_set(thread_attrs, 1024);

        rc = apr_thread_create(&thread, thread_attrs,
                               thread_worker, *curlptr, thread_pool);
        if (rc != APR_SUCCESS) {
            if (lock) {
                error_log(LOG_DEBUG, NULL,
                          "Worker creation unlocking thread mutex.");
                apr_thread_mutex_unlock(mutex);
            }
            error_log(LOG_ERROR, NULL,
                      "Failed to create new worker thread: %d", rc);
            logc_shutdown(1);
        }

        current_workers++;
    }
    else {
        if (lock) {
            error_log(LOG_DEBUG, NULL,
                      "Worker creation unlocking thread mutex.");
            apr_thread_mutex_unlock(mutex);
        }
        error_log(LOG_ERROR, NULL, "No more cURL handles (Internal Error).");
        logc_shutdown(1);
    }

    error_log(LOG_DEBUG, NULL, "Worker creation completed: %pp", thread);

    if (lock) {
        error_log(LOG_DEBUG, NULL, "Worker creation unlocking thread mutex.");
        apr_thread_mutex_unlock(mutex);
    }
}


/**
 * This function implements the management thread.
 */
static void * APR_THREAD_FUNC thread_manager(apr_thread_t *thread, void *data)
{
    apr_time_t last = 0;
    apr_time_t now = 0;

    error_log(LOG_DEBUG, thread, "Management thread: Starting.");

    for(;;) {
        now = apr_time_now();

        /* Should we stop running? */
        if (running == 0) {
            /* We need to be last */
            error_log(LOG_DEBUG, thread,
                      "Management thread: Waiting for worker "
                      "threads to finish.");
            while(current_workers > 0) {
                apr_sleep(10 * 1000);
            }

            if (have_read_data) {
                error_log(LOG_NOTICE, thread,
                          "Running final transaction checkpoint.");
                transaction_checkpoint();
            }

            error_log(LOG_DEBUG, thread, "Management thread: Exiting.");
            management_thread_active = 0;
            apr_thread_exit(thread, 0);
        }

        /* Sleep for a while, but wake up often to check running status */
        if ((last > 0) && ((now - last) < MANAGER_SLEEP)) {
            apr_sleep(MANAGER_SUBSLEEP);
            continue;
        }
        last = now;

        error_log(LOG_DEBUG2, thread, "Management thread: Processing");

        /* When the server is flagged errored we need to
         * create a worker thread from time to time to
         * investigate.
         */
        if (server_error) {
            if ((current_workers == 0)&&
                (apr_time_sec(now - server_error_last_check_time)
                    > server_error_timeout))
            {
                server_error_last_check_time = now;
                error_log(LOG_DEBUG, thread,
                          "Management thread: Creating worker thread to "
                          "investigate server.");
                create_new_worker(1);
            }
        }
        else {
            if (   (current_workers < max_connections)
                && (queue->nelts > current_workers) )
            {
                error_log(LOG_DEBUG, thread,
                          "Management thread: Creating worker thread to "
                          "catch up with the queue.");
                create_new_worker(1);
            }
        }

        /* Initiate a transaction log checkpoint if enough time passed
         * since the last one.
         */
        if (apr_time_sec(now - checkpoint_time_last) > checkpoint_interval) {
            error_log(LOG_DEBUG, thread,
                      "Management thread: Initiating a checkpoint "
                      "(previous was %" APR_TIME_T_FMT " seconds ago).",
                      apr_time_sec(now - checkpoint_time_last));
            checkpoint_time_last = now;
            transaction_checkpoint();
        }
        else {
            error_log(LOG_DEBUG2, thread,
                      "Management thread: Last checkpoint was %" APR_TIME_T_FMT
                      " seconds ago.",
                      apr_time_sec(now - checkpoint_time_last));
        }
    }

    return NULL;
}

#ifndef WIN32
/**
 * Thread to handle all signals
 */
static void * APR_THREAD_FUNC thread_signals(apr_thread_t *thread, void *data)
{
    apr_status_t rc;

    error_log(LOG_DEBUG, thread, "Signal thread: Starting.");
    rc = apr_signal_thread(handle_signals);
    if (rc != APR_SUCCESS) {
        error_log(LOG_DEBUG, thread, "Signal thread: Error %d", rc);
        logc_shutdown(1);
    }

    return NULL;
}
#endif /* WIN32 */

/**
 * The main loop where we receive log entries from
 * Apache and add them to the queue, sometimes creating
 * new worker threads to handle them.
 */
static void receive_loop(void) {
    apr_file_t *fd_stdin;
    apr_size_t nbytes = PIPE_BUF_SIZE;
    char *buf = apr_palloc(pool, PIPE_BUF_SIZE + 1);
    char errstr[1024];
    apr_size_t evnt = 0; /* Index in buf to first event char */
    apr_size_t curr = 0; /* Index in buf to current processing char */
    apr_size_t next = 0; /* Index in buf to next unused char */
    int done = 0;
    int drop_next = 0;
    int buffered_events = 0;
    int count = 0;
    apr_pool_t *tmp_pool;

    /* Open stdin. */
    if (apr_file_open_stdin(&fd_stdin, pool) != APR_SUCCESS) {
        error_log(LOG_ERROR, NULL, "Unable to open stdin for reading");
        logc_shutdown(1);
    }

    /* Always want this NUL terminated */
    buf[PIPE_BUF_SIZE] = '\0';

    apr_pool_create(&tmp_pool, NULL);

    /* Loop forever receiving entries from stdin. */
    while(!done || (curr < next)) {
        apr_status_t rc;

        if (error_log_level >= LOG_DEBUG2) {
            error_log(LOG_DEBUG2, NULL,
                      "Internal state: "
                      "[evnt \"%" APR_SIZE_T_FMT "\"]"
                      "[curr \"%" APR_SIZE_T_FMT "\"]"
                      "[next \"%" APR_SIZE_T_FMT "\"]"
                      "[nbytes \"%" APR_SIZE_T_FMT "\"]",
                      evnt, curr, next, nbytes);
        }

        /* If we are not done and have the space, read more */
        if (!done && (nbytes > 0)) {
            buffered_events = 0;
            nbytes = PIPE_BUF_SIZE - next;
            rc = apr_file_read(fd_stdin, (buf + next), &nbytes);
            if (rc != APR_SUCCESS) {
                if (have_read_data) {
                    error_log(LOG_NOTICE, NULL,
                              "No more data to read, emptying buffer: %s",
                              apr_strerror(rc, errstr, 1024));
                }
                done = 1;
            }
            else {
                have_read_data = 1;
                if (error_log_level == LOG_DEBUG) {
                    error_log(LOG_DEBUG, NULL,
                              "Read %" APR_SIZE_T_FMT " bytes from pipe",
                              nbytes);
                }
                else {
                    error_log(LOG_DEBUG2, NULL,
                              "Read %" APR_SIZE_T_FMT " bytes from pipe: `%s'",
                              nbytes,
                              _log_escape(tmp_pool, (buf + next), nbytes));
                }
            }

            next += nbytes;
        }

        /**
         * Each chunk of data we receive can contain one or more lines for
         * which we need to find the EOL marker and then queue the event
         * up to that.  So, find/queue as many lines in the buffer as we
         * can.  Any remaining data will get shifted back to the beginning
         * of the buffer and the buffer size for the next read adjusted.
         */
        while(curr < next) {
            /* Look for EOL so we can parse the event */
            while((curr < next) && (buf[curr] != 0x0a)) {
                curr++;
            }
            if (buf[curr] == 0x0a) {
                buf[curr] = '\0';

                /* We may have to drop this one if it previously failed */
                if (drop_next) {
                    error_log(LOG_ERROR, NULL,
                              "Dropping remaining portion of failed "
                              "event: `%s'",
                              _log_escape(tmp_pool,
                                          (buf + evnt), (curr - evnt)));
                    drop_next = 0;
                }
                else {
                    transaction_log(TXIN, buf + evnt);
                    error_log(LOG_DEBUG2, NULL,
                              "Received audit log entry "
                              "(count %lu queue %d workers %d): %s",
                              entry_counter, queue->nelts,
                              current_workers,
                              _log_escape(tmp_pool,
                                          (buf + evnt), strlen(buf + evnt)));
                    add_entry(buf + evnt, 1);
                    buffered_events++;
                }

                /* Advance indexes to next event in buf */
                evnt = curr = curr + 1;
            }
            else {
                error_log(LOG_DEBUG2, NULL,
                          "Event buffer contains partial event: `%s'",
                          _log_escape(tmp_pool, (buf + evnt), (next - evnt)));
                break;
            }
        }


        if (buffered_events > 0) {
            error_log(LOG_DEBUG, NULL,
                      "Processed %d entries from buffer.", buffered_events);

            /* Move the unused portion of the buffer to the beginning */
            next -= evnt;
            curr -= evnt;
            memmove(buf, (buf + evnt), next);

            error_log(LOG_DEBUG2, NULL,
                      "Shifted buffer back %" APR_SIZE_T_FMT 
                      " and offset %" APR_SIZE_T_FMT 
                      " bytes for next read: `%s'",
                      evnt, next, _log_escape(tmp_pool, buf, next));

            evnt = 0;
        }
        else if (next == PIPE_BUF_SIZE) {
            /**
             * There is a chance we could fill the buffer, but not have finished
             * reading the event (no EOL yet), so we need to say so and drop
             * all data until we find the end of the event that is too large.
             */

            if (drop_next) {
                error_log(LOG_ERROR, NULL,
                          "Event continuation too large, "
                          "dropping it as well: `%s'",
                          _log_escape(tmp_pool, buf, PIPE_BUF_SIZE));
            }
            else {
                error_log(LOG_ERROR, NULL,
                          "Event too large, dropping event: `%s'",
                          _log_escape(tmp_pool, buf, PIPE_BUF_SIZE));
            }

            /* Rewind buf and mark that we need to drop up to the next event */
            evnt = curr = next = 0;
            drop_next = 1;
        }

        nbytes = PIPE_BUF_SIZE - next;

        if (count++ > 1000) {
            count = 0;
            error_log(LOG_DEBUG, NULL, "Recycling tmp_pool.");
            apr_pool_destroy(tmp_pool);
            apr_pool_create(&tmp_pool, NULL);
        }
        else {
            apr_pool_clear(tmp_pool);
        }
    }

    /* Wait for queue to empty if specified */
    if ((server_error == 0) && (opt_force != 0) && (queue->nelts > 0)) {
        error_log(LOG_NOTICE, NULL,
                  "Waiting for queue to empty (%d active).", queue->nelts);
        while ((server_error == 0) && (opt_force != 0) && (queue->nelts > 0)) {
            apr_sleep(10 * 1000);
        }
        if (queue->nelts > 0) {
            error_log(LOG_ERROR, NULL,
                      "Could not empty queue (%d active).", queue->nelts);
        }
    }
}


/**
 * Creates the management thread.
 */
static void start_management_thread(void)
{
    apr_thread_t *thread = NULL;
    apr_threadattr_t *thread_attrs;
    apr_status_t rc;

    apr_threadattr_create(&thread_attrs, pool);
    apr_threadattr_detach_set(thread_attrs, 1);
    apr_threadattr_stacksize_set(thread_attrs, 1024);

    management_thread_active = 1;

    rc = apr_thread_create(&thread, thread_attrs, thread_manager, NULL, pool);
    if (rc != APR_SUCCESS) {
        error_log(LOG_ERROR, NULL,
                  "Failed to create new management thread: %d", rc);
        management_thread_active = 0;
        logc_shutdown(1);
    }
}
#ifndef WIN32
/**
 * Creates a thread to handle all signals
 */
static void start_signal_thread(void)
{
    apr_thread_t *thread = NULL;
    apr_threadattr_t *thread_attrs;
    apr_status_t rc;

    apr_threadattr_create(&thread_attrs, pool);
    apr_threadattr_detach_set(thread_attrs, 1);
    apr_threadattr_stacksize_set(thread_attrs, 1024);

    rc = apr_thread_create(&thread, thread_attrs, thread_signals, NULL, pool);
    if (rc != APR_SUCCESS) {
        error_log(LOG_ERROR, NULL,
                  "Failed to create new signal thread: %d", rc);
        logc_shutdown(1);
    }
}
#endif /* WIN32 */

/**
 * Usage text.
 */
static void usage(void) {
    fprintf(stderr, "ModSecurity Log Collector (mlogc) v%s\n", VERSION);
    fprintf(stderr, "  Usage: mlogc [options] /path/to/the/mlogc.conf\n");
    fprintf(stderr, "\n");
    fprintf(stderr, "  Options:\n");
    fprintf(stderr, "    -f        Force depletion of queue on exit\n");
    fprintf(stderr, "    -v        Version information\n");
    fprintf(stderr, "    -h        This help\n\n");
}

/**
 * Version text.
 */
static void version(void) {
#ifndef WITH_PCRE
    char pcre2_loaded_version_buffer[80] ={0};
    char *pcre_loaded_version = pcre2_loaded_version_buffer;
    pcre2_config(PCRE2_CONFIG_VERSION, pcre_loaded_version);
#endif
    fprintf(stderr,
            "ModSecurity Log Collector (mlogc) v%s\n", VERSION);
    fprintf(stderr,
            "   APR: compiled=\"%s\"; "
            "loaded=\"%s\"\n", APR_VERSION_STRING, apr_version_string());
    fprintf(stderr,
            "  PCRE: compiled=\"%d.%d\"; "
#ifndef WITH_PCRE
            "loaded=\"%s\"\n", PCRE2_MAJOR, PCRE2_MINOR, pcre_loaded_version);
#else
            "loaded=\"%s\"\n", PCRE_MAJOR, PCRE_MINOR, pcre_version());
#endif
    fprintf(stderr,
            "  cURL: compiled=\"%s\"; "
            "loaded=\"%s\"\n", LIBCURL_VERSION, curl_version());
    fprintf(stderr, "\n");
}

/**
 * This is the main entry point.
 */
int main(int argc, const char * const argv[]) {
    apr_getopt_t *opt;
    apr_status_t rc;

    apr_app_initialize(&argc, &argv, NULL);
    atexit(apr_terminate);

    curl_global_init(CURL_GLOBAL_ALL);
    atexit(logc_cleanup);

    logc_pid = getpid();
    apr_pool_create(&pool, NULL);
    apr_pool_create(&recv_pool, NULL);
	
#ifndef WIN32
    apr_setup_signal_thread();
#else
	apr_signal(SIGINT, handle_signals);
	apr_signal(SIGTERM, handle_signals);
#endif /* WIN32 */

    if (argc < 2) {
        usage();
        logc_shutdown(1);
    }

    /* Commandline opts */
    rc = apr_getopt_init(&opt, pool, argc, argv);
    if (rc != APR_SUCCESS) {
        usage();
        logc_shutdown(1);
    }

    do {
        char  ch;
        const char *val;
        rc = apr_getopt(opt, CMDLINE_OPTS, &ch, &val);
        switch (rc) {
            case APR_SUCCESS:
                switch (ch) {
                    case 'f':
                        opt_force = 1;
                        break;
                    case 'v':
                        version();
                        logc_shutdown(0);
                    case 'h':
                        usage();
                        logc_shutdown(0);
                }
                break;
            case APR_BADCH:
            case APR_BADARG:
                usage();
                logc_shutdown(1);
        }
    } while (rc != APR_EOF);

    /* Conf file is last */
    conffile = argv[argc - 1];

    read_configuration();
    init_configuration();

    logc_init();
    transaction_log_init();

    running = 1;
    server_error = 0;

    start_management_thread();
#ifndef WIN32
    start_signal_thread();
#endif /* WIN32 */

    /* Process stdin until EOF */
    receive_loop();

    logc_shutdown(0);

    return 0;
}