aboutsummaryrefslogtreecommitdiff
path: root/liberty.c
blob: 035d23d005584c782a2f3d297bb62006bef3a0e7 (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
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
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
/*
 * liberty.c: the ultimate C unlibrary
 *
 * Copyright (c) 2014 - 2016, Přemysl Janouch <p.janouch@gmail.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#define _POSIX_C_SOURCE 199309L
#define _XOPEN_SOURCE 600

#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdbool.h>
#include <inttypes.h>
#include <ctype.h>
#include <time.h>
#include <limits.h>
#include <setjmp.h>

#include <unistd.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <strings.h>
#include <regex.h>
#include <libgen.h>
#include <syslog.h>
#include <fnmatch.h>
#include <iconv.h>
#include <pwd.h>
#include <pthread.h>

#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>

#ifdef __unix__
// This file may define the "BSD" macro...
#include <sys/param.h>
// ...as well as these conflicting ones
#undef MIN
#undef MAX
#endif // __unix__

#ifndef NI_MAXHOST
#define NI_MAXHOST 1025
#endif // ! NI_MAXHOST

#ifndef NI_MAXSERV
#define NI_MAXSERV 32
#endif // ! NI_MAXSERV

#ifdef LIBERTY_WANT_SSL
#include <openssl/sha.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#endif // LIBERTY_WANT_SSL

#include <getopt.h>
#include "siphash.c"

extern char **environ;

#ifdef CLOCK_MONOTONIC_RAW
// This should be more accurate for shorter intervals
#define CLOCK_BEST CLOCK_MONOTONIC_RAW
#elif defined _POSIX_MONOTONIC_CLOCK
#define CLOCK_BEST CLOCK_MONOTONIC
#else // ! _POSIX_MONOTIC_CLOCK
#define CLOCK_BEST CLOCK_REALTIME
#endif // ! _POSIX_MONOTONIC_CLOCK

#if defined __GNUC__
#define ATTRIBUTE_PRINTF(x, y) __attribute__ ((format (printf, x, y)))
#else // ! __GNUC__
#define ATTRIBUTE_PRINTF(x, y)
#endif // ! __GNUC__

#if defined __GNUC__ && __GNUC__ >= 4
#define ATTRIBUTE_SENTINEL __attribute__ ((sentinel))
#else // ! __GNUC__ || __GNUC__ < 4
#define ATTRIBUTE_SENTINEL
#endif // ! __GNUC__ || __GNUC__ < 4

#define N_ELEMENTS(a) (sizeof (a) / sizeof ((a)[0]))

#define BLOCK_START  do {
#define BLOCK_END    } while (0)

#define MIN(a, b)  ((a) < (b) ? (a) : (b))
#define MAX(a, b)  ((a) > (b) ? (a) : (b))

#define STRINGIFY(x) #x
#define XSTRINGIFY(x) STRINGIFY (x)

#define CONTAINER_OF(pointer, type, member) \
	((type *) ((char *) pointer - offsetof (type, member)))

// --- Logging -----------------------------------------------------------------

static void
log_message_stdio (void *user_data, const char *quote, const char *fmt,
	va_list ap)
{
	(void) user_data;
	FILE *stream = stderr;

	fputs (quote, stream);
	vfprintf (stream, fmt, ap);
	fputs ("\n", stream);
}

static void (*g_log_message_real) (void *, const char *, const char *, va_list)
	= log_message_stdio;

static void
log_message (void *user_data, const char *quote, const char *fmt, ...)
	ATTRIBUTE_PRINTF (3, 4);

static void
log_message (void *user_data, const char *quote, const char *fmt, ...)
{
	va_list ap;
	va_start (ap, fmt);
	g_log_message_real (user_data, quote, fmt, ap);
	va_end (ap);
}

// `fatal' is reserved for unexpected failures that would harm further operation

#ifndef print_fatal_data
#define print_fatal_data    NULL
#endif

#ifndef print_error_data
#define print_error_data    NULL
#endif

#ifndef print_warning_data
#define print_warning_data  NULL
#endif

#ifndef print_status_data
#define print_status_data   NULL
#endif

#define print_fatal(...) \
	log_message (print_fatal_data,   "fatal: ",   __VA_ARGS__)
#define print_error(...) \
	log_message (print_error_data,   "error: ",   __VA_ARGS__)
#define print_warning(...) \
	log_message (print_warning_data, "warning: ", __VA_ARGS__)
#define print_status(...) \
	log_message (print_status_data,  "-- ",       __VA_ARGS__)

#define exit_fatal(...)                                                        \
	BLOCK_START                                                                \
		print_fatal (__VA_ARGS__);                                             \
		exit (EXIT_FAILURE);                                                   \
	BLOCK_END

// --- Debugging and assertions ------------------------------------------------

// We should check everything that may possibly fail with at least a soft
// assertion, so that any causes for problems don't slip us by silently.
//
// `g_soft_asserts_are_deadly' may be useful while running inside a debugger.

static bool g_debug_mode;               ///< Debug messages are printed
static bool g_soft_asserts_are_deadly;  ///< soft_assert() aborts as well

#ifndef print_debug_data
#define print_debug_data   NULL
#endif

#define print_debug(...)                                                       \
	BLOCK_START                                                                \
		if (g_debug_mode)                                                      \
			log_message (print_debug_data, "debug: ", __VA_ARGS__);            \
	BLOCK_END

// A few other debugging shorthands for when failures are allowed
#define LOG_FUNC_FAILURE(name, desc)                                           \
	print_debug ("%s: %s: %s", __func__, (name), (desc))
#define LOG_LIBC_FAILURE(name)                                                 \
	print_debug ("%s: %s: %s", __func__, (name), strerror (errno))

static void
assertion_failure_handler (bool is_fatal, const char *file, int line,
	const char *function, const char *condition)
{
	const char *slash = strrchr (file, '/');
	if (slash)
		file = slash + 1;
	if (is_fatal)
	{
		print_fatal ("assertion failed [%s:%d in function %s]: %s",
			file, line, function, condition);
		abort ();
	}
	else
		print_debug ("assertion failed [%s:%d in function %s]: %s",
			file, line, function, condition);
}

#define soft_assert(condition)                                                 \
	((condition) ? true :                                                      \
		(assertion_failure_handler (g_soft_asserts_are_deadly,                 \
		__FILE__, __LINE__, __func__, #condition), false))

#define hard_assert(condition)                                                 \
	((condition) ? (void) 0 :                                                  \
		assertion_failure_handler (true,                                       \
		__FILE__, __LINE__, __func__, #condition))

// --- Safe memory management --------------------------------------------------

// When a memory allocation fails and we need the memory, we're usually pretty
// much fucked.  Use the non-prefixed versions when there's a legitimate
// worry that an unrealistic amount of memory may be requested for allocation.

// XXX: it's not a good idea to use print_message() as it may want to allocate
//   further memory for printf() and the output streams.  That may fail.

static void *
xmalloc (size_t n)
{
	void *p = malloc (n);
	if (!p)
		exit_fatal ("malloc: %s", strerror (errno));
	return p;
}

static void *
xcalloc (size_t n, size_t m)
{
	void *p = calloc (n, m);
	if (!p && n && m)
		exit_fatal ("calloc: %s", strerror (errno));
	return p;
}

static void *
xrealloc (void *o, size_t n)
{
	void *p = realloc (o, n);
	if (!p && n)
		exit_fatal ("realloc: %s", strerror (errno));
	return p;
}

static void *
xreallocarray (void *o, size_t n, size_t m)
{
	if (m && n > SIZE_MAX / m)
	{
		errno = ENOMEM;
		exit_fatal ("reallocarray: %s", strerror (errno));
	}
	return xrealloc (o, n * m);
}

static char *
xstrdup (const char *s)
{
	return strcpy (xmalloc (strlen (s) + 1), s);
}

static char *
xstrndup (const char *s, size_t n)
{
	size_t size = strlen (s);
	if (n > size)
		n = size;

	char *copy = xmalloc (n + 1);
	memcpy (copy, s, n);
	copy[n] = '\0';
	return copy;
}

// --- Simple array support ----------------------------------------------------

// The most basic helper macros to make working with arrays not suck

#define ARRAY(type, name) type *name; size_t name ## _len, name ## _alloc;
#define ARRAY_INIT_SIZED(a, n)                                                 \
	BLOCK_START                                                                \
		(a) = xcalloc (sizeof *(a), (a ## _alloc) = (n));                      \
		(a ## _len) = 0;                                                       \
	BLOCK_END
#define ARRAY_INIT(a) ARRAY_INIT_SIZED (a, 16)
#define ARRAY_RESERVE(a, n)                                                    \
	BLOCK_START                                                                \
		while ((a ## _alloc) - (a ## _len) < n)                                \
			(a) = xreallocarray ((a), sizeof *(a), (a ## _alloc) <<= 1);       \
	BLOCK_END

// --- Double-linked list helpers ----------------------------------------------

#define LIST_HEADER(type)                                                      \
	type *next;                                                                \
	type *prev;

#define LIST_PREPEND(head, link)                                               \
	BLOCK_START                                                                \
		(link)->prev = NULL;                                                   \
		(link)->next = (head);                                                 \
		if ((link)->next)                                                      \
			(link)->next->prev = (link);                                       \
		(head) = (link);                                                       \
	BLOCK_END

#define LIST_UNLINK(head, link)                                                \
	BLOCK_START                                                                \
		if ((link)->prev)                                                      \
			(link)->prev->next = (link)->next;                                 \
		else                                                                   \
			(head) = (link)->next;                                             \
		if ((link)->next)                                                      \
			(link)->next->prev = (link)->prev;                                 \
	BLOCK_END

#define LIST_APPEND_WITH_TAIL(head, tail, link)                                \
	BLOCK_START                                                                \
		(link)->prev = (tail);                                                 \
		(link)->next = NULL;                                                   \
		if ((link)->prev)                                                      \
			(link)->prev->next = (link);                                       \
		else                                                                   \
			(head) = (link);                                                   \
		(tail) = (link);                                                       \
	BLOCK_END

#define LIST_INSERT_WITH_TAIL(head, tail, link, following)                     \
	BLOCK_START                                                                \
		if (following)                                                         \
			LIST_APPEND_WITH_TAIL ((head), (following)->prev, (link));         \
		else                                                                   \
			LIST_APPEND_WITH_TAIL ((head), (tail), (link));                    \
		(link)->next = (following);                                            \
	BLOCK_END

#define LIST_UNLINK_WITH_TAIL(head, tail, link)                                \
	BLOCK_START                                                                \
		if ((tail) == (link))                                                  \
			(tail) = (link)->prev;                                             \
		LIST_UNLINK ((head), (link));                                          \
	BLOCK_END

#define LIST_FOR_EACH(type, iter, list)                                        \
	for (type *iter = (list), *next;                                           \
		(iter && (next = iter->next)) || iter;                                 \
		iter = next)

// --- Dynamically allocated string array --------------------------------------

struct strv
{
	char **vector;
	size_t len;
	size_t alloc;
};

static void
strv_init (struct strv *self)
{
	self->alloc = 4;
	self->len = 0;
	self->vector = xcalloc (sizeof *self->vector, self->alloc);
}

static void
strv_free (struct strv *self)
{
	unsigned i;
	for (i = 0; i < self->len; i++)
		free (self->vector[i]);

	free (self->vector);
	self->vector = NULL;
}

static void
strv_reset (struct strv *self)
{
	strv_free (self);
	strv_init (self);
}

static void
strv_append_owned (struct strv *self, char *s)
{
	self->vector[self->len] = s;
	if (++self->len >= self->alloc)
		self->vector = xreallocarray (self->vector,
			sizeof *self->vector, (self->alloc <<= 1));
	self->vector[self->len] = NULL;
}

static void
strv_append (struct strv *self, const char *s)
{
	strv_append_owned (self, xstrdup (s));
}

static void
strv_append_args (struct strv *self, const char *s, ...)
	ATTRIBUTE_SENTINEL;

static void
strv_append_args (struct strv *self, const char *s, ...)
{
	va_list ap;

	va_start (ap, s);
	while (s)
	{
		strv_append (self, s);
		s = va_arg (ap, const char *);
	}
	va_end (ap);
}

static void
strv_append_vector (struct strv *self, char **vector)
{
	while (*vector)
		strv_append (self, *vector++);
}

static char *
strv_steal (struct strv *self, size_t i)
{
	hard_assert (i < self->len);
	char *tmp = self->vector[i];
	memmove (self->vector + i, self->vector + i + 1,
		(self->len-- - i) * sizeof *self->vector);
	return tmp;
}

static void
strv_remove (struct strv *self, size_t i)
{
	free (strv_steal (self, i));
}

// --- Dynamically allocated strings -------------------------------------------

// Basically a string builder to abstract away manual memory management.

struct str
{
	char *str;                          ///< String data, null terminated
	size_t alloc;                       ///< How many bytes are allocated
	size_t len;                         ///< How long the string actually is
};

/// We don't care about allocations that are way too large for the content, as
/// long as the allocation is below the given threshold.  (Trivial heuristics.)
#define STR_SHRINK_THRESHOLD (1 << 20)

static void
str_init (struct str *self)
{
	self->alloc = 16;
	self->len = 0;
	self->str = strcpy (xmalloc (self->alloc), "");
}

static void
str_free (struct str *self)
{
	free (self->str);
	self->str = NULL;
	self->alloc = 0;
	self->len = 0;
}

static void
str_reset (struct str *self)
{
	str_free (self);
	str_init (self);
}

static char *
str_steal (struct str *self)
{
	char *str = self->str;
	self->str = NULL;
	str_free (self);
	return str;
}

static void
str_reserve (struct str *self, size_t n)
{
	// We allocate at least one more byte for the terminating null character
	size_t new_alloc = self->alloc;
	while (new_alloc <= self->len + n)
		new_alloc <<= 1;
	if (new_alloc != self->alloc)
		self->str = xrealloc (self->str, (self->alloc = new_alloc));
}

static void
str_append_data (struct str *self, const void *data, size_t n)
{
	str_reserve (self, n);
	memcpy (self->str + self->len, data, n);
	self->len += n;
	self->str[self->len] = '\0';
}

static void
str_append_c (struct str *self, char c)
{
	str_append_data (self, &c, 1);
}

static void
str_append (struct str *self, const char *s)
{
	str_append_data (self, s, strlen (s));
}

static void
str_append_str (struct str *self, const struct str *another)
{
	str_append_data (self, another->str, another->len);
}

static int
str_append_vprintf (struct str *self, const char *fmt, va_list va)
{
	va_list ap;
	int size;

	va_copy (ap, va);
	size = vsnprintf (NULL, 0, fmt, ap);
	va_end (ap);

	if (size < 0)
		return -1;

	va_copy (ap, va);
	str_reserve (self, size);
	size = vsnprintf (self->str + self->len, self->alloc - self->len, fmt, ap);
	va_end (ap);

	if (size > 0)
		self->len += size;

	return size;
}

static int
str_append_printf (struct str *self, const char *fmt, ...)
	ATTRIBUTE_PRINTF (2, 3);

static int
str_append_printf (struct str *self, const char *fmt, ...)
{
	va_list ap;

	va_start (ap, fmt);
	int size = str_append_vprintf (self, fmt, ap);
	va_end (ap);
	return size;
}

static void
str_remove_slice (struct str *self, size_t start, size_t length)
{
	size_t end = start + length;
	hard_assert (end <= self->len);
	memmove (self->str + start, self->str + end, self->len - end);
	self->str[self->len -= length] = '\0';

	// Shrink the string if the allocation becomes way too large
	if (self->alloc >= STR_SHRINK_THRESHOLD && self->len < (self->alloc >> 2))
		self->str = xrealloc (self->str, self->alloc >>= 2);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
str_pack_u8 (struct str *self, uint8_t x)
{
	str_append_data (self, &x, 1);
}

static void
str_pack_u16 (struct str *self, uint16_t x)
{
	uint8_t tmp[2] = { x >> 8, x };
	str_append_data (self, tmp, sizeof tmp);
}

static void
str_pack_u32 (struct str *self, uint32_t x)
{
	uint32_t u = x;
	uint8_t tmp[4] = { u >> 24, u >> 16, u >> 8, u };
	str_append_data (self, tmp, sizeof tmp);
}

static void
str_pack_u64 (struct str *self, uint64_t x)
{
	uint8_t tmp[8] =
		{ x >> 56, x >> 48, x >> 40, x >> 32, x >> 24, x >> 16, x >> 8, x };
	str_append_data (self, tmp, sizeof tmp);
}

#define str_pack_i8(self, x)   str_pack_u8  ((self), (uint8_t)  (x))
#define str_pack_i16(self, x)  str_pack_u16 ((self), (uint16_t) (x))
#define str_pack_i32(self, x)  str_pack_u32 ((self), (uint32_t) (x))
#define str_pack_i64(self, x)  str_pack_u64 ((self), (uint64_t) (x))

// --- Errors ------------------------------------------------------------------

// Error reporting utilities.  Inspired by GError, only much simpler.

struct error
{
	char *message;                      ///< Textual description of the event
};

static bool
error_set (struct error **e, const char *message, ...) ATTRIBUTE_PRINTF (2, 3);

static bool
error_set (struct error **e, const char *message, ...)
{
	if (!e)
		return false;

	va_list ap;
	va_start (ap, message);
	int size = vsnprintf (NULL, 0, message, ap);
	va_end (ap);

	hard_assert (size >= 0);

	struct error *tmp = xmalloc (sizeof *tmp);
	tmp->message = xmalloc (size + 1);

	va_start (ap, message);
	size = vsnprintf (tmp->message, size + 1, message, ap);
	va_end (ap);

	hard_assert (size >= 0);

	soft_assert (*e == NULL);
	*e = tmp;
	return false;
}

static void
error_free (struct error *e)
{
	free (e->message);
	free (e);
}

static void
error_propagate (struct error **destination, struct error *source)
{
	if (!destination)
	{
		error_free (source);
		return;
	}

	soft_assert (*destination == NULL);
	*destination = source;
}

// --- File descriptor utilities -----------------------------------------------

static void
set_cloexec (int fd)
{
	soft_assert (fcntl (fd, F_SETFD, fcntl (fd, F_GETFD) | FD_CLOEXEC) != -1);
}

static bool
set_blocking (int fd, bool blocking)
{
	int flags = fcntl (fd, F_GETFL);
	if (flags == -1)
		exit_fatal ("%s: %s", "fcntl", strerror (errno));

	bool prev = !(flags & O_NONBLOCK);
	if (blocking)
		flags &= ~O_NONBLOCK;
	else
		flags |=  O_NONBLOCK;

	hard_assert (fcntl (fd, F_SETFL, flags) != -1);
	return prev;
}

static void
xclose (int fd)
{
	while (close (fd) == -1)
		if (!soft_assert (errno == EINTR))
			break;
}

// --- Randomness --------------------------------------------------------------

static bool
random_bytes (void *output, size_t len, struct error **e)
{
	bool result = false;
	int fd = open ("/dev/urandom", O_RDONLY);
	ssize_t got = 0;

	if (fd < 0)
		return error_set (e, "%s: %s", "open", strerror (errno));
	else if ((got = read (fd, output, len)) < 0)
		error_set (e, "%s: %s", "read", strerror (errno));
	else if (got != (ssize_t) len)
		error_set (e, "can't get enough bytes from the device");
	else
		result = true;

	xclose (fd);
	return result;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static unsigned char g_siphash_key[16] = "SipHash 2-4 key!";

static inline void
siphash_wrapper_randomize (void)
{
	// I guess there's no real need to be this paranoic, so we ignore failures
	soft_assert (random_bytes (g_siphash_key, sizeof g_siphash_key, NULL));
}

static inline uint64_t
siphash_wrapper (const void *m, size_t len)
{
	return siphash (g_siphash_key, m, len);
}

// --- String hash map ---------------------------------------------------------

// The most basic <string, managed pointer> map (or associative array).

struct str_map_link
{
	LIST_HEADER (struct str_map_link)

	void *data;                         ///< Payload
	size_t key_length;                  ///< Length of the key without '\0'
	char key[];                         ///< The key for this link
};

struct str_map
{
	struct str_map_link **map;          ///< The hash table data itself
	size_t alloc;                       ///< Number of allocated entries
	size_t len;                         ///< Number of entries in the table
	void (*free) (void *);              ///< Callback to destruct the payload

	/// Callback that transforms all key values for storage and comparison;
	/// has to behave exactly like strxfrm().
	size_t (*key_xfrm) (char *dest, const char *src, size_t n);

	bool shrink_lock;                   ///< Lock against autoshrinking
};

#define STR_MAP_MIN_ALLOC 16

typedef void (*str_map_free_fn) (void *);

static void
str_map_init (struct str_map *self)
{
	self->alloc = STR_MAP_MIN_ALLOC;
	self->len = 0;
	self->free = NULL;
	self->key_xfrm = NULL;
	self->map = xcalloc (self->alloc, sizeof *self->map);
	self->shrink_lock = false;
}

static void
str_map_clear (struct str_map *self)
{
	struct str_map_link **iter, **end = self->map + self->alloc;
	struct str_map_link *link, *tmp;

	for (iter = self->map; iter < end; iter++)
		for (link = *iter; link; link = tmp)
		{
			tmp = link->next;
			if (self->free)
				self->free (link->data);
			free (link);
		}

	self->len = 0;
	memset (self->map, 0, self->alloc * sizeof *self->map);
}

static void
str_map_free (struct str_map *self)
{
	str_map_clear (self);
	free (self->map);
	self->map = NULL;
}

static uint64_t
str_map_pos (const struct str_map *self, const char *s)
{
	size_t mask = self->alloc - 1;
	return siphash_wrapper (s, strlen (s)) & mask;
}

static uint64_t
str_map_link_hash (const struct str_map_link *self)
{
	return siphash_wrapper (self->key, self->key_length);
}

static void
str_map_resize (struct str_map *self, size_t new_size)
{
	struct str_map_link **old_map = self->map;
	size_t i, old_size = self->alloc;

	// Only powers of two, so that we don't need to compute the modulo
	hard_assert ((new_size & (new_size - 1)) == 0);
	size_t mask = new_size - 1;

	self->alloc = new_size;
	self->map = xcalloc (self->alloc, sizeof *self->map);
	for (i = 0; i < old_size; i++)
	{
		struct str_map_link *iter = old_map[i], *next_iter;
		while (iter)
		{
			next_iter = iter->next;
			uint64_t pos = str_map_link_hash (iter) & mask;
			LIST_PREPEND (self->map[pos], iter);
			iter = next_iter;
		}
	}

	free (old_map);
}

static void
str_map_shrink (struct str_map *self)
{
	if (self->shrink_lock)
		return;

	// The array should be at least 1/4 full
	size_t new_alloc = self->alloc;
	while (self->len < (new_alloc >> 2)
		&& new_alloc >= (STR_MAP_MIN_ALLOC << 1))
		new_alloc >>= 1;
	if (new_alloc != self->alloc)
		str_map_resize (self, new_alloc);
}

static void
str_map_set_real (struct str_map *self, const char *key, void *value)
{
	uint64_t pos = str_map_pos (self, key);
	struct str_map_link *iter = self->map[pos];
	for (; iter; iter = iter->next)
	{
		if (strcmp (key, iter->key))
			continue;

		// Storing the same data doesn't destroy it
		if (self->free && value != iter->data)
			self->free (iter->data);

		if (value)
		{
			iter->data = value;
			return;
		}

		LIST_UNLINK (self->map[pos], iter);
		free (iter);
		self->len--;

		str_map_shrink (self);
		return;
	}

	if (!value)
		return;

	if (self->len >= self->alloc)
	{
		str_map_resize (self, self->alloc << 1);
		pos = str_map_pos (self, key);
	}

	// Link in a new element for the given <key, value> pair
	size_t key_length = strlen (key);
	struct str_map_link *link = xmalloc (sizeof *link + key_length + 1);
	link->data = value;
	link->key_length = key_length;
	memcpy (link->key, key, key_length + 1);

	LIST_PREPEND (self->map[pos], link);
	self->len++;
}

static void
str_map_set (struct str_map *self, const char *key, void *value)
{
	if (!self->key_xfrm)
	{
		str_map_set_real (self, key, value);
		return;
	}
	char tmp[self->key_xfrm (NULL, key, 0) + 1];
	self->key_xfrm (tmp, key, sizeof tmp);
	str_map_set_real (self, tmp, value);
}

static void *
str_map_find_real (const struct str_map *self, const char *key)
{
	struct str_map_link *iter = self->map[str_map_pos (self, key)];
	for (; iter; iter = iter->next)
		if (!strcmp (key, (const char *) iter + sizeof *iter))
			return iter->data;
	return NULL;
}

static void *
str_map_find (const struct str_map *self, const char *key)
{
	if (!self->key_xfrm)
		return str_map_find_real (self, key);

	char tmp[self->key_xfrm (NULL, key, 0) + 1];
	self->key_xfrm (tmp, key, sizeof tmp);
	return str_map_find_real (self, tmp);
}

static void *
str_map_steal (struct str_map *self, const char *key)
{
	void *value = str_map_find (self, key);
	if (value)
	{
		str_map_free_fn free_saved = self->free;
		self->free = NULL;
		str_map_set (self, key, NULL);
		self->free = free_saved;
	}
	return value;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// This iterator is intended for accessing and eventually adding links.
// Use `link' directly to access the data.

struct str_map_iter
{
	const struct str_map *map;          ///< The map we're iterating
	size_t next_index;                  ///< Next table index to search
	struct str_map_link *link;          ///< Current link
};

static void
str_map_iter_init (struct str_map_iter *self, const struct str_map *map)
{
	self->map = map;
	self->next_index = 0;
	self->link = NULL;
}

static void *
str_map_iter_next (struct str_map_iter *self)
{
	const struct str_map *map = self->map;
	if (self->link)
		self->link = self->link->next;
	while (!self->link)
	{
		if (self->next_index >= map->alloc)
			return NULL;
		self->link = map->map[self->next_index++];
	}
	return self->link->data;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// This iterator is intended for accessing and eventually removing links.
// Use `link' directly to access the data.

struct str_map_unset_iter
{
	struct str_map_iter iter;           ///< Regular iterator
	struct str_map_link *link;          ///< Current link
	struct str_map_link *next;          ///< Next link
};

static void
str_map_unset_iter_init (struct str_map_unset_iter *self, struct str_map *map)
{
	str_map_iter_init (&self->iter, map);
	map->shrink_lock = true;
	(void) str_map_iter_next (&self->iter);
	self->next = self->iter.link;
}

static void *
str_map_unset_iter_next (struct str_map_unset_iter *self)
{
	if (!(self->link = self->next))
		return NULL;
	(void) str_map_iter_next (&self->iter);
	self->next = self->iter.link;
	return self->link->data;
}

static void
str_map_unset_iter_free (struct str_map_unset_iter *self)
{
	// So that we don't have to store another non-const pointer
	struct str_map *map = (struct str_map *) self->iter.map;

	map->shrink_lock = false;
	str_map_shrink (map);
}

// --- Asynchronous jobs -------------------------------------------------------

// For operations that can block execution but can be run independently on the
// rest of the program, such as getaddrinfo(), read(), write(), fsync().
//
// The async structure is meant to be extended for the various usages with
// new fields and provide an appropriate callback for its destruction.
//
// This is designed so that it can be used in other event loops than poller.

#ifdef LIBERTY_WANT_ASYNC

struct async;
typedef void (*async_fn) (struct async *);

struct async
{
	LIST_HEADER (struct async)
	struct async_manager *manager;      ///< Our manager object

	// "cancelled" may not be accesed or modified by the worker thread

	pthread_t worker;                   ///< Worker thread ID
	bool started;                       ///< Worker thread ID is valid
	bool cancelled;                     ///< Task has been cancelled

	async_fn execute;                   ///< Worker main function
	async_fn dispatcher;                ///< Main thread result dispatcher
	async_fn destroy;                   ///< Destroys the whole object
};

struct async_manager
{
	pthread_mutex_t lock;               ///< Lock for the queues
	struct async *running;              ///< Queue of running jobs
	struct async *finished;             ///< Queue of completed/cancelled jobs

	// It's upon the user to call async_manager_dispatch() to retry the delayed.
	// It's somewhat questionable if this feature is of any use. Possibly if we
	// provide a means of actively limiting the amount of running async jobs.

	struct async *delayed;              ///< Resource exhaustion queue

	// We need the pipe in order to abort polling (instead of using EINTR)

	pthread_cond_t finished_cond;       ///< Signals that a task has finished
	int finished_pipe[2];               ///< Signals that a task has finished
};

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
async_init (struct async *self, struct async_manager *manager)
{
	memset (self, 0, sizeof *self);
	self->manager = manager;
}

/// Only allowed from the main thread once the job has been started but before
/// the results have been dispatched
static void
async_cancel (struct async *self)
{
	if (self->started)
		soft_assert (!pthread_cancel (self->worker));
	self->cancelled = true;
}

static void
async_cleanup (void *user_data)
{
	struct async *self = user_data;

	hard_assert (!pthread_mutex_lock (&self->manager->lock));
	LIST_UNLINK (self->manager->running, self);
	LIST_PREPEND (self->manager->finished, self);
	hard_assert (!pthread_mutex_unlock (&self->manager->lock));

	hard_assert (!pthread_cond_broadcast (&self->manager->finished_cond));
	hard_assert (write (self->manager->finished_pipe[1], "", 1) > 0);
}

static void *
async_routine (void *user_data)
{
	// Beware that we mustn't trigger any cancellation point before we set up
	// the cleanup handler, otherwise we'd need to disable it first
	struct async *self = user_data;
	pthread_cleanup_push (async_cleanup, self);

	self->execute (self);

	pthread_cleanup_pop (true);
	return NULL;
}

static bool
async_run (struct async *self)
{
	hard_assert (!pthread_mutex_lock (&self->manager->lock));
	LIST_PREPEND (self->manager->running, self);
	hard_assert (!pthread_mutex_unlock (&self->manager->lock));

	// Block all signals so that the new thread doesn't receive any (inherited)
	sigset_t all_blocked, old_blocked;
	hard_assert (!sigfillset (&all_blocked));
	hard_assert (!pthread_sigmask (SIG_SETMASK, &all_blocked, &old_blocked));

	int error = pthread_create (&self->worker, NULL, async_routine, self);

	// Now that we've created the thread, resume signal processing as usual
	hard_assert (!pthread_sigmask (SIG_SETMASK, &old_blocked, NULL));

	if (error)
	{
		hard_assert (error == EAGAIN);

		hard_assert (!pthread_mutex_lock (&self->manager->lock));
		LIST_UNLINK (self->manager->running, self);
		hard_assert (!pthread_mutex_unlock (&self->manager->lock));

		// FIXME: we probably want to have some kind of a limit on the queue
		LIST_PREPEND (self->manager->delayed, self);
		return false;
	}
	return (self->started = true);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static struct async *
async_manager_dispatch_fetch (struct async_manager *self)
{
	// We don't want to hold the mutex for too long, mainly to prevent
	// a deadlock when trying to add an async job while dispatching another
	hard_assert (!pthread_mutex_lock (&self->lock));
	struct async *result;
	if ((result = self->finished))
		LIST_UNLINK (self->finished, result);
	hard_assert (!pthread_mutex_unlock (&self->lock));
	return result;
}

static void
async_manager_dispatch (struct async_manager *self)
{
	char dummy;
	while (read (self->finished_pipe[0], &dummy, 1) > 0)
		;  // Just emptying the signalling pipe

	struct async *iter;
	while ((iter = async_manager_dispatch_fetch (self)))
	{
		// The thread has finished execution already
		soft_assert (!pthread_join (iter->worker, NULL));

		if (iter->dispatcher && !iter->cancelled)
			iter->dispatcher (iter);
		if (iter->destroy)
			iter->destroy (iter);
	}

	LIST_FOR_EACH (struct async, iter, self->delayed)
	{
		LIST_UNLINK (self->delayed, iter);
		if (iter->cancelled)
		{
			if (iter->destroy)
				iter->destroy (iter);
		}
		else if (!async_run (iter))
			break;
	}
}

static void
async_manager_cancel_all (struct async_manager *self)
{
	hard_assert (!pthread_mutex_lock (&self->lock));

	// Cancel all running jobs
	LIST_FOR_EACH (struct async, iter, self->running)
		soft_assert (!pthread_cancel (iter->worker));

	// Wait until no jobs are running anymore (we need to release the lock
	// here so that worker threads can move their jobs to the finished queue)
	while (self->running)
		hard_assert (!pthread_cond_wait (&self->finished_cond, &self->lock));

	// Mark everything cancelled so that it's not actually dispatched
	LIST_FOR_EACH (struct async, iter, self->finished)
		iter->cancelled = true;
	LIST_FOR_EACH (struct async, iter, self->delayed)
		iter->cancelled = true;

	hard_assert (!pthread_mutex_unlock (&self->lock));
	async_manager_dispatch (self);
}

static void
async_manager_init (struct async_manager *self)
{
	memset (self, 0, sizeof *self);
	hard_assert (!pthread_mutex_init (&self->lock, NULL));
	hard_assert (!pthread_cond_init (&self->finished_cond, NULL));

	hard_assert (!pipe (self->finished_pipe));
	hard_assert (set_blocking (self->finished_pipe[0], false));
	set_cloexec (self->finished_pipe[0]);
	set_cloexec (self->finished_pipe[1]);
}

static void
async_manager_free (struct async_manager *self)
{
	async_manager_cancel_all (self);
	hard_assert (!pthread_cond_destroy (&self->finished_cond));
	hard_assert (!pthread_mutex_destroy (&self->lock));

	xclose (self->finished_pipe[0]);
	xclose (self->finished_pipe[1]);
}

#endif // LIBERTY_WANT_ASYNC

// --- Event loop --------------------------------------------------------------

#ifdef LIBERTY_WANT_POLLER

// Basically the poor man's GMainLoop/libev/libuv.  It might make some sense
// to instead use those tested and proven libraries but we don't need much
// and it's interesting to implement.

// We sacrifice some memory to allow for O(1) and O(log n) operations.

typedef void (*poller_fd_fn) (const struct pollfd *, void *);
typedef void (*poller_timer_fn) (void *);
typedef void (*poller_idle_fn) (void *);

#define POLLER_MIN_ALLOC 16

struct poller_timer
{
	struct poller_timers *timers;       ///< The timers part of our poller
	ssize_t index;                      ///< Where we are in the array, or -1

	int64_t when;                       ///< When is the timer to expire

	poller_timer_fn dispatcher;         ///< Event dispatcher
	void *user_data;                    ///< User data
};

struct poller_fd
{
	struct poller *poller;              ///< Our poller
	ssize_t index;                      ///< Where we are in the array, or -1

	int fd;                             ///< Our file descriptor
	short events;                       ///< The poll() events we registered for

	// Make triple sure that no forked child is keeping the FD,
	// otherwise we may access freed memory on Linux (poor epoll design)
	bool closed;                        ///< Whether fd has been closed already

	poller_fd_fn dispatcher;            ///< Event dispatcher
	void *user_data;                    ///< User data
};

struct poller_idle
{
	LIST_HEADER (struct poller_idle)
	struct poller *poller;              ///< Our poller

	bool active;                        ///< Whether we're on the list

	poller_idle_fn dispatcher;          ///< Event dispatcher
	void *user_data;                    ///< User data
};

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

struct poller_timers
{
	struct poller_timer **heap;         ///< Min-heap of timers
	size_t len;                         ///< Number of scheduled timers
	size_t alloc;                       ///< Number of timers allocated
};

static void
poller_timers_init (struct poller_timers *self)
{
	self->alloc = POLLER_MIN_ALLOC;
	self->len = 0;
	self->heap = xmalloc (self->alloc * sizeof *self->heap);
}

static void
poller_timers_free (struct poller_timers *self)
{
	free (self->heap);
}

static int64_t
poller_timers_get_current_time (void)
{
#ifdef _POSIX_TIMERS
	struct timespec tp;
	hard_assert (clock_gettime (CLOCK_BEST, &tp) != -1);
	return (int64_t) tp.tv_sec * 1000 + (int64_t) tp.tv_nsec / 1000000;
#else
	struct timeval tp;
	gettimeofday (&tp, NULL);
	return (int64_t) tp.tv_sec * 1000 + (int64_t) tp.tv_usec / 1000;
#endif
}

static void
poller_timers_heapify_down (struct poller_timers *self, size_t index)
{
	typedef struct poller_timer *timer_t;
	timer_t *end = self->heap + self->len;

	while (true)
	{
		timer_t *parent = self->heap + index;
		timer_t *left   = self->heap + 2 * index + 1;
		timer_t *right  = self->heap + 2 * index + 2;

		timer_t *lowest = parent;
		if (left  < end && (*left) ->when < (*lowest)->when)
			lowest = left;
		if (right < end && (*right)->when < (*lowest)->when)
			lowest = right;
		if (parent == lowest)
			break;

		timer_t tmp = *parent;
		*parent = *lowest;
		*lowest = tmp;

		(*parent)->index = parent - self->heap;
		(*lowest)->index = lowest - self->heap;
		index = lowest - self->heap;
	}
}

static void
poller_timers_remove_at_index (struct poller_timers *self, size_t index)
{
	hard_assert (index < self->len);
	self->heap[index]->index = -1;
	if (index == --self->len)
		return;

	self->heap[index] = self->heap[self->len];
	self->heap[index]->index = index;
	poller_timers_heapify_down (self, index);
}

static void
poller_timers_dispatch (struct poller_timers *self)
{
	int64_t now = poller_timers_get_current_time ();
	while (self->len && self->heap[0]->when <= now)
	{
		struct poller_timer *timer = self->heap[0];
		poller_timers_remove_at_index (self, 0);
		timer->dispatcher (timer->user_data);
	}
}

static void
poller_timers_heapify_up (struct poller_timers *self, size_t index)
{
	while (index != 0)
	{
		size_t parent = (index - 1) / 2;
		if (self->heap[parent]->when <= self->heap[index]->when)
			break;

		struct poller_timer *tmp = self->heap[parent];
		self->heap[parent] = self->heap[index];
		self->heap[index] = tmp;

		self->heap[parent]->index = parent;
		self->heap[index] ->index = index;
		index = parent;
	}
}

static void
poller_timers_set (struct poller_timers *self, struct poller_timer *timer)
{
	hard_assert (timer->timers == self);
	if (timer->index != -1)
	{
		poller_timers_heapify_down (self, timer->index);
		poller_timers_heapify_up (self, timer->index);
		return;
	}

	if (self->len == self->alloc)
		self->heap = xreallocarray (self->heap,
			self->alloc <<= 1, sizeof *self->heap);
	self->heap[self->len] = timer;
	timer->index = self->len;
	poller_timers_heapify_up (self, self->len++);
}

static int
poller_timers_get_poll_timeout (const struct poller_timers *self)
{
	if (!self->len)
		return -1;

	int64_t timeout = self->heap[0]->when - poller_timers_get_current_time ();
	if (timeout <= 0)
		return 0;
	if (timeout > INT_MAX)
		return INT_MAX;
	return timeout;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
poller_idle_dispatch (const struct poller_idle *list)
{
	const struct poller_idle *iter, *next;
	for (iter = list; iter; iter = next)
	{
		next = iter->next;
		iter->dispatcher (iter->user_data);
	}
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

struct poller_common
{
	struct poller_timers timers;        ///< Timeouts
	struct poller_idle *idle;           ///< Idle events
#ifdef LIBERTY_WANT_ASYNC
	struct async_manager async;         ///< Asynchronous jobs
	struct poller_fd async_event;       ///< Asynchronous jobs have finished
#endif // LIBERTY_WANT_ASYNC
};

static void poller_common_init (struct poller_common *, struct poller *);
static void poller_common_free (struct poller_common *);
static int poller_common_get_timeout (const struct poller_common *);
static void poller_common_dispatch (struct poller_common *);

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

#ifdef __linux__
#include <sys/epoll.h>

struct poller
{
	int epoll_fd;                       ///< The epoll FD
	struct poller_fd **fds;             ///< Information associated with each FD
	int *dummy;                         ///< For poller_remove_from_dispatch()
	struct epoll_event *revents;        ///< Output array for epoll_wait()
	size_t len;                         ///< Number of polled descriptors
	size_t alloc;                       ///< Number of entries allocated
	struct poller_common common;        ///< Stuff common to all backends
	int revents_len;                    ///< Number of entries in `revents'
};

static void
poller_init (struct poller *self)
{
	self->epoll_fd = epoll_create (POLLER_MIN_ALLOC);
	hard_assert (self->epoll_fd != -1);
	set_cloexec (self->epoll_fd);

	self->len = 0;
	self->alloc = POLLER_MIN_ALLOC;
	self->fds = xcalloc (self->alloc, sizeof *self->fds);
	self->dummy = xcalloc (self->alloc, sizeof *self->dummy);
	self->revents = xcalloc (self->alloc, sizeof *self->revents);
	self->revents_len = 0;

	poller_common_init (&self->common, self);
}

static void
poller_free (struct poller *self)
{
	for (size_t i = 0; i < self->len; i++)
	{
		struct poller_fd *fd = self->fds[i];
		hard_assert (epoll_ctl (self->epoll_fd,
			EPOLL_CTL_DEL, fd->fd, (void *) "") != -1);
	}

	poller_common_free (&self->common);

	xclose (self->epoll_fd);
	free (self->fds);
	free (self->dummy);
	free (self->revents);
}

static void
poller_ensure_space (struct poller *self)
{
	if (self->len < self->alloc)
		return;

	self->alloc <<= 1;
	hard_assert (self->alloc != 0);

	self->revents = xreallocarray
		(self->revents, sizeof *self->revents, self->alloc);
	self->fds = xreallocarray
		(self->fds, sizeof *self->fds, self->alloc);
	self->dummy = xreallocarray
		(self->dummy, sizeof *self->dummy, self->alloc);
}

static short
poller_epoll_to_poll_events (uint32_t events)
{
	short result = 0;
	if (events & EPOLLIN)   result |= POLLIN;
	if (events & EPOLLOUT)  result |= POLLOUT;
	if (events & EPOLLERR)  result |= POLLERR;
	if (events & EPOLLHUP)  result |= POLLHUP;
	if (events & EPOLLPRI)  result |= POLLPRI;
	return result;
}

static uint32_t
poller_poll_to_epoll_events (short events)
{
	uint32_t result = 0;
	if (events & POLLIN)   result |= EPOLLIN;
	if (events & POLLOUT)  result |= EPOLLOUT;
	if (events & POLLERR)  result |= EPOLLERR;
	if (events & POLLHUP)  result |= EPOLLHUP;
	if (events & POLLPRI)  result |= EPOLLPRI;
	return result;
}

static void
poller_set (struct poller *self, struct poller_fd *fd)
{
	hard_assert (fd->poller == self);
	bool modifying = true;
	if (fd->index == -1)
	{
		poller_ensure_space (self);
		self->fds[fd->index = self->len++] = fd;
		modifying = false;
	}

	struct epoll_event event;
	event.events = poller_poll_to_epoll_events (fd->events);
	event.data.ptr = fd;
	hard_assert (epoll_ctl (self->epoll_fd,
		modifying ? EPOLL_CTL_MOD : EPOLL_CTL_ADD, fd->fd, &event) != -1);
}

#define poller_post_fork(self)

static int
poller_compare_fds (const void *ax, const void *bx)
{
	const struct epoll_event *ay = ax, *by = bx;
	struct poller_fd *a = ay->data.ptr, *b = by->data.ptr;
	return a->fd - b->fd;
}

static void
poller_remove_from_dispatch (struct poller *self, const struct poller_fd *fd)
{
	if (!self->revents_len)
		return;

	struct epoll_event key = { .data.ptr = (void *) fd }, *fd_event;
	if ((fd_event = bsearch (&key, self->revents,
		self->revents_len, sizeof *self->revents, poller_compare_fds)))
	{
		fd_event->events = -1;

		// Don't let any further bsearch()'s touch possibly freed memory
		int *dummy = self->dummy + (fd_event - self->revents);
		*dummy = fd->fd;
		fd_event->data.ptr =
			(uint8_t *) dummy - offsetof (struct poller_fd, fd);
	}
}

static void
poller_remove_at_index (struct poller *self, size_t index)
{
	hard_assert (index < self->len);
	struct poller_fd *fd = self->fds[index];
	fd->index = -1;

	poller_remove_from_dispatch (self, fd);
	if (!fd->closed)
		hard_assert (epoll_ctl (self->epoll_fd,
			EPOLL_CTL_DEL, fd->fd, (void *) "") != -1);

	if (index != --self->len)
	{
		self->fds[index] = self->fds[self->len];
		self->fds[index]->index = index;
	}
}

static void
poller_run (struct poller *self)
{
	// Not reentrant
	hard_assert (!self->revents_len);

	int n_fds;
	do
		n_fds = epoll_wait (self->epoll_fd, self->revents, self->alloc,
			poller_common_get_timeout (&self->common));
	while (n_fds == -1 && errno == EINTR);

	if (n_fds == -1)
		exit_fatal ("%s: %s", "epoll", strerror (errno));

	// Sort them by file descriptor number for binary search
	qsort (self->revents, n_fds, sizeof *self->revents, poller_compare_fds);
	self->revents_len = n_fds;

	poller_common_dispatch (&self->common);

	for (int i = 0; i < n_fds; i++)
	{
		struct epoll_event *revents = self->revents + i;
		if (revents->events == (uint32_t) -1)
			continue;

		struct poller_fd *fd = revents->data.ptr;
		hard_assert (fd->index != -1);

		struct pollfd pfd;
		pfd.fd = fd->fd;
		pfd.revents = poller_epoll_to_poll_events (revents->events);
		pfd.events = fd->events;

		fd->dispatcher (&pfd, fd->user_data);
	}

	self->revents_len = 0;
}

#elif defined (BSD)

// Mac OS X's kqueue is fatally broken, or so I've been told; leaving it out.
// Otherwise this is sort of similar to the epoll version.

#include <sys/types.h>
#include <sys/event.h>
#include <sys/time.h>

struct poller
{
	int kqueue_fd;                      ///< The kqueue FD
	struct poller_fd **fds;             ///< Information associated with each FD
	struct kevent *revents;             ///< Output array for kevent()
	size_t len;                         ///< Number of polled descriptors
	size_t alloc;                       ///< Number of entries allocated
	struct poller_common common;        ///< Stuff common to all backends
	int revents_len;                    ///< Number of entries in `revents'
};

static void
poller_init (struct poller *self)
{
	self->kqueue_fd = kqueue ();
	hard_assert (self->kqueue_fd != -1);
	set_cloexec (self->kqueue_fd);

	self->len = 0;
	self->alloc = POLLER_MIN_ALLOC;
	self->fds = xcalloc (self->alloc, sizeof *self->fds);
	self->revents = xcalloc (self->alloc, sizeof *self->revents);
	self->revents_len = 0;
	poller_common_init (&self->common, self);
}

static void
poller_free (struct poller *self)
{
	xclose (self->kqueue_fd);
	free (self->fds);
	free (self->revents);
	poller_common_free (&self->common);
}

static void
poller_ensure_space (struct poller *self)
{
	if (self->len < self->alloc)
		return;

	self->alloc <<= 1;
	hard_assert (self->alloc != 0);

	self->revents = xreallocarray
		(self->revents, sizeof *self->revents, self->alloc);
	self->fds = xreallocarray
		(self->fds, sizeof *self->fds, self->alloc);
}

static void
poller_set (struct poller *self, struct poller_fd *fd)
{
	hard_assert (fd->poller == self);
	if (fd->index == -1)
	{
		poller_ensure_space (self);
		self->fds[fd->index = self->len++] = fd;
	}

	// We have to watch for readability and writeability separately;
	// to simplify matters, we can just disable what we don't desire to receive
	struct kevent changes[2];
	EV_SET (&changes[0], fd->fd, EVFILT_READ,  EV_ADD, 0, 0, fd);
	EV_SET (&changes[1], fd->fd, EVFILT_WRITE, EV_ADD, 0, 0, fd);
	changes[0].flags |= (fd->events & POLLIN)  ? EV_ENABLE : EV_DISABLE;
	changes[1].flags |= (fd->events & POLLOUT) ? EV_ENABLE : EV_DISABLE;

	if (kevent (self->kqueue_fd,
		changes, N_ELEMENTS (changes), NULL, 0, NULL) == -1)
		exit_fatal ("%s: %s", "kevent", strerror (errno));
}

static void
poller_post_fork (struct poller *self)
{
	// The kqueue FD isn't preserved across forks, need to recreate it
	self->kqueue_fd = kqueue ();
	hard_assert (self->kqueue_fd != -1);
	set_cloexec (self->kqueue_fd);

	for (size_t i = 0; i < self->len; i++)
		poller_set (self, self->fds[i]);
}

static int
poller_compare_fds (const void *ax, const void *bx)
{
	const struct kevent *ay = ax, *by = bx;
	return (int) ay->ident - (int) by->ident;
}

static void
poller_dummify (struct kevent *fd_event)
{
	fd_event->flags = USHRT_MAX;
}

static void
poller_remove_from_dispatch (struct poller *self, const struct poller_fd *fd)
{
	if (!self->revents_len)
		return;

	struct kevent key = { .ident = fd->fd }, *fd_event;
	if (!(fd_event = bsearch (&key, self->revents,
		self->revents_len, sizeof *self->revents, poller_compare_fds)))
		return;

	// The FD may appear twice -- both for reading and writing
	int index = fd_event - self->revents;

	if (index > 0
	 && !poller_compare_fds (&key, fd_event - 1))
		poller_dummify (fd_event - 1);

	poller_dummify (fd_event);

	if (index < self->revents_len - 1
	 && !poller_compare_fds (&key, fd_event + 1))
		poller_dummify (fd_event + 1);
}

static void
poller_remove_at_index (struct poller *self, size_t index)
{
	hard_assert (index < self->len);
	struct poller_fd *fd = self->fds[index];
	fd->index = -1;

	poller_remove_from_dispatch (self, fd);

	if (index != --self->len)
	{
		self->fds[index] = self->fds[self->len];
		self->fds[index]->index = index;
	}

	if (fd->closed)
		return;

	struct kevent changes[2];
	EV_SET (&changes[0], fd->fd, EVFILT_READ,  EV_DELETE, 0, 0, fd);
	EV_SET (&changes[1], fd->fd, EVFILT_WRITE, EV_DELETE, 0, 0, fd);

	if (kevent (self->kqueue_fd,
		changes, N_ELEMENTS (changes), NULL, 0, NULL) == -1)
		exit_fatal ("%s: %s", "kevent", strerror (errno));
}

static struct timespec
poller_timeout_to_timespec (int ms)
{
	return (struct timespec)
	{
		.tv_sec = ms / 1000,
		.tv_nsec = (ms % 1000) * 1000 * 1000
	};
}

static short
poller_kqueue_to_poll_events (struct kevent *event)
{
	short result = 0;
	if (event->filter == EVFILT_READ)
	{
		result |= POLLIN;
		if ((event->flags & EV_EOF) && event->fflags)
			result |= POLLERR;
	}
	if (event->filter == EVFILT_WRITE)  result |= POLLOUT;
	if (event->flags & EV_EOF)          result |= POLLHUP;
	return result;
}

static void
poller_run (struct poller *self)
{
	// Not reentrant
	hard_assert (!self->revents_len);

	int n_fds;
	do
	{
		int timeout = poller_common_get_timeout (&self->common);
		struct timespec ts = poller_timeout_to_timespec (timeout);
		n_fds = kevent (self->kqueue_fd,
			NULL, 0, self->revents, self->len, timeout < 0 ? NULL : &ts);
	}
	while (n_fds == -1 && errno == EINTR);

	if (n_fds == -1)
		exit_fatal ("%s: %s", "kevent", strerror (errno));

	// Sort them by file descriptor number for binary search
	qsort (self->revents, n_fds, sizeof *self->revents, poller_compare_fds);
	self->revents_len = n_fds;

	poller_common_dispatch (&self->common);

	for (int i = 0; i < n_fds; i++)
	{
		struct kevent *event = self->revents + i;
		if (event->flags == USHRT_MAX)
			continue;

		struct poller_fd *fd = event->udata;
		hard_assert (fd->index != -1);

		struct pollfd pfd;
		pfd.fd = fd->fd;
		pfd.revents = poller_kqueue_to_poll_events (event);
		pfd.events = fd->events;

		// Read and write events are separate in the kqueue API -- merge them
		int sibling = 1;
		while (i + sibling < n_fds
			&& !poller_compare_fds (event, event + sibling))
			pfd.revents |= poller_kqueue_to_poll_events (event + sibling++);
		if ((pfd.revents & POLLHUP) && (pfd.revents & POLLOUT))
			pfd.revents &= ~POLLOUT;
		i += --sibling;

		fd->dispatcher (&pfd, fd->user_data);
	}

	self->revents_len = 0;
}

#else  // ! BSD

struct poller
{
	struct pollfd *fds;                 ///< Polled descriptors
	struct poller_fd **fds_data;        ///< Additional information for each FD
	size_t len;                         ///< Number of polled descriptors
	size_t alloc;                       ///< Number of entries allocated
	struct poller_common common;        ///< Stuff common to all backends
	int dispatch_next;                  ///< The next dispatched FD or -1
};

static void
poller_init (struct poller *self)
{
	self->alloc = POLLER_MIN_ALLOC;
	self->len = 0;
	self->fds = xcalloc (self->alloc, sizeof *self->fds);
	self->fds_data = xcalloc (self->alloc, sizeof *self->fds_data);
	poller_common_init (&self->common, self);
	self->dispatch_next = -1;
}

static void
poller_free (struct poller *self)
{
	free (self->fds);
	free (self->fds_data);
	poller_common_free (&self->common);
}

static void
poller_ensure_space (struct poller *self)
{
	if (self->len < self->alloc)
		return;

	self->alloc <<= 1;
	self->fds = xreallocarray (self->fds, sizeof *self->fds, self->alloc);
	self->fds_data = xreallocarray
		(self->fds_data, sizeof *self->fds_data, self->alloc);
}

static void
poller_set (struct poller *self, struct poller_fd *fd)
{
	hard_assert (fd->poller == self);
	if (fd->index == -1)
	{
		poller_ensure_space (self);
		self->fds_data[fd->index = self->len++] = fd;
	}

	struct pollfd *new_entry = self->fds + fd->index;
	memset (new_entry, 0, sizeof *new_entry);
	new_entry->fd = fd->fd;
	new_entry->events = fd->events;
}

#define poller_post_fork(self)

static void
poller_remove_at_index (struct poller *self, size_t index)
{
	hard_assert (index < self->len);
	struct poller_fd *fd = self->fds_data[index];
	fd->index = -1;

	if (index == --self->len)
		return;

	// Make sure that we don't disrupt the dispatch loop; kind of crude
	if ((int) index < self->dispatch_next)
	{
		memmove (self->fds + index, self->fds + index + 1,
			(self->len - index) * sizeof *self->fds);
		memmove (self->fds_data + index, self->fds_data + index + 1,
			(self->len - index) * sizeof *self->fds_data);
		for (size_t i = index; i < self->len; i++)
			self->fds_data[i]->index = i;

		self->dispatch_next--;
	}
	else
	{
		self->fds[index]      = self->fds     [self->len];
		self->fds_data[index] = self->fds_data[self->len];
		self->fds_data[index]->index = index;
	}
}

static void
poller_run (struct poller *self)
{
	// Not reentrant
	hard_assert (self->dispatch_next == -1);

	int result;
	do
		result = poll (self->fds, self->len,
			poller_common_get_timeout (&self->common));
	while (result == -1 && errno == EINTR);

	if (result == -1)
		exit_fatal ("%s: %s", "poll", strerror (errno));

	poller_common_dispatch (&self->common);

	for (int i = 0; i < (int) self->len; )
	{
		struct pollfd pfd = self->fds[i];
		struct poller_fd *fd = self->fds_data[i];
		self->dispatch_next = ++i;
		if (pfd.revents)
			fd->dispatcher (&pfd, fd->user_data);
		i = self->dispatch_next;
	}

	self->dispatch_next = -1;
}

#endif  // ! BSD

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
poller_timer_init (struct poller_timer *self, struct poller *poller)
{
	memset (self, 0, sizeof *self);
	self->timers = &poller->common.timers;
	self->index = -1;
}

static void
poller_timer_set (struct poller_timer *self, int timeout_ms)
{
	self->when = poller_timers_get_current_time () + timeout_ms;
	poller_timers_set (self->timers, self);
}

static bool
poller_timer_is_active (const struct poller_timer *self)
{
	return self->index != -1;
}

static void
poller_timer_reset (struct poller_timer *self)
{
	if (self->index != -1)
		poller_timers_remove_at_index (self->timers, self->index);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
poller_idle_init (struct poller_idle *self, struct poller *poller)
{
	memset (self, 0, sizeof *self);
	self->poller = poller;
}

static void
poller_idle_set (struct poller_idle *self)
{
	if (self->active)
		return;

	LIST_PREPEND (self->poller->common.idle, self);
	self->active = true;
}

static void
poller_idle_reset (struct poller_idle *self)
{
	if (!self->active)
		return;

	LIST_UNLINK (self->poller->common.idle, self);
	self->prev = NULL;
	self->next = NULL;
	self->active = false;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
poller_fd_init (struct poller_fd *self, struct poller *poller, int fd)
{
	memset (self, 0, sizeof *self);
	self->poller = poller;
	self->index = -1;
	self->fd = fd;
}

static void
poller_fd_set (struct poller_fd *self, short events)
{
	self->events = events;
	poller_set (self->poller, self);
}

static void
poller_fd_reset (struct poller_fd *self)
{
	if (self->index != -1)
		poller_remove_at_index (self->poller, self->index);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
poller_common_dummy_dispatcher (const struct pollfd *pfd, void *user_data)
{
	(void) pfd;
	(void) user_data;

	// The async manager will empty the pipe when we invoke dispatch
}

static void
poller_common_init (struct poller_common *self, struct poller *poller)
{
	poller_timers_init (&self->timers);
	self->idle = NULL;
#ifdef LIBERTY_WANT_ASYNC
	async_manager_init (&self->async);

	poller_fd_init (&self->async_event, poller, self->async.finished_pipe[0]);
	poller_fd_set (&self->async_event, POLLIN);
	self->async_event.dispatcher = poller_common_dummy_dispatcher;
	self->async_event.user_data = self;
#else // ! LIBERTY_WANT_ASYNC
	(void) poller;
#endif // ! LIBERTY_WANT_ASYNC
}

static void
poller_common_free (struct poller_common *self)
{
	poller_timers_free (&self->timers);
#ifdef LIBERTY_WANT_ASYNC
	async_manager_free (&self->async);
#endif // LIBERTY_WANT_ASYNC
}

static int
poller_common_get_timeout (const struct poller_common *self)
{
	if (self->idle)
		return 0;

	int timeout = poller_timers_get_poll_timeout (&self->timers);
#ifdef LIBERTY_WANT_ASYNC
	// This is completely arbitrary, in general we have no idea when to retry,
	// however one second doesn't sound like a particularly bad number
	if (self->async.delayed)
		timeout = MIN (timeout, 1000);
#endif // LIBERTY_WANT_ASYNC
	return timeout;
}

static void
poller_common_dispatch (struct poller_common *self)
{
	poller_timers_dispatch (&self->timers);
	poller_idle_dispatch (self->idle);
#ifdef LIBERTY_WANT_ASYNC
	async_manager_dispatch (&self->async);
#endif // LIBERTY_WANT_ASYNC
}

#endif // LIBERTY_WANT_POLLER

// --- Asynchronous jobs -------------------------------------------------------

#ifdef LIBERTY_WANT_ASYNC

/// The callback takes ownership of the returned list
typedef void (*async_getaddrinfo_fn) (int, struct addrinfo *, void *);

struct async_getaddrinfo
{
	struct async async;                 ///< Parent object

	int gai_result;                     ///< Direct result from getaddrinfo()
	char *host;                         ///< gai() argument: host
	char *service;                      ///< gai() argument: service
	struct addrinfo hints;              ///< gai() argument: hints
	struct addrinfo *result;            ///< Resulting addresses from gai()

	async_getaddrinfo_fn dispatcher;    ///< Event dispatcher
	void *user_data;                    ///< User data
};

static void
async_getaddrinfo_execute (struct async *async)
{
	struct async_getaddrinfo *self = (struct async_getaddrinfo *) async;
	self->gai_result =
		getaddrinfo (self->host, self->service, &self->hints, &self->result);
}

static void
async_getaddrinfo_dispatch (struct async *async)
{
	struct async_getaddrinfo *self = (struct async_getaddrinfo *) async;
	self->dispatcher (self->gai_result, self->result, self->user_data);
	self->result = NULL;
}

static void
async_getaddrinfo_destroy (struct async *async)
{
	struct async_getaddrinfo *self = (struct async_getaddrinfo *) async;
	free (self->host);
	free (self->service);

	if (self->result)
		freeaddrinfo (self->result);

	free (self);
}

static struct async_getaddrinfo *
async_getaddrinfo (struct async_manager *manager,
	const char *host, const char *service, const struct addrinfo *hints)
{
	struct async_getaddrinfo *self = xcalloc (1, sizeof *self);
	async_init (&self->async, manager);

	if (host)     self->host = xstrdup (host);
	if (service)  self->service = xstrdup (service);
	if (hints)    memcpy (&self->hints, hints, sizeof *hints);

	self->async.execute    = async_getaddrinfo_execute;
	self->async.dispatcher = async_getaddrinfo_dispatch;
	self->async.destroy    = async_getaddrinfo_destroy;

	async_run (&self->async);
	return self;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

typedef void (*async_getnameinfo_fn) (int, char *, char *, void *);

struct async_getnameinfo
{
	struct async async;                 ///< Parent object

	int gni_result;                     ///< Direct result from getnameinfo()
	char host[NI_MAXHOST];              ///< gni() result: host name
	char service[NI_MAXSERV];           ///< gni() result: service name

	struct sockaddr *address;           ///< gni() argument: address
	socklen_t address_len;              ///< Size of the address
	int flags;                          ///< gni() argument: flags

	async_getnameinfo_fn dispatcher;    ///< Event dispatcher
	void *user_data;                    ///< User data
};

static void
async_getnameinfo_execute (struct async *async)
{
	struct async_getnameinfo *self = (struct async_getnameinfo *) async;
	self->gni_result = getnameinfo (self->address, self->address_len,
		self->host, sizeof self->host,
		self->service, sizeof self->service, self->flags);
}

static void
async_getnameinfo_dispatch (struct async *async)
{
	struct async_getnameinfo *self = (struct async_getnameinfo *) async;
	self->dispatcher (self->gni_result, self->host, self->service,
		self->user_data);
}

static void
async_getnameinfo_destroy (struct async *async)
{
	struct async_getnameinfo *self = (struct async_getnameinfo *) async;
	free (self->address);
	free (self);
}

static struct async_getnameinfo *
async_getnameinfo (struct async_manager *manager,
	const struct sockaddr *sa, socklen_t sa_len, int flags)
{
	struct async_getnameinfo *self = xcalloc (1, sizeof *self);
	async_init (&self->async, manager);

	self->address = memcpy (xmalloc (sa_len), sa, sa_len);
	self->address_len = sa_len;
	self->flags = flags;

	self->async.execute    = async_getnameinfo_execute;
	self->async.dispatcher = async_getnameinfo_dispatch;
	self->async.destroy    = async_getnameinfo_destroy;

	async_run (&self->async);
	return self;
}

#endif // LIBERTY_WANT_ASYNC

// --- libuv-style write adaptor -----------------------------------------------

// Makes it possible to use iovec to write multiple data chunks at once.

struct write_req
{
	LIST_HEADER (struct write_req)
	struct iovec data;                  ///< Data to be written
};

struct write_queue
{
	struct write_req *head;             ///< The head of the queue
	struct write_req *tail;             ///< The tail of the queue
	size_t head_offset;                 ///< Offset into the head
	size_t len;
};

static void
write_queue_init (struct write_queue *self)
{
	self->head = self->tail = NULL;
	self->head_offset = 0;
	self->len = 0;
}

static void
write_queue_free (struct write_queue *self)
{
	LIST_FOR_EACH (struct write_req, iter, self->head)
	{
		free (iter->data.iov_base);
		free (iter);
	}
}

static void
write_queue_add (struct write_queue *self, struct write_req *req)
{
	LIST_APPEND_WITH_TAIL (self->head, self->tail, req);
	self->len++;
}

static void
write_queue_processed (struct write_queue *self, size_t len)
{
	while (self->head
		&& self->head_offset + len >= self->head->data.iov_len)
	{
		struct write_req *head = self->head;
		len -= (head->data.iov_len - self->head_offset);
		self->head_offset = 0;

		LIST_UNLINK_WITH_TAIL (self->head, self->tail, head);
		self->len--;
		free (head->data.iov_base);
		free (head);
	}
	self->head_offset += len;
}

static bool
write_queue_is_empty (struct write_queue *self)
{
	return self->head == NULL;
}

// --- Message reader ----------------------------------------------------------

struct msg_reader
{
	struct str buf;                     ///< Input buffer
	uint64_t offset;                    ///< Current offset in the buffer
};

static void
msg_reader_init (struct msg_reader *self)
{
	str_init (&self->buf);
	self->offset = 0;
}

static void
msg_reader_free (struct msg_reader *self)
{
	str_free (&self->buf);
}

static void
msg_reader_compact (struct msg_reader *self)
{
	str_remove_slice (&self->buf, 0, self->offset);
	self->offset = 0;
}

static void
msg_reader_feed (struct msg_reader *self, const void *data, size_t len)
{
	// TODO: have some mechanism to prevent flooding
	msg_reader_compact (self);
	str_append_data (&self->buf, data, len);
}

static void *
msg_reader_get (struct msg_reader *self, size_t *len)
{
	// Try to read in the length of the message
	if (self->offset + sizeof (uint64_t) > self->buf.len)
		return NULL;

	uint8_t *x = (uint8_t *) self->buf.str + self->offset;
	uint64_t msg_len
		= (uint64_t) x[0] << 56 | (uint64_t) x[1] << 48
		| (uint64_t) x[2] << 40 | (uint64_t) x[3] << 32
		| (uint64_t) x[4] << 24 | (uint64_t) x[5] << 16
		| (uint64_t) x[6] << 8  | (uint64_t) x[7];

	if (msg_len < sizeof msg_len)
	{
		// The message is shorter than its header
		// TODO: have some mechanism to report errors
		return NULL;
	}

	if (self->offset + msg_len < self->offset)
	{
		// Trying to read an insane amount of data but whatever
		msg_reader_compact (self);
		return NULL;
	}

	// Check if we've got the full message in the buffer and return it
	if (self->offset + msg_len > self->buf.len)
		return NULL;

	// We have to subtract the header from the reported length
	void *data = self->buf.str + self->offset + sizeof msg_len;
	self->offset += msg_len;
	*len = msg_len - sizeof msg_len;
	return data;
}

// --- Message unpacker --------------------------------------------------------

struct msg_unpacker
{
	const char *data;
	size_t offset;
	size_t len;
};

static void
msg_unpacker_init (struct msg_unpacker *self, const void *data, size_t len)
{
	self->data = data;
	self->len = len;
	self->offset = 0;
}

static size_t
msg_unpacker_get_available (struct msg_unpacker *self)
{
	return self->len - self->offset;
}

#define UNPACKER_INT_BEGIN                                                     \
	if (self->len - self->offset < sizeof *value)                              \
		return false;                                                          \
	uint8_t *x = (uint8_t *) self->data + self->offset;                        \
	self->offset += sizeof *value;

static bool
msg_unpacker_u8 (struct msg_unpacker *self, uint8_t *value)
{
	UNPACKER_INT_BEGIN
	*value = x[0];
	return true;
}

static bool
msg_unpacker_u16 (struct msg_unpacker *self, uint16_t *value)
{
	UNPACKER_INT_BEGIN
	*value
		= (uint16_t) x[0] << 8  | (uint16_t) x[1];
	return true;
}

static bool
msg_unpacker_u32 (struct msg_unpacker *self, uint32_t *value)
{
	UNPACKER_INT_BEGIN
	*value
		= (uint32_t) x[0] << 24 | (uint32_t) x[1] << 16
		| (uint32_t) x[2] << 8  | (uint32_t) x[3];
	return true;
}

static bool
msg_unpacker_u64 (struct msg_unpacker *self, uint64_t *value)
{
	UNPACKER_INT_BEGIN
	*value
		= (uint64_t) x[0] << 56 | (uint64_t) x[1] << 48
		| (uint64_t) x[2] << 40 | (uint64_t) x[3] << 32
		| (uint64_t) x[4] << 24 | (uint64_t) x[5] << 16
		| (uint64_t) x[6] << 8  | (uint64_t) x[7];
	return true;
}

#define msg_unpacker_i8(self, value)                                           \
	msg_unpacker_u8  ((self), (uint8_t *) (value))
#define msg_unpacker_i16(self, value)                                          \
	msg_unpacker_u16 ((self), (uint16_t *) (value))
#define msg_unpacker_i32(self, value)                                          \
	msg_unpacker_u32 ((self), (uint32_t *) (value))
#define msg_unpacker_i64(self, value)                                          \
	msg_unpacker_u64 ((self), (uint64_t *) (value))

#undef UNPACKER_INT_BEGIN

// --- Message packer and writer -----------------------------------------------

// Use str_pack_*() or other methods to append to the internal buffer, then
// flush it to get a nice frame.  Handy for iovec.

struct msg_writer
{
	struct str buf;                     ///< Holds the message data
};

static void
msg_writer_init (struct msg_writer *self)
{
	str_init (&self->buf);
	// Placeholder for message length
	str_append_data (&self->buf, "\x00\x00\x00\x00" "\x00\x00\x00\x00", 8);
}

static void *
msg_writer_flush (struct msg_writer *self, size_t *len)
{
	// Update the message length
	uint64_t x = self->buf.len;
	uint8_t tmp[8] =
		{ x >> 56, x >> 48, x >> 40, x >> 32, x >> 24, x >> 16, x >> 8, x };
	memcpy (self->buf.str, tmp, sizeof tmp);

	*len = x;
	return str_steal (&self->buf);
}

// --- ASCII -------------------------------------------------------------------

#define TRIVIAL_STRXFRM(name, fn)                                              \
	static size_t                                                              \
	name (char *dest, const char *src, size_t n)                               \
	{                                                                          \
		size_t len = strlen (src);                                             \
		while (n-- && (*dest++ = (fn) (*src++)))                               \
			;                                                                  \
		return len;                                                            \
	}

static int
tolower_ascii (int c)
{
	return c >= 'A' && c <= 'Z' ? c + ('a' - 'A') : c;
}

static int
toupper_ascii (int c)
{
	return c >= 'a' && c <= 'z' ? c - ('a' - 'A') : c;
}

TRIVIAL_STRXFRM (tolower_ascii_strxfrm, tolower_ascii)
TRIVIAL_STRXFRM (toupper_ascii_strxfrm, toupper_ascii)

static int
strcasecmp_ascii (const char *a, const char *b)
{
	int x;
	while (*a || *b)
		if ((x = tolower_ascii (*(const unsigned char *) a++)
			- tolower_ascii (*(const unsigned char *) b++)))
			return x;
	return 0;
}

static int
strncasecmp_ascii (const char *a, const char *b, size_t n)
{
	int x;
	while (n-- && (*a || *b))
		if ((x = tolower_ascii (*(const unsigned char *) a++)
			- tolower_ascii (*(const unsigned char *) b++)))
			return x;
	return 0;
}

static bool
isalpha_ascii (int c)
{
	c &= ~32;
	return c >= 'A' && c <= 'Z';
}

static bool
isdigit_ascii (int c)
{
	return c >= '0' && c <= '9';
}

static bool
isalnum_ascii (int c)
{
	return isalpha_ascii (c) || isdigit_ascii (c);
}

static bool
isspace_ascii (int c)
{
	return c == ' '  || c == '\f' || c == '\n'
		|| c == '\r' || c == '\t' || c == '\v';
}

// --- UTF-8 -------------------------------------------------------------------

/// Return a pointer to the next UTF-8 character, or NULL on error
static const char *
utf8_next (const char *s, size_t len, int32_t *codepoint)
{
	// End of string, we go no further
	if (!len)
		return NULL;

	// Find out how long the sequence is (0 for ASCII)
	unsigned mask = 0x80;
	unsigned sequence_len = 0;

	const uint8_t *p = (const uint8_t *) s;
	while ((*p & mask) == mask)
	{
		// Invalid start of sequence
		if (mask == 0xFE)
			return NULL;

		mask |= mask >> 1;
		sequence_len++;
	}

	// In the middle of a character or the input is too short
	if (sequence_len == 1 || sequence_len > len)
		return NULL;

	// Check the rest of the sequence
	uint32_t cp = *p++ & ~mask;
	while (sequence_len && --sequence_len)
	{
		if ((*p & 0xC0) != 0x80)
			return NULL;
		cp = cp << 6 | (*p++ & 0x3F);
	}
	if (codepoint)
		*codepoint = cp;
	return (const char *) p;
}

/// Very rough UTF-8 validation, just makes sure codepoints can be iterated
static bool
utf8_validate (const char *s, size_t len)
{
	const char *next;
	while (len)
	{
		int32_t codepoint;
		// TODO: better validations
		if (!(next = utf8_next (s, len, &codepoint))
		 || codepoint > 0x10FFFF)
			return false;

		len -= next - s;
		s = next;
	}
	return true;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

struct utf8_iter
{
	const char *s;                      ///< String iterator
	size_t len;                         ///< How many bytes remain
};

static void
utf8_iter_init (struct utf8_iter *self, const char *s)
{
	self->len = strlen ((self->s = s));
}

static int32_t
utf8_iter_next (struct utf8_iter *self, size_t *len)
{
	if (!self->len)
		return -1;

	const char *old = self->s;
	int32_t codepoint;
	if (!soft_assert ((self->s = utf8_next (old, self->len, &codepoint))))
	{
		// Invalid UTF-8
		self->len = 0;
		return -1;
	}

	size_t advance = self->s - old;
	self->len -= advance;
	if (len) *len = advance;
	return codepoint;
}

// --- Base 64 -----------------------------------------------------------------

static uint8_t g_base64_table[256] =
{
	64, 64, 64, 64, 64, 64, 64, 64,  64, 64, 64, 64, 64, 64, 64, 64,
	64, 64, 64, 64, 64, 64, 64, 64,  64, 64, 64, 64, 64, 64, 64, 64,
	64, 64, 64, 64, 64, 64, 64, 64,  64, 64, 64, 62, 64, 64, 64, 63,
	52, 53, 54, 55, 56, 57, 58, 59,  60, 61, 64, 64, 64,  0, 64, 64,
	64,  0,  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, 64, 64, 64, 64, 64,
	64, 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, 64, 64, 64, 64, 64,

	64, 64, 64, 64, 64, 64, 64, 64,  64, 64, 64, 64, 64, 64, 64, 64,
	64, 64, 64, 64, 64, 64, 64, 64,  64, 64, 64, 64, 64, 64, 64, 64,
	64, 64, 64, 64, 64, 64, 64, 64,  64, 64, 64, 64, 64, 64, 64, 64,
	64, 64, 64, 64, 64, 64, 64, 64,  64, 64, 64, 64, 64, 64, 64, 64,
	64, 64, 64, 64, 64, 64, 64, 64,  64, 64, 64, 64, 64, 64, 64, 64,
	64, 64, 64, 64, 64, 64, 64, 64,  64, 64, 64, 64, 64, 64, 64, 64,
	64, 64, 64, 64, 64, 64, 64, 64,  64, 64, 64, 64, 64, 64, 64, 64,
	64, 64, 64, 64, 64, 64, 64, 64,  64, 64, 64, 64, 64, 64, 64, 64,
};

static inline bool
base64_decode_group (const char **s, bool ignore_ws, struct str *output)
{
	uint8_t input[4];
	size_t loaded = 0;
	for (; loaded < 4; (*s)++)
	{
		if (!**s)
			return loaded == 0;
		if (!ignore_ws || !isspace_ascii (**s))
			input[loaded++] = **s;
	}

	size_t len = 3;
	if (input[0] == '=' || input[1] == '=')
		return false;
	if (input[2] == '=' && input[3] != '=')
		return false;
	if (input[2] == '=')
		len--;
	if (input[3] == '=')
		len--;

	uint8_t a = g_base64_table[input[0]];
	uint8_t b = g_base64_table[input[1]];
	uint8_t c = g_base64_table[input[2]];
	uint8_t d = g_base64_table[input[3]];

	if (((a | b) | (c | d)) & 0x40)
		return false;

	uint32_t block = a << 18 | b << 12 | c << 6 | d;
	switch (len)
	{
	case 1:
		str_append_c (output, block >> 16);
		break;
	case 2:
		str_append_c (output, block >> 16);
		str_append_c (output, block >> 8);
		break;
	case 3:
		str_append_c (output, block >> 16);
		str_append_c (output, block >> 8);
		str_append_c (output, block);
	}
	return true;
}

static bool
base64_decode (const char *s, bool ignore_ws, struct str *output)
{
	while (*s)
		if (!base64_decode_group (&s, ignore_ws, output))
			return false;
	return true;
}

static void
base64_encode (const void *data, size_t len, struct str *output)
{
	const char *alphabet =
		"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

	const uint8_t *p = data;
	size_t n_groups = len / 3;
	size_t tail = len - n_groups * 3;
	uint32_t group;

	for (; n_groups--; p += 3)
	{
		group = p[0] << 16 | p[1] << 8 | p[2];
		str_append_c (output, alphabet[(group >> 18) & 63]);
		str_append_c (output, alphabet[(group >> 12) & 63]);
		str_append_c (output, alphabet[(group >>  6) & 63]);
		str_append_c (output, alphabet[ group        & 63]);
	}

	switch (tail)
	{
	case 2:
		group = p[0] << 16 | p[1] << 8;
		str_append_c (output, alphabet[(group >> 18) & 63]);
		str_append_c (output, alphabet[(group >> 12) & 63]);
		str_append_c (output, alphabet[(group >>  6) & 63]);
		str_append_c (output, '=');
		break;
	case 1:
		group = p[0] << 16;
		str_append_c (output, alphabet[(group >> 18) & 63]);
		str_append_c (output, alphabet[(group >> 12) & 63]);
		str_append_c (output, '=');
		str_append_c (output, '=');
	default:
		break;
	}
}

// --- Utilities ---------------------------------------------------------------

static void
cstr_split (const char *s, const char *delimiters, bool ignore_empty,
	struct strv *out)
{
	const char *begin = s, *end;
	while ((end = strpbrk (begin, delimiters)))
	{
		if (!ignore_empty || begin != end)
			strv_append_owned (out, xstrndup (begin, end - begin));
		begin = ++end;
	}
	if (!ignore_empty || *begin)
		strv_append (out, begin);
}

static char *
cstr_strip_in_place (char *s, const char *stripped_chars)
{
	char *end = s + strlen (s);
	while (end > s && strchr (stripped_chars, end[-1]))
		*--end = '\0';

	char *start = s + strspn (s, stripped_chars);
	if (start > s)
		memmove (s, start, end - start + 1);
	return s;
}

static void
cstr_transform (char *s, int (*tolower) (int c))
{
	for (; *s; s++)
		*s = tolower (*s);
}

static char *
cstr_cut_until (const char *s, const char *alphabet)
{
	return xstrndup (s, strcspn (s, alphabet));
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static char *
strv_join (const struct strv *v, const char *delimiter)
{
	if (!v->len)
		return xstrdup ("");

	struct str result;
	str_init (&result);
	str_append (&result, v->vector[0]);
	for (size_t i = 1; i < v->len; i++)
		str_append_printf (&result, "%s%s", delimiter, v->vector[i]);
	return str_steal (&result);
}

static char *xstrdup_printf (const char *, ...) ATTRIBUTE_PRINTF (1, 2);

static char *
xstrdup_printf (const char *format, ...)
{
	va_list ap;
	struct str tmp;
	str_init (&tmp);
	va_start (ap, format);
	str_append_vprintf (&tmp, format, ap);
	va_end (ap);
	return str_steal (&tmp);
}

static char *
iconv_xstrdup (iconv_t conv, char *in, size_t in_len, size_t *out_len)
{
	char *buf, *buf_ptr;
	size_t out_left, buf_alloc;

	buf = buf_ptr = xmalloc (out_left = buf_alloc = 64);

	char *in_ptr = in;
	if (in_len == (size_t) -1)
		in_len = strlen (in) + 1;

	while (iconv (conv, (char **) &in_ptr, &in_len,
		(char **) &buf_ptr, &out_left) == (size_t) -1)
	{
		if (errno != E2BIG)
		{
			free (buf);
			return NULL;
		}
		out_left += buf_alloc;
		char *new_buf = xrealloc (buf, buf_alloc <<= 1);
		buf_ptr += new_buf - buf;
		buf = new_buf;
	}
	if (out_len)
		*out_len = buf_alloc - out_left;
	return buf;
}

static bool
set_boolean_if_valid (bool *out, const char *s)
{
	if      (!strcasecmp (s, "yes"))    *out = true;
	else if (!strcasecmp (s, "no"))     *out = false;
	else if (!strcasecmp (s, "on"))     *out = true;
	else if (!strcasecmp (s, "off"))    *out = false;
	else if (!strcasecmp (s, "true"))   *out = true;
	else if (!strcasecmp (s, "false"))  *out = false;
	else return false;

	return true;
}

static bool
xstrtoul (unsigned long *out, const char *s, int base)
{
	char *end;
	errno = 0;
	*out = strtoul (s, &end, base);
	return errno == 0 && !*end && end != s;
}

static bool
read_line (FILE *fp, struct str *s)
{
	int c;
	bool at_end = true;

	str_reset (s);
	while ((c = fgetc (fp)) != EOF)
	{
		at_end = false;
		if (c == '\r')
			continue;
		if (c == '\n')
			break;
		str_append_c (s, c);
	}

	return !at_end;
}

static char *
format_host_port_pair (const char *host, const char *port)
{
	// For when binding to the NULL address; would an asterisk be better?
	if (!host)
		host = "";

	// IPv6 addresses mess with the "colon notation"; let's go with RFC 2732
	if (strchr (host, ':'))
		return xstrdup_printf ("[%s]:%s", host, port);
	return xstrdup_printf ("%s:%s", host, port);
}

// --- File system -------------------------------------------------------------

static int
lock_pid_file (const char *path, struct error **e)
{
	// When using XDG_RUNTIME_DIR, the file needs to either have its
	// access time bumped every 6 hours, or have the sticky bit set
	int fd = open (path, O_RDWR | O_CREAT,
		S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH /* 644 */ | S_ISVTX /* sticky */);
	if (fd < 0)
	{
		error_set (e, "can't open `%s': %s", path, strerror (errno));
		return -1;
	}

	set_cloexec (fd);

	struct flock lock =
	{
		.l_type = F_WRLCK,
		.l_start = 0,
		.l_whence = SEEK_SET,
		.l_len = 0,
	};
	if (fcntl (fd, F_SETLK, &lock))
	{
		error_set (e, "can't lock `%s': %s", path, strerror (errno));
		xclose (fd);
		return -1;
	}

	struct str pid;
	str_init (&pid);
	str_append_printf (&pid, "%ld", (long) getpid ());

	if (ftruncate (fd, 0)
	 || write (fd, pid.str, pid.len) != (ssize_t) pid.len)
	{
		error_set (e, "can't write to `%s': %s", path, strerror (errno));
		xclose (fd);
		return -1;
	}
	str_free (&pid);

	// Intentionally not closing the file descriptor; it must stay alive
	// for the entire life of the application
	return fd;
}

static bool
ensure_directory_existence (const char *path, struct error **e)
{
	struct stat st;

	if (stat (path, &st))
	{
		if (mkdir (path, S_IRWXU | S_IRWXG | S_IRWXO))
		{
			return error_set (e, "cannot create directory `%s': %s",
				path, strerror (errno));
		}
	}
	else if (!S_ISDIR (st.st_mode))
	{
		return error_set (e, "cannot create directory `%s': %s",
			path, "file exists but is not a directory");
	}
	return true;
}

static bool
mkdir_with_parents (char *path, struct error **e)
{
	char *p = path;

	// XXX: This is prone to the TOCTTOU problem.  The solution would be to
	//   rewrite the function using the {mkdir,fstat}at() functions from
	//   POSIX.1-2008, ideally returning a file descriptor to the open
	//   directory, with the current code as a fallback.  Or to use chdir().
	while ((p = strchr (p + 1, '/')))
	{
		*p = '\0';
		bool success = ensure_directory_existence (path, e);
		*p = '/';

		if (!success)
			return false;
	}

	return ensure_directory_existence (path, e);
}

static bool
str_append_env_path (struct str *output, const char *var, bool only_absolute)
{
	const char *value = getenv (var);

	if (!value || (only_absolute && *value != '/'))
		return false;

	str_append (output, value);
	return true;
}

static void
get_xdg_home_dir (struct str *output, const char *var, const char *def)
{
	str_reset (output);
	if (!str_append_env_path (output, var, true))
	{
		str_append_env_path (output, "HOME", false);
		str_append_c (output, '/');
		str_append (output, def);
	}
}

static char *
resolve_relative_filename_generic
	(struct strv *paths, const char *tail, const char *filename)
{
	for (unsigned i = 0; i < paths->len; i++)
	{
		// As per XDG spec, relative paths are ignored
		if (*paths->vector[i] != '/')
			continue;

		char *file = xstrdup_printf
			("%s/%s%s", paths->vector[i], tail, filename);

		struct stat st;
		if (!stat (file, &st))
			return file;
		free (file);
	}
	return NULL;
}

static void
get_xdg_config_dirs (struct strv *out)
{
	struct str config_home;
	str_init (&config_home);
	get_xdg_home_dir (&config_home, "XDG_CONFIG_HOME", ".config");
	strv_append (out, config_home.str);
	str_free (&config_home);

	const char *xdg_config_dirs;
	if (!(xdg_config_dirs = getenv ("XDG_CONFIG_DIRS")))
		xdg_config_dirs = "/etc/xdg";
	cstr_split (xdg_config_dirs, ":", true, out);
}

static char *
resolve_relative_config_filename (const char *filename)
{
	struct strv paths;
	strv_init (&paths);
	get_xdg_config_dirs (&paths);
	char *result = resolve_relative_filename_generic
		(&paths, PROGRAM_NAME "/", filename);
	strv_free (&paths);
	return result;
}

static void
get_xdg_data_dirs (struct strv *out)
{
	struct str data_home;
	str_init (&data_home);
	get_xdg_home_dir (&data_home, "XDG_DATA_HOME", ".local/share");
	strv_append (out, data_home.str);
	str_free (&data_home);

	const char *xdg_data_dirs;
	if (!(xdg_data_dirs = getenv ("XDG_DATA_DIRS")))
		xdg_data_dirs = "/usr/local/share/:/usr/share/";
	cstr_split (xdg_data_dirs, ":", true, out);
}

static char *
resolve_relative_data_filename (const char *filename)
{
	struct strv paths;
	strv_init (&paths);
	get_xdg_data_dirs (&paths);
	char *result = resolve_relative_filename_generic
		(&paths, PROGRAM_NAME "/", filename);
	strv_free (&paths);
	return result;
}

static char *
resolve_relative_runtime_filename (const char *filename)
{
	struct str path;
	str_init (&path);

	const char *runtime_dir = getenv ("XDG_RUNTIME_DIR");
	if (runtime_dir && *runtime_dir == '/')
		str_append (&path, runtime_dir);
	else
		get_xdg_home_dir (&path, "XDG_DATA_HOME", ".local/share");
	str_append_printf (&path, "/%s/%s", PROGRAM_NAME, filename);

	// Try to create the file's ancestors;
	// typically the user will want to immediately create a file in there
	const char *last_slash = strrchr (path.str, '/');
	if (last_slash && last_slash != path.str)
	{
		char *copy = xstrndup (path.str, last_slash - path.str);
		(void) mkdir_with_parents (copy, NULL);
		free (copy);
	}
	return str_steal (&path);
}

static char *
try_expand_tilde (const char *filename)
{
	size_t until_slash = strcspn (filename, "/");
	if (!until_slash)
	{
		struct str expanded;
		str_init (&expanded);
		str_append_env_path (&expanded, "HOME", false);
		str_append (&expanded, filename);
		return str_steal (&expanded);
	}

	int buf_len = sysconf (_SC_GETPW_R_SIZE_MAX);
	if (buf_len < 0)
		buf_len = 1024;
	struct passwd pwd, *success = NULL;

	char *user = xstrndup (filename, until_slash);
	char *buf = xmalloc (buf_len);
	while (getpwnam_r (user, &pwd, buf, buf_len, &success) == ERANGE)
		buf = xrealloc (buf, buf_len <<= 1);
	free (user);

	char *result = NULL;
	if (success)
		result = xstrdup_printf ("%s%s", pwd.pw_dir, filename + until_slash);
	free (buf);
	return result;
}

static char *
resolve_filename (const char *filename, char *(*relative_cb) (const char *))
{
	// Absolute path is absolute
	if (*filename == '/')
		return xstrdup (filename);

	// We don't want to use wordexp() for this as it may execute /bin/sh
	if (*filename == '~')
	{
		// Paths to home directories ought to be absolute
		char *expanded = try_expand_tilde (filename + 1);
		if (expanded)
			return expanded;
		print_debug ("failed to expand the home directory in `%s'", filename);
	}
	return relative_cb (filename);
}

// --- OpenSSL -----------------------------------------------------------------

#ifdef LIBERTY_WANT_SSL

#define XSSL_ERROR_TRY_AGAIN INT_MAX

/// A small wrapper around SSL_get_error() to simplify further handling
static int
xssl_get_error (SSL *ssl, int result, const char **error_info)
{
	int error = SSL_get_error (ssl, result);
	switch (error)
	{
	case SSL_ERROR_NONE:
	case SSL_ERROR_ZERO_RETURN:
	case SSL_ERROR_WANT_READ:
	case SSL_ERROR_WANT_WRITE:
		return error;
	case SSL_ERROR_SYSCALL:
		if ((error = ERR_get_error ()))
			*error_info = ERR_reason_error_string (error);
		else if (result == 0)
			// An EOF that's not according to the protocol is still an EOF
			return SSL_ERROR_ZERO_RETURN;
		else
		{
			if (errno == EINTR)
				return XSSL_ERROR_TRY_AGAIN;
			*error_info = strerror (errno);
		}
		return SSL_ERROR_SSL;
	default:
		if ((error = ERR_get_error ()))
			*error_info = ERR_reason_error_string (error);
		else
			*error_info = "unknown error";
		return SSL_ERROR_SSL;
	}
}

#endif  // LIBERTY_WANT_SSL

// --- Regular expressions -----------------------------------------------------

static regex_t *
regex_compile (const char *regex, int flags, struct error **e)
{
	regex_t *re = xmalloc (sizeof *re);
	int err = regcomp (re, regex, flags);
	if (!err)
		return re;

	char buf[regerror (err, re, NULL, 0)];
	regerror (err, re, buf, sizeof buf);

	free (re);
	error_set (e, "%s: %s", "failed to compile regular expression", buf);
	return NULL;
}

static void
regex_free (void *regex)
{
	regfree (regex);
	free (regex);
}

// The cost of hashing a string is likely to be significantly smaller than that
// of compiling the whole regular expression anew, so here is a simple cache.
// Adding basic support for subgroups is easy: check `re_nsub' and output into
// a `struct strv' (if all we want is the substrings).

static void
regex_cache_init (struct str_map *cache)
{
	str_map_init (cache);
	cache->free = regex_free;
}

static bool
regex_cache_match (struct str_map *cache, const char *regex, int flags,
	const char *s, struct error **e)
{
	regex_t *re = str_map_find (cache, regex);
	if (!re)
	{
		re = regex_compile (regex, flags, e);
		if (!re)
			return false;
		str_map_set (cache, regex, re);
	}
	return regexec (re, s, 0, NULL, 0) != REG_NOMATCH;
}

// --- Simple file I/O ---------------------------------------------------------

static bool
read_file (const char *filename, struct str *output, struct error **e)
{
	FILE *fp = fopen (filename, "rb");
	if (!fp)
	{
		return error_set (e, "could not open `%s' for reading: %s",
			filename, strerror (errno));
	}

	char buf[BUFSIZ];
	size_t len;

	while ((len = fread (buf, 1, sizeof buf, fp)) == sizeof buf)
		str_append_data (output, buf, len);
	str_append_data (output, buf, len);

	bool success = !ferror (fp);
	fclose (fp);

	if (success)
		return true;

	return error_set (e, "error while reading `%s': %s",
		filename, strerror (errno));
}

/// Overwrites filename contents with data; creates directories as needed
static bool
write_file (const char *filename, const void *data, size_t data_len,
	struct error **e)
{
	char *dir = xstrdup (filename);
	bool parents_created = mkdir_with_parents (dirname (dir), e);
	free (dir);
	if (!parents_created)
		return false;

	FILE *fp = fopen (filename, "w");
	if (!fp)
	{
		return error_set (e, "could not open `%s' for writing: %s",
			filename, strerror (errno));
	}

	fwrite (data, data_len, 1, fp);
	bool success = !ferror (fp) && !fflush (fp)
		&& (!fsync (fileno (fp)) || errno == EINVAL);
	fclose (fp);

	if (!success)
	{
		return error_set (e, "writing to `%s' failed: %s",
			filename, strerror (errno));
	}
	return true;
}

/// Wrapper for write_file() that makes sure that the new data has been written
/// to disk in its entirety before overriding the old file
static bool
write_file_safe (const char *filename, const void *data, size_t data_len,
	struct error **e)
{
	// XXX: ideally we would also open the directory, use *at() versions
	//   of functions and call fsync() on the directory as appropriate
	char *temp = xstrdup_printf ("%s.new", filename);
	bool success = write_file (temp, data, data_len, e);
	if (success && !(success = !rename (temp, filename)))
		error_set (e, "could not rename `%s' to `%s': %s",
			temp, filename, strerror (errno));
	free (temp);
	return success;
}

// --- Simple configuration ----------------------------------------------------

// The keys are stripped of surrounding whitespace, the values are not.

struct simple_config_item
{
	const char *key;
	const char *default_value;
	const char *description;
};

static void
simple_config_load_defaults
	(struct str_map *config, const struct simple_config_item *table)
{
	for (; table->key != NULL; table++)
		if (table->default_value)
			str_map_set (config, table->key, xstrdup (table->default_value));
		else
			str_map_set (config, table->key, NULL);
}

static bool
simple_config_update_from_file (struct str_map *config, struct error **e)
{
	char *filename = resolve_filename
		(PROGRAM_NAME ".conf", resolve_relative_config_filename);
	if (!filename)
		return true;

	FILE *fp = fopen (filename, "r");
	if (!fp)
	{
		error_set (e, "could not open `%s' for reading: %s",
			filename, strerror (errno));
		free (filename);
		return false;
	}

	struct str line;
	str_init (&line);

	bool errors = false;
	for (unsigned line_no = 1; read_line (fp, &line); line_no++)
	{
		char *start = line.str;
		if (*start == '#')
			continue;

		while (isspace (*start))
			start++;

		char *end = strchr (start, '=');
		if (end)
		{
			char *value = end + 1;
			do
				*end = '\0';
			while (isspace (*--end));

			str_map_set (config, start, xstrdup (value));
		}
		else if (*start)
		{
			error_set (e, "line %u in config: %s", line_no, "malformed input");
			errors = true;
			break;
		}
	}

	str_free (&line);
	fclose (fp);
	free (filename);
	return !errors;
}

static char *
write_configuration_file (const char *path_hint, const struct str *data,
	struct error **e)
{
	struct str path;
	str_init (&path);

	if (path_hint)
		str_append (&path, path_hint);
	else
	{
		get_xdg_home_dir (&path, "XDG_CONFIG_HOME", ".config");
		str_append (&path, "/" PROGRAM_NAME "/" PROGRAM_NAME ".conf");
	}

	if (!write_file_safe (path.str, data->str, data->len, e))
	{
		str_free (&path);
		return NULL;
	}
	return str_steal (&path);
}

static char *
simple_config_write_default (const char *path_hint, const char *prolog,
	const struct simple_config_item *table, struct error **e)
{
	struct str data;
	str_init (&data);

	if (prolog)
		str_append (&data, prolog);

	for (; table->key != NULL; table++)
	{
		str_append_printf (&data, "# %s\n", table->description);
		if (table->default_value)
			str_append_printf (&data, "%s=%s\n",
				table->key, table->default_value);
		else
			str_append_printf (&data, "#%s=\n", table->key);
	}

	char *path = write_configuration_file (path_hint, &data, e);
	str_free (&data);
	return path;
}

/// Convenience wrapper suitable for most simple applications
static void
call_simple_config_write_default
	(const char *path_hint, const struct simple_config_item *table)
{
	static const char *prolog =
	"# " PROGRAM_NAME " " PROGRAM_VERSION " configuration file\n"
	"#\n"
	"# Relative paths are searched for in ${XDG_CONFIG_HOME:-~/.config}\n"
	"# /" PROGRAM_NAME " as well as in $XDG_CONFIG_DIRS/" PROGRAM_NAME "\n"
	"\n";

	struct error *e = NULL;
	char *filename = simple_config_write_default (path_hint, prolog, table, &e);
	if (!filename)
	{
		print_error ("%s", e->message);
		error_free (e);
		exit (EXIT_FAILURE);
	}
	print_status ("configuration written to `%s'", filename);
	free (filename);
}

// --- Option handler ----------------------------------------------------------

// Simple wrapper for the getopt_long API to make it easier to use and maintain.

#define OPT_USAGE_ALIGNMENT_COLUMN 30   ///< Alignment for option descriptions

enum
{
	OPT_OPTIONAL_ARG  = (1 << 0),       ///< The argument is optional
	OPT_LONG_ONLY     = (1 << 1)        ///< Ignore the short name in opt_string
};

// All options need to have both a short name, and a long name.  The short name
// is what is returned from opt_handler_get().  It is possible to define a value
// completely out of the character range combined with the OPT_LONG_ONLY flag.
//
// When `arg_hint' is defined, the option is assumed to have an argument.

struct opt
{
	int short_name;                     ///< The single-letter name
	const char *long_name;              ///< The long name
	const char *arg_hint;               ///< Option argument hint
	int flags;                          ///< Option flags
	const char *description;            ///< Option description
};

struct opt_handler
{
	int argc;                           ///< The number of program arguments
	char **argv;                        ///< Program arguments

	const char *arg_hint;               ///< Program arguments hint
	const char *description;            ///< Description of the program

	const struct opt *opts;             ///< The list of options
	size_t opts_len;                    ///< The length of the option array

	struct option *options;             ///< The list of options for getopt
	char *opt_string;                   ///< The `optstring' for getopt
};

static void
opt_handler_free (struct opt_handler *self)
{
	free (self->options);
	free (self->opt_string);
}

static void
opt_handler_init (struct opt_handler *self, int argc, char **argv,
	const struct opt *opts, const char *arg_hint, const char *description)
{
	memset (self, 0, sizeof *self);
	self->argc = argc;
	self->argv = argv;
	self->arg_hint = arg_hint;
	self->description = description;

	size_t len = 0;
	for (const struct opt *iter = opts; iter->long_name; iter++)
		len++;

	self->opts = opts;
	self->opts_len = len;
	self->options = xcalloc (len + 1, sizeof *self->options);

	struct str opt_string;
	str_init (&opt_string);

	for (size_t i = 0; i < len; i++)
	{
		const struct opt *opt = opts + i;
		struct option *mapped = self->options + i;

		mapped->name = opt->long_name;
		if (!opt->arg_hint)
			mapped->has_arg = no_argument;
		else if (opt->flags & OPT_OPTIONAL_ARG)
			mapped->has_arg = optional_argument;
		else
			mapped->has_arg = required_argument;
		mapped->val = opt->short_name;

		if (opt->flags & OPT_LONG_ONLY)
			continue;

		str_append_c (&opt_string, opt->short_name);
		if (opt->arg_hint)
		{
			str_append_c (&opt_string, ':');
			if (opt->flags & OPT_OPTIONAL_ARG)
				str_append_c (&opt_string, ':');
		}
	}

	self->opt_string = str_steal (&opt_string);
}

static void
opt_handler_usage (const struct opt_handler *self, FILE *stream)
{
	struct str usage;
	str_init (&usage);

	str_append_printf (&usage, "Usage: %s [OPTION]... %s\n",
		self->argv[0], self->arg_hint ? self->arg_hint : "");
	str_append_printf (&usage, "%s\n\n", self->description);

	for (size_t i = 0; i < self->opts_len; i++)
	{
		struct str row;
		str_init (&row);

		const struct opt *opt = self->opts + i;
		if (!(opt->flags & OPT_LONG_ONLY))
			str_append_printf (&row, "  -%c, ", opt->short_name);
		else
			str_append (&row, "      ");
		str_append_printf (&row, "--%s", opt->long_name);
		if (opt->arg_hint)
			str_append_printf (&row, (opt->flags & OPT_OPTIONAL_ARG)
				? " [%s]" : " %s", opt->arg_hint);

		// TODO: keep the indent if there are multiple lines
		if (row.len + 2 <= OPT_USAGE_ALIGNMENT_COLUMN)
		{
			str_append (&row, "  ");
			str_append_printf (&usage, "%-*s%s\n",
				OPT_USAGE_ALIGNMENT_COLUMN, row.str, opt->description);
		}
		else
			str_append_printf (&usage, "%s\n%-*s%s\n", row.str,
				OPT_USAGE_ALIGNMENT_COLUMN, "", opt->description);

		str_free (&row);
	}

	fputs (usage.str, stream);
	str_free (&usage);
}

static int
opt_handler_get (const struct opt_handler *self)
{
	return getopt_long (self->argc, self->argv,
		self->opt_string, self->options, NULL);
}

// --- Unit tests --------------------------------------------------------------

// This is modeled after GTest, only remarkably simpler.

typedef void (*test_fn) (const void *data, void *fixture);

struct test_unit
{
	LIST_HEADER (struct test_unit)

	char *name;                         ///< Name of the test
	size_t fixture_size;                ///< Fixture size
	const void *user_data;              ///< User data

	test_fn setup;                      ///< Fixture setup callback
	test_fn test;                       ///< The test
	test_fn teardown;                   ///< Fixture teardown callback
};

struct test
{
	struct test_unit *tests;            ///< List of tests
	struct test_unit *tests_tail;       ///< End of the list of tests

	struct str_map whitelist;           ///< Whitelisted tests
	struct str_map blacklist;           ///< Blacklisted tests

	unsigned list_only : 1;             ///< Just list all tests
	unsigned can_fork  : 1;             ///< Forking doesn't break anything
};

static void
test_init (struct test *self, int argc, char **argv)
{
	memset (self, 0, sizeof *self);
	str_map_init (&self->whitelist);
	str_map_init (&self->blacklist);

	// Usually this shouldn't pose a problem but let's make it optional
	self->can_fork = true;

	static const struct opt opts[] =
	{
		{ 'd', "debug", NULL, 0, "run in debug mode" },
		{ 'h', "help", NULL, 0, "display this help and exit" },
		{ 'p', "pass", "NAME", 0, "only run tests glob-matching the name" },
		{ 's', "skip", "NAME", 0, "skip all tests glob-matching the name" },
		{ 'S', "single-process", NULL, 0, "don't fork for each test" },
		{ 'l', "list", NULL, 0, "list all available tests" },
		{ 0, NULL, NULL, 0, NULL }
	};

	struct opt_handler oh;
	opt_handler_init (&oh, argc, argv, opts, NULL, "Unit test runner");

	int c;
	while ((c = opt_handler_get (&oh)) != -1)
	switch (c)
	{
	case 'd':
		g_debug_mode = true;
		break;
	case 'h':
		opt_handler_usage (&oh, stdout);
		exit (EXIT_SUCCESS);
	case 'p':
		str_map_set (&self->whitelist, optarg, (void *) 1);
		break;
	case 's':
		str_map_set (&self->blacklist, optarg, (void *) 1);
		break;

	case 'S':  self->can_fork = false;  break;
	case 'l':  self->list_only = true;  break;

	default:
		print_error ("wrong options");
		opt_handler_usage (&oh, stderr);
		exit (EXIT_FAILURE);
	}

	argc -= optind;
	argv += optind;

	if (argc)
	{
		opt_handler_usage (&oh, stderr);
		exit (EXIT_FAILURE);
	}

	opt_handler_free (&oh);
}

static void
test_add_internal (struct test *self, const char *name, size_t fixture_size,
	const void *user_data, test_fn setup, test_fn test, test_fn teardown)
{
	hard_assert (test != NULL);
	hard_assert (name != NULL);

	struct test_unit *unit = xcalloc (1, sizeof *unit);
	unit->name = xstrdup (name);
	unit->fixture_size = fixture_size;
	unit->user_data = user_data;

	unit->setup = setup;
	unit->test = test;
	unit->teardown = teardown;

	LIST_APPEND_WITH_TAIL (self->tests, self->tests_tail, unit);
}

#define test_add(self, name, fixture_type, user_data, setup, test, teardown)   \
	test_add_internal ((self), (name), sizeof (fixture_type), (user_data),     \
		(test_fn) (setup), (test_fn) (test), (test_fn) (teardown))

#define test_add_simple(self, name, user_data, test)                           \
	test_add_internal ((self), (name), 0, (user_data),                         \
		NULL, (test_fn) (test), NULL)

static bool
str_map_glob_match (struct str_map *self, const char *entry)
{
	struct str_map_iter iter;
	str_map_iter_init (&iter, self);
	while (str_map_iter_next (&iter))
		if (!fnmatch (iter.link->key, entry, 0))
			return true;
	return false;
}

static bool
test_is_allowed (struct test *self, const char *name)
{
	bool allowed = true;
	if (self->whitelist.len)
		allowed  =  str_map_glob_match (&self->whitelist, name);
	if (self->blacklist.len)
		allowed &= !str_map_glob_match (&self->blacklist, name);
	return allowed;
}

static void
test_unit_run (struct test_unit *self)
{
	void *fixture = xcalloc (1, self->fixture_size);
	if (self->setup)
		self->setup (self->user_data, fixture);

	self->test (self->user_data, fixture);

	if (self->teardown)
		self->teardown (self->user_data, fixture);
	free (fixture);
}

static bool
test_unit_run_forked (struct test_unit *self)
{
	pid_t child = fork ();
	if (child == -1)
	{
		print_error ("%s: %s", "fork", strerror (errno));
		return false;
	}
	else if (!child)
	{
		test_unit_run (self);
		_exit (EXIT_SUCCESS);
	}

	int status = 0;
	if (waitpid (child, &status, WUNTRACED) == -1)
		print_error ("%s: %s", "waitpid", strerror (errno));
	else if (WIFSTOPPED (status))
	{
		print_error ("test child has been stopped");
		(void) kill (child, SIGKILL);
	}
	else if (WIFSIGNALED (status))
		print_error ("test child was killed by signal %d", WTERMSIG (status));
	else if (WEXITSTATUS (status) != 0)
		print_error ("test child exited with status %d", WEXITSTATUS (status));
	else
		return true;
	return false;
}

static bool
test_run_unit (struct test *self, struct test_unit *unit)
{
	fprintf (stderr, "%s: ", unit->name);

	if (!self->can_fork)
		test_unit_run (unit);
	else if (!test_unit_run_forked (unit))
		return false;

	fprintf (stderr, "OK\n");
	return true;
}

static int
test_run (struct test *self)
{
	g_soft_asserts_are_deadly = true;

	bool failure = false;
	LIST_FOR_EACH (struct test_unit, iter, self->tests)
	{
		if (!test_is_allowed (self, iter->name))
			continue;
		if (self->list_only)
			printf ("%s\n", iter->name);
		else if (!test_run_unit (self, iter))
			failure = true;
	}

	LIST_FOR_EACH (struct test_unit, iter, self->tests)
	{
		free (iter->name);
		free (iter);
	}

	str_map_free (&self->whitelist);
	str_map_free (&self->blacklist);
	return failure;
}

// --- Connector ---------------------------------------------------------------

#if defined LIBERTY_WANT_POLLER && defined LIBERTY_WANT_ASYNC

// This is a helper that tries to establish a connection with any address on
// a given list.  Sadly it also introduces a bit of a callback hell.

struct connector_target
{
	LIST_HEADER (struct connector_target)
	struct connector *connector;        ///< Parent connector

	char *hostname;                     ///< Target hostname or address
	char *service;                      ///< Target service name or port

	struct async *getaddrinfo_event;    ///< Address resolution
	struct error *getaddrinfo_error;    ///< Address resolution error

	struct addrinfo *results;           ///< Resolved target
	struct addrinfo *iter;              ///< Current endpoint
};

static struct connector_target *
connector_target_new (void)
{
	struct connector_target *self = xcalloc (1, sizeof *self);
	return self;
}

static void
connector_target_destroy (struct connector_target *self)
{
	if (self->getaddrinfo_event)
		async_cancel (self->getaddrinfo_event);
	if (self->getaddrinfo_error)
		error_free (self->getaddrinfo_error);
	if (self->results)
		freeaddrinfo (self->results);

	free (self->hostname);
	free (self->service);
	free (self);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

struct connector
{
	struct poller *poller;              ///< Poller
	int socket;                         ///< Socket FD for the connection
	struct poller_fd connected_event;   ///< We've connected or failed
	struct connector_target *targets;   ///< Targets
	struct connector_target *targets_t; ///< Tail of targets

	void *user_data;                    ///< User data for callbacks

	// You may destroy the connector object in these two main callbacks:

	/// Connection has been successfully established;
	/// the hostname is mainly intended for TLS Server Name Indication
	void (*on_connected) (void *user_data, int socket, const char *hostname);
	/// Failed to establish a connection to either target
	void (*on_failure) (void *user_data);

	// Optional:

	/// Connecting to a new address
	void (*on_connecting) (void *user_data, const char *address);
	/// Connecting to the last address has failed
	void (*on_error) (void *user_data, const char *error);
};

static void
connector_notify_connecting (struct connector *self,
	struct connector_target *target, struct addrinfo *gai_iter)
{
	if (!self->on_connecting)
		return;

	const char *real_host = target->hostname;
	char buf[NI_MAXHOST];

	if (gai_iter)
	{
		// We don't really need this, so we can let it quietly fail
		int err = getnameinfo (gai_iter->ai_addr, gai_iter->ai_addrlen,
			buf, sizeof buf, NULL, 0, NI_NUMERICHOST);
		if (err)
			LOG_FUNC_FAILURE ("getnameinfo", gai_strerror (err));
		else
			real_host = buf;
	}

	char *address = format_host_port_pair (real_host, target->service);
	self->on_connecting (self->user_data, address);
	free (address);
}

static void
connector_notify_connected (struct connector *self, int fd)
{
	set_blocking (fd, true);
	self->on_connected (self->user_data, fd, self->targets->hostname);
}

static void
connector_prepare_next (struct connector *self)
{
	struct connector_target *target = self->targets;
	if (!target->iter || !(target->iter = target->iter->ai_next))
	{
		LIST_UNLINK_WITH_TAIL (self->targets, self->targets_t, target);
		connector_target_destroy (target);
	}
}

static void connector_handle_error (struct connector *self, const char *error);

/// See if there's any target remaining at all -- it can however either still
/// be waiting for address resolution to finish, or have already failed
static bool
connector_check_target (struct connector *self, struct connector_target *target)
{
	if (!target)
		self->on_failure (self->user_data);
	else if (target->getaddrinfo_error)
	{
		connector_notify_connecting (self, target, NULL);
		connector_handle_error (self, target->getaddrinfo_error->message);
	}
	else if (target->results)
		return true;
	return false;
}

static void
connector_step (struct connector *self)
{
	struct connector_target *target = self->targets;
	if (!connector_check_target (self, target))
		return;

	struct addrinfo *gai_iter = target->iter;
	hard_assert (gai_iter != NULL);

	connector_notify_connecting (self, target, gai_iter);

	int fd = socket (gai_iter->ai_family,
		gai_iter->ai_socktype, gai_iter->ai_protocol);
	if (fd == -1)
	{
		connector_handle_error (self, strerror (errno));
		return;
	}

	set_cloexec (fd);
	set_blocking (fd, false);

	int yes = 1;
	soft_assert (setsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
		&yes, sizeof yes) != -1);

	if (!connect (fd, gai_iter->ai_addr, gai_iter->ai_addrlen))
		connector_notify_connected (self, fd);
	else if (errno == EINPROGRESS)
	{
		self->connected_event.fd = self->socket = fd;
		poller_fd_set (&self->connected_event, POLLOUT);
	}
	else
	{
		connector_handle_error (self, strerror (errno));
		xclose (fd);
	}
}

static void
connector_handle_error (struct connector *self, const char *error)
{
	if (self->on_error)
		self->on_error (self->user_data, error);

	connector_prepare_next (self);
	connector_step (self);
}

static void
connector_on_ready (const struct pollfd *pfd, struct connector *self)
{
	// See http://cr.yp.to/docs/connect.html if this doesn't work.
	// The second connect() method doesn't work with DragonflyBSD.

	int error = 0;
	socklen_t error_len = sizeof error;
	hard_assert (!getsockopt (pfd->fd,
		SOL_SOCKET, SO_ERROR, &error, &error_len));

	if (error)
	{
		poller_fd_reset (&self->connected_event);
		xclose (self->socket);
		self->socket = -1;

		connector_handle_error (self, strerror (error));
	}
	else
	{
		poller_fd_reset (&self->connected_event);
		self->socket = -1;
		connector_notify_connected (self, pfd->fd);
	}
}

static void
connector_init (struct connector *self, struct poller *poller)
{
	memset (self, 0, sizeof *self);
	self->poller = poller;
	self->socket = -1;
	poller_fd_init (&self->connected_event, poller, self->socket);
	self->connected_event.user_data = self;
	self->connected_event.dispatcher = (poller_fd_fn) connector_on_ready;
}

static void
connector_free (struct connector *self)
{
	poller_fd_reset (&self->connected_event);
	if (self->socket != -1)
		xclose (self->socket);

	LIST_FOR_EACH (struct connector_target, iter, self->targets)
		connector_target_destroy (iter);
}

static void
connector_on_getaddrinfo (int err, struct addrinfo *results, void *user_data)
{
	struct connector_target *self = user_data;

	if (err)
	{
		error_set (&self->getaddrinfo_error,
			"%s: %s", "getaddrinfo", gai_strerror (err));
	}

	self->results = self->iter = results;
	self->getaddrinfo_event = NULL;

	// We've been waiting for this address to be resolved
	if (self == self->connector->targets)
		connector_step (self->connector);
}

/// Connection will be attempted asynchronously once you add any target
static void
connector_add_target (struct connector *self,
	const char *hostname, const char *service)
{
	struct connector_target *target = connector_target_new ();
	target->connector = self;
	target->hostname = xstrdup (hostname);
	target->service = xstrdup (service);

	struct addrinfo hints;
	memset (&hints, 0, sizeof hints);
	hints.ai_socktype = SOCK_STREAM;

	struct async_getaddrinfo *gai = async_getaddrinfo
		(&self->poller->common.async, hostname, service, &hints);

	gai->dispatcher = connector_on_getaddrinfo;
	gai->user_data = target;
	target->getaddrinfo_event = &gai->async;

	LIST_APPEND_WITH_TAIL (self->targets, self->targets_t, target);
}

#endif // defined LIBERTY_WANT_POLLER && defined LIBERTY_WANT_ASYNC

// --- Simple network I/O ------------------------------------------------------

enum socket_io_result
{
	SOCKET_IO_OK = 0,                   ///< Completed successfully
	SOCKET_IO_EOF,                      ///< Connection shut down by peer
	SOCKET_IO_ERROR                     ///< Connection error
};

static enum socket_io_result
socket_io_try_read (int socket_fd, struct str *rb)
{
	// Flood protection, cannot afford to read too much at once
	size_t read_limit = rb->len + (1 << 20);
	if (read_limit < rb->len)
		read_limit = SIZE_MAX;

	ssize_t n_read;
	while (rb->len < read_limit)
	{
		str_reserve (rb, 1024);
		n_read = read (socket_fd, rb->str + rb->len,
			rb->alloc - rb->len - 1 /* null byte */);

		if (n_read > 0)
		{
			rb->str[rb->len += n_read] = '\0';
			continue;
		}
		if (n_read == 0)
			return SOCKET_IO_EOF;

		if (errno == EAGAIN)
			return SOCKET_IO_OK;
		if (errno == EINTR)
			continue;

		int errno_save = errno;
		LOG_LIBC_FAILURE ("read");
		errno = errno_save;
		return SOCKET_IO_ERROR;
	}
	return SOCKET_IO_OK;
}

static enum socket_io_result
socket_io_try_write (int socket_fd, struct str *wb)
{
	ssize_t n_written;
	while (wb->len)
	{
		n_written = write (socket_fd, wb->str, wb->len);
		if (n_written >= 0)
		{
			str_remove_slice (wb, 0, n_written);
			continue;
		}

		if (errno == EAGAIN)
			return SOCKET_IO_OK;
		if (errno == EINTR)
			continue;

		int errno_save = errno;
		LOG_LIBC_FAILURE ("write");
		errno = errno_save;
		return SOCKET_IO_ERROR;
	}
	return SOCKET_IO_OK;
}

// --- Advanced configuration --------------------------------------------------

// This is a more powerful configuration format, adding key-value maps and
// simplifying item validation and dynamic handling of changes.  All strings
// must be encoded in UTF-8.

enum config_item_type
{
	CONFIG_ITEM_NULL,                   ///< No value
	CONFIG_ITEM_OBJECT,                 ///< Key-value map
	CONFIG_ITEM_BOOLEAN,                ///< Truth value
	CONFIG_ITEM_INTEGER,                ///< Integer
	CONFIG_ITEM_STRING,                 ///< Arbitrary string of characters
	CONFIG_ITEM_STRING_ARRAY            ///< Comma-separated list of strings
};

struct config_item
{
	enum config_item_type type;         ///< Type of the item
	union
	{
		struct str_map object;          ///< Key-value data
		bool boolean;                   ///< Boolean data
		int64_t integer;                ///< Integer data
		struct str string;              ///< String data
	}
	value;                              ///< The value of this item

	struct config_schema *schema;       ///< Schema describing this value
	void *user_data;                    ///< User value attached by schema owner
};

struct config_schema
{
	const char *name;                   ///< Name of the item
	const char *comment;                ///< User-readable description

	enum config_item_type type;         ///< Required type
	const char *default_;               ///< Default as a configuration snippet

	/// Check if the new value can be accepted.
	/// In addition to this, "type" and having a default is considered.
	bool (*validate) (const struct config_item *, struct error **e);

	/// The value has changed
	void (*on_change) (struct config_item *);
};

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static const char *
config_item_type_name (enum config_item_type type)
{
	switch (type)
	{
	case CONFIG_ITEM_NULL:          return "null";
	case CONFIG_ITEM_BOOLEAN:       return "boolean";
	case CONFIG_ITEM_INTEGER:       return "integer";
	case CONFIG_ITEM_STRING:        return "string";
	case CONFIG_ITEM_STRING_ARRAY:  return "string array";

	default:
		hard_assert (!"invalid config item type value");
		return NULL;
	}
}

static bool
config_item_type_is_string (enum config_item_type type)
{
	return type == CONFIG_ITEM_STRING
		|| type == CONFIG_ITEM_STRING_ARRAY;
}

static void
config_item_free (struct config_item *self)
{
	switch (self->type)
	{
	case CONFIG_ITEM_STRING:
	case CONFIG_ITEM_STRING_ARRAY:
		str_free (&self->value.string);
		break;
	case CONFIG_ITEM_OBJECT:
		str_map_free (&self->value.object);
	default:
		break;
	}
}

static void
config_item_destroy (struct config_item *self)
{
	config_item_free (self);
	free (self);
}

/// Doesn't do any validations or handle schemas, just moves source data
/// to the target item and destroys the source item
static void
config_item_move (struct config_item *self, struct config_item *source)
{
	// Not quite sure how to handle that
	hard_assert (!source->schema);

	config_item_free (self);
	self->type = source->type;
	memcpy (&self->value, &source->value, sizeof source->value);
	free (source);
}

static struct config_item *
config_item_new (enum config_item_type type)
{
	struct config_item *self = xcalloc (1, sizeof *self);
	self->type = type;
	return self;
}

static struct config_item *
config_item_null (void)
{
	return config_item_new (CONFIG_ITEM_NULL);
}

static struct config_item *
config_item_boolean (bool b)
{
	struct config_item *self = config_item_new (CONFIG_ITEM_BOOLEAN);
	self->value.boolean = b;
	return self;
}

static struct config_item *
config_item_integer (int64_t i)
{
	struct config_item *self = config_item_new (CONFIG_ITEM_INTEGER);
	self->value.integer = i;
	return self;
}

static struct config_item *
config_item_string (const struct str *s)
{
	struct config_item *self = config_item_new (CONFIG_ITEM_STRING);
	str_init (&self->value.string);
	hard_assert (utf8_validate
		(self->value.string.str, self->value.string.len));
	if (s) str_append_str (&self->value.string, s);
	return self;
}

static struct config_item *
config_item_string_from_cstr (const char *s)
{
	struct str tmp;
	str_init (&tmp);
	str_append (&tmp, s);
	struct config_item *self = config_item_string (&tmp);
	str_free (&tmp);
	return self;
}

static struct config_item *
config_item_string_array (const struct str *s)
{
	struct config_item *self = config_item_string (s);
	self->type = CONFIG_ITEM_STRING_ARRAY;
	return self;
}

static struct config_item *
config_item_object (void)
{
	struct config_item *self = config_item_new (CONFIG_ITEM_OBJECT);
	str_map_init (&self->value.object);
	self->value.object.free = (void (*)(void *)) config_item_destroy;
	return self;
}

static bool
config_schema_accepts_type
	(struct config_schema *self, enum config_item_type type)
{
	if (self->type == type)
		return true;
	// This is a bit messy but it has its purpose
	if (config_item_type_is_string (self->type)
	 && config_item_type_is_string (type))
		return true;
	return !self->default_ && type == CONFIG_ITEM_NULL;
}

static bool
config_item_validate_by_schema (struct config_item *self,
	struct config_schema *schema, struct error **e)
{
	struct error *error = NULL;
	if (!config_schema_accepts_type (schema, self->type))
		error_set (e, "invalid type of value, expected: %s%s",
			config_item_type_name (schema->type),
			!schema->default_ ? " (or null)" : "");
	else if (schema->validate && !schema->validate (self, &error))
	{
		error_set (e, "%s: %s", "invalid value", error->message);
		error_free (error);
	}
	else
		return true;
	return false;
}

static bool
config_item_set_from (struct config_item *self, struct config_item *source,
	struct error **e)
{
	struct config_schema *schema = self->schema;
	if (!schema)
	{
		// Easy, we don't know what this item is
		config_item_move (self, source);
		return true;
	}

	source->user_data = self->user_data;
	if (!config_item_validate_by_schema (source, schema, e))
		return false;

	// Make sure the string subtype fits the schema
	if (config_item_type_is_string (source->type)
	 && config_item_type_is_string (schema->type))
		source->type = schema->type;

	config_item_move (self, source);

	// Notify owner about the change so that they can apply it
	if (schema->on_change)
		schema->on_change (self);
	return true;
}

static struct config_item *
config_item_get (struct config_item *self, const char *path, struct error **e)
{
	hard_assert (self->type == CONFIG_ITEM_OBJECT);

	struct strv v;
	strv_init (&v);
	cstr_split (path, ".", false, &v);

	struct config_item *result = NULL;
	size_t i = 0;
	while (true)
	{
		const char *key = v.vector[i];
		if (!*key)
			error_set (e, "empty path element");
		else if (!(self = str_map_find (&self->value.object, key)))
			error_set (e, "`%s' not found in object", key);
		else if (++i == v.len)
			result = self;
		else if (self->type != CONFIG_ITEM_OBJECT)
			error_set (e, "`%s' is not an object", key);
		else
			continue;
		break;
	}
	strv_free (&v);
	return result;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

struct config_writer
{
	struct str *output;
	unsigned indent;
};

static void config_item_write_object_innards
	(struct config_writer *self, struct config_item *object);

static void
config_item_write_string (struct str *output, const struct str *s)
{
	str_append_c (output, '"');
	for (size_t i = 0; i < s->len; i++)
	{
		unsigned char c = s->str[i];
		if      (c == '\n')  str_append        (output, "\\n");
		else if (c == '\r')  str_append        (output, "\\r");
		else if (c == '\t')  str_append        (output, "\\t");
		else if (c == '\\')  str_append        (output, "\\\\");
		else if (c == '"')   str_append        (output, "\\\"");
		else if (c < 32)     str_append_printf (output, "\\x%02x", c);
		else                 str_append_c      (output, c);
	}
	str_append_c (output, '"');
}

static void
config_item_write_object
	(struct config_writer *self, struct config_item *value)
{
	char indent[self->indent + 1];
	memset (indent, '\t', self->indent);
	indent[self->indent] = 0;

	str_append_c (self->output, '{');
	if (value->value.object.len)
	{
		self->indent++;
		str_append_c (self->output, '\n');
		config_item_write_object_innards (self, value);
		self->indent--;
		str_append (self->output, indent);
	}
	str_append_c (self->output, '}');
}

static void
config_item_write_value (struct config_writer *self, struct config_item *value)
{
	switch (value->type)
	{
	case CONFIG_ITEM_NULL:
		str_append (self->output, "null");
		break;
	case CONFIG_ITEM_BOOLEAN:
		str_append (self->output, value->value.boolean ? "on" : "off");
		break;
	case CONFIG_ITEM_INTEGER:
		str_append_printf (self->output, "%" PRIi64, value->value.integer);
		break;
	case CONFIG_ITEM_STRING:
	case CONFIG_ITEM_STRING_ARRAY:
		config_item_write_string (self->output, &value->value.string);
		break;
	case CONFIG_ITEM_OBJECT:
		config_item_write_object (self, value);
		break;
	default:
		hard_assert (!"invalid item type");
	}
}

// FIXME: shuffle code so that this isn't needed (serializer after the parser)
static bool config_tokenizer_is_word_char (int c);

static void
config_item_write_kv_pair (struct config_writer *self,
	const char *key, struct config_item *value)
{
	char indent[self->indent + 1];
	memset (indent, '\t', self->indent);
	indent[self->indent] = 0;

	if (value->schema && value->schema->comment)
		str_append_printf (self->output,
			"%s# %s\n", indent, value->schema->comment);

	bool can_use_word = true;
	for (const char *p = key; *p; p++)
		if (!config_tokenizer_is_word_char (*p))
			can_use_word = false;

	str_append (self->output, indent);
	if (can_use_word)
		str_append (self->output, key);
	else
	{
		struct str s = { .str = (char *) key, .len = strlen (key) };
		config_item_write_string (self->output, &s);
	}

	str_append (self->output, " = ");
	config_item_write_value (self, value);
	str_append_c (self->output, '\n');
}

static void
config_item_write_object_innards
	(struct config_writer *self, struct config_item *object)
{
	hard_assert (object->type == CONFIG_ITEM_OBJECT);

	struct str_map_iter iter;
	str_map_iter_init (&iter, &object->value.object);

	struct config_item *value;
	while ((value = str_map_iter_next (&iter)))
		config_item_write_kv_pair (self, iter.link->key, value);
}

static void
config_item_write (struct config_item *value,
	bool object_innards, struct str *output)
{
	struct config_writer writer = { .output = output, .indent = 0 };
	if (object_innards)
		config_item_write_object_innards (&writer, value);
	else
		config_item_write_value (&writer, value);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

enum config_token
{
	CONFIG_T_ABORT,                     ///< EOF or error

	CONFIG_T_WORD,                      ///< [a-zA-Z0-9_]+
	CONFIG_T_EQUALS,                    ///< Equal sign
	CONFIG_T_LBRACE,                    ///< Left curly bracket
	CONFIG_T_RBRACE,                    ///< Right curly bracket
	CONFIG_T_NEWLINE,                   ///< New line

	CONFIG_T_NULL,                      ///< CONFIG_ITEM_NULL
	CONFIG_T_BOOLEAN,                   ///< CONFIG_ITEM_BOOLEAN
	CONFIG_T_INTEGER,                   ///< CONFIG_ITEM_INTEGER
	CONFIG_T_STRING                     ///< CONFIG_ITEM_STRING{,_LIST}
};

static const char *
config_token_name (enum config_token token)
{
	switch (token)
	{
	case CONFIG_T_ABORT:    return "end of input";

	case CONFIG_T_WORD:     return "word";
	case CONFIG_T_EQUALS:   return "equal sign";
	case CONFIG_T_LBRACE:   return "left brace";
	case CONFIG_T_RBRACE:   return "right brace";
	case CONFIG_T_NEWLINE:  return "newline";

	case CONFIG_T_NULL:     return "null value";
	case CONFIG_T_BOOLEAN:  return "boolean";
	case CONFIG_T_INTEGER:  return "integer";
	case CONFIG_T_STRING:   return "string";

	default:
		hard_assert (!"invalid token value");
		return NULL;
	}
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

struct config_tokenizer
{
	const char *p;                      ///< Current position in input
	size_t len;                         ///< How many bytes of input are left

	bool report_line;                   ///< Whether to count lines at all
	unsigned line;                      ///< Current line
	unsigned column;                    ///< Current column

	int64_t integer;                    ///< Parsed boolean or integer value
	struct str string;                  ///< Parsed string value
};

/// Input has to be null-terminated anyway
static void
config_tokenizer_init (struct config_tokenizer *self, const char *p, size_t len)
{
	memset (self, 0, sizeof *self);
	self->p = p;
	self->len = len;
	self->report_line = true;
	str_init (&self->string);
}

static void
config_tokenizer_free (struct config_tokenizer *self)
{
	str_free (&self->string);
}

static bool
config_tokenizer_is_word_char (int c)
{
	return isalnum_ascii (c) || c == '_';
}

static int
config_tokenizer_advance (struct config_tokenizer *self)
{
	int c = *self->p++;
	if (c == '\n' && self->report_line)
	{
		self->column = 0;
		self->line++;
	}
	else
		self->column++;

	self->len--;
	return c;
}

static void config_tokenizer_error (struct config_tokenizer *self,
	struct error **e, const char *format, ...) ATTRIBUTE_PRINTF (3, 4);

static void
config_tokenizer_error (struct config_tokenizer *self,
	struct error **e, const char *format, ...)
{
	struct str description;
	str_init (&description);

	va_list ap;
	va_start (ap, format);
	str_append_vprintf (&description, format, ap);
	va_end (ap);

	if (self->report_line)
		error_set (e, "near line %u, column %u: %s",
			self->line + 1, self->column + 1, description.str);
	else if (self->len)
		error_set (e, "near character %u: %s",
			self->column + 1, description.str);
	else
		error_set (e, "near end: %s", description.str);

	str_free (&description);
}

static bool
config_tokenizer_hexa_escape (struct config_tokenizer *self, struct str *output)
{
	int i;
	unsigned char code = 0;

	for (i = 0; self->len && i < 2; i++)
	{
		unsigned char c = tolower_ascii (*self->p);
		if (c >= '0' && c <= '9')
			code = (code << 4) | (c - '0');
		else if (c >= 'a' && c <= 'f')
			code = (code << 4) | (c - 'a' + 10);
		else
			break;

		config_tokenizer_advance (self);
	}

	if (!i)
		return false;

	str_append_c (output, code);
	return true;
}

static bool
config_tokenizer_octal_escape
	(struct config_tokenizer *self, struct str *output)
{
	int i;
	unsigned char code = 0;

	for (i = 0; self->len && i < 3; i++)
	{
		unsigned char c = *self->p;
		if (c >= '0' && c <= '7')
			code = (code << 3) | (c - '0');
		else
			break;

		config_tokenizer_advance (self);
	}

	if (!i)
		return false;

	str_append_c (output, code);
	return true;
}

static bool
config_tokenizer_escape_sequence
	(struct config_tokenizer *self, struct str *output, struct error **e)
{
	if (!self->len)
	{
		config_tokenizer_error (self, e, "premature end of escape sequence");
		return false;
	}

	unsigned char c;
	switch ((c = *self->p))
	{
	case '"':              break;
	case '\\':             break;
	case 'a':   c = '\a';  break;
	case 'b':   c = '\b';  break;
	case 'f':   c = '\f';  break;
	case 'n':   c = '\n';  break;
	case 'r':   c = '\r';  break;
	case 't':   c = '\t';  break;
	case 'v':   c = '\v';  break;

	case 'x':
	case 'X':
		config_tokenizer_advance (self);
		if (config_tokenizer_hexa_escape (self, output))
			return true;

		config_tokenizer_error (self, e, "invalid hexadecimal escape");
		return false;

	default:
		if (config_tokenizer_octal_escape (self, output))
			return true;

		config_tokenizer_error (self, e, "unknown escape sequence");
		return false;
	}

	str_append_c (output, c);
	config_tokenizer_advance (self);
	return true;
}

static bool
config_tokenizer_string
	(struct config_tokenizer *self, struct str *output, struct error **e)
{
	unsigned char c;
	while (self->len)
	{
		if ((c = config_tokenizer_advance (self)) == '"')
			return true;
		if (c != '\\')
			str_append_c (output, c);
		else if (!config_tokenizer_escape_sequence (self, output, e))
			return false;
	}
	config_tokenizer_error (self, e, "premature end of string");
	return false;
}

static enum config_token
config_tokenizer_next (struct config_tokenizer *self, struct error **e)
{
	// Skip over any whitespace between tokens
	while (self->len && isspace_ascii (*self->p) && *self->p != '\n')
		config_tokenizer_advance (self);
	if (!self->len)
		return CONFIG_T_ABORT;

	switch (*self->p)
	{
	case '\n':  config_tokenizer_advance (self);  return CONFIG_T_NEWLINE;
	case '=':   config_tokenizer_advance (self);  return CONFIG_T_EQUALS;
	case '{':   config_tokenizer_advance (self);  return CONFIG_T_LBRACE;
	case '}':   config_tokenizer_advance (self);  return CONFIG_T_RBRACE;

	case '#':
		// Comments go until newline
		while (self->len)
			if (config_tokenizer_advance (self) == '\n')
				return CONFIG_T_NEWLINE;
		return CONFIG_T_ABORT;

	case '"':
		config_tokenizer_advance (self);
		str_reset (&self->string);
		if (!config_tokenizer_string (self, &self->string, e))
			return CONFIG_T_ABORT;
		if (!utf8_validate (self->string.str, self->string.len))
		{
			config_tokenizer_error (self, e, "not a valid UTF-8 string");
			return CONFIG_T_ABORT;
		}
		return CONFIG_T_STRING;
	}

	char *end;
	errno = 0;
	self->integer = strtoll (self->p, &end, 10);
	if (errno == ERANGE)
	{
		config_tokenizer_error (self, e, "integer out of range");
		return CONFIG_T_ABORT;
	}
	if (end != self->p)
	{
		self->len -= end - self->p;
		self->p = end;
		return CONFIG_T_INTEGER;
	}

	if (!config_tokenizer_is_word_char (*self->p))
	{
		config_tokenizer_error (self, e, "invalid input");
		return CONFIG_T_ABORT;
	}

	str_reset (&self->string);
	do
		str_append_c (&self->string, config_tokenizer_advance (self));
	while (config_tokenizer_is_word_char (*self->p));

	if (!strcmp (self->string.str, "null"))
		return CONFIG_T_NULL;

	bool boolean;
	if (!set_boolean_if_valid (&boolean, self->string.str))
		return CONFIG_T_WORD;

	self->integer = boolean;
	return CONFIG_T_BOOLEAN;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

struct config_parser
{
	struct config_tokenizer tokenizer;  ///< Tokenizer

	struct error *error;                ///< Tokenizer error
	enum config_token token;            ///< Current token in the tokenizer
	bool replace_token;                 ///< Replace the token
};

static void
config_parser_init (struct config_parser *self, const char *script, size_t len)
{
	memset (self, 0, sizeof *self);
	config_tokenizer_init (&self->tokenizer, script, len);

	// As reading in tokens may cause exceptions, we wait for the first peek()
	// to replace the initial CONFIG_T_ABORT.
	self->replace_token = true;
}

static void
config_parser_free (struct config_parser *self)
{
	config_tokenizer_free (&self->tokenizer);
	if (self->error)
		error_free (self->error);
}

static enum config_token
config_parser_peek (struct config_parser *self, jmp_buf out)
{
	if (self->replace_token)
	{
		self->token = config_tokenizer_next (&self->tokenizer, &self->error);
		if (self->error)
			longjmp (out, 1);
		self->replace_token = false;
	}
	return self->token;
}

static bool
config_parser_accept
	(struct config_parser *self, enum config_token token, jmp_buf out)
{
	return self->replace_token = (config_parser_peek (self, out) == token);
}

static void
config_parser_expect
	(struct config_parser *self, enum config_token token, jmp_buf out)
{
	if (config_parser_accept (self, token, out))
		return;

	config_tokenizer_error (&self->tokenizer, &self->error,
		"unexpected `%s', expected `%s'",
		config_token_name (self->token),
		config_token_name (token));
	longjmp (out, 1);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// We don't need no generator, but a few macros will come in handy.
// From time to time C just doesn't have the right features.

#define PEEK()         config_parser_peek   (self, err)
#define ACCEPT(token)  config_parser_accept (self, token, err)
#define EXPECT(token)  config_parser_expect (self, token, err)
#define SKIP_NL()      do {} while (ACCEPT (CONFIG_T_NEWLINE))

static struct config_item *config_parser_parse_object
	(struct config_parser *self, jmp_buf out);

static struct config_item *
config_parser_parse_value (struct config_parser *self, jmp_buf out)
{
	struct config_item *volatile result = NULL;
	jmp_buf err;

	if (setjmp (err))
	{
		if (result)
			config_item_destroy (result);
		longjmp (out, 1);
	}

	if (ACCEPT (CONFIG_T_LBRACE))
	{
		result = config_parser_parse_object (self, out);
		SKIP_NL ();
		EXPECT (CONFIG_T_RBRACE);
		return result;
	}
	if (ACCEPT (CONFIG_T_NULL))
		return config_item_null ();
	if (ACCEPT (CONFIG_T_BOOLEAN))
		return config_item_boolean (self->tokenizer.integer);
	if (ACCEPT (CONFIG_T_INTEGER))
		return config_item_integer (self->tokenizer.integer);
	if (ACCEPT (CONFIG_T_STRING))
		return config_item_string (&self->tokenizer.string);

	config_tokenizer_error (&self->tokenizer, &self->error,
		"unexpected `%s', expected a value",
		config_token_name (self->token));
	longjmp (out, 1);
}

/// Parse a single "key = value" assignment into @a object
static bool
config_parser_parse_kv_pair (struct config_parser *self,
	struct config_item *object, jmp_buf out)
{
	char *volatile key = NULL;
	jmp_buf err;

	if (setjmp (err))
	{
		free (key);
		longjmp (out, 1);
	}

	SKIP_NL ();

	// Either this object's closing right brace if called recursively,
	// or end of file when called on a whole configuration file
	if (PEEK () == CONFIG_T_RBRACE
	 || PEEK () == CONFIG_T_ABORT)
		return false;

	// I'm not sure how to feel about arbitrary keys but here they are
	if (!ACCEPT (CONFIG_T_STRING))
		EXPECT (CONFIG_T_WORD);

	key = xstrdup (self->tokenizer.string.str);
	SKIP_NL ();

	EXPECT (CONFIG_T_EQUALS);
	SKIP_NL ();

	str_map_set (&object->value.object, key,
		config_parser_parse_value (self, err));

	free (key);
	key = NULL;

	if (PEEK () == CONFIG_T_RBRACE
	 || PEEK () == CONFIG_T_ABORT)
		return false;

	EXPECT (CONFIG_T_NEWLINE);
	return true;
}

/// Parse the inside of an object definition
static struct config_item *
config_parser_parse_object (struct config_parser *self, jmp_buf out)
{
	struct config_item *volatile object = config_item_object ();
	jmp_buf err;

	if (setjmp (err))
	{
		config_item_destroy (object);
		longjmp (out, 1);
	}

	while (config_parser_parse_kv_pair (self, object, err))
		;
	return object;
}

#undef PEEK
#undef ACCEPT
#undef EXPECT
#undef SKIP_NL

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

/// Parse a configuration snippet either as an object or a bare value.
/// If it's the latter (@a single_value_only), no newlines may follow.
static struct config_item *
config_item_parse (const char *script, size_t len,
	bool single_value_only, struct error **e)
{
	struct config_parser parser;
	config_parser_init (&parser, script, len);

	struct config_item *volatile object = NULL;
	jmp_buf err;

	if (setjmp (err))
	{
		if (object)
		{
			config_item_destroy (object);
			object = NULL;
		}

		error_propagate (e, parser.error);
		parser.error = NULL;
		goto end;
	}

	if (single_value_only)
	{
		// This is really only intended for in-program configuration
		// and telling the line number would look awkward
		parser.tokenizer.report_line = false;
		object = config_parser_parse_value (&parser, err);
	}
	else
		object = config_parser_parse_object (&parser, err);
	config_parser_expect (&parser, CONFIG_T_ABORT, err);
end:
	config_parser_free (&parser);
	return object;
}

/// Clone an item.  Schema assignments aren't retained.
struct config_item *
config_item_clone (struct config_item *self)
{
	// Oh well, it saves code
	struct str tmp;
	str_init (&tmp);
	config_item_write (self, false, &tmp);
	struct config_item *result =
		config_item_parse (tmp.str, tmp.len, true, NULL);
	str_free (&tmp);
	return result;
}

static struct config_item *
config_read_from_file (const char *filename, struct error **e)
{
	struct config_item *root = NULL;

	struct str data;
	str_init (&data);
	if (!read_file (filename, &data, e))
		goto end;

	struct error *error = NULL;
	if (!(root = config_item_parse (data.str, data.len, false, &error)))
	{
		error_set (e, "parse error in `%s': %s", filename, error->message);
		error_free (error);
	}
end:
	str_free (&data);
	return root;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

/// "user_data" is passed to allow its immediate use in validation callbacks
static struct config_item *
config_schema_initialize_item (struct config_schema *schema,
	struct config_item *parent, void *user_data, struct error **warning,
	struct error **e)
{
	hard_assert (parent->type == CONFIG_ITEM_OBJECT);
	struct config_item *item =
		str_map_find (&parent->value.object, schema->name);

	if (item)
	{
		struct error *error = NULL;
		item->user_data = user_data;
		if (config_item_validate_by_schema (item, schema, &error))
			goto keep_current;

		error_set (warning, "resetting configuration item "
			"`%s' to default: %s", schema->name, error->message);
		error_free (error);
	}

	struct error *error = NULL;
	if (schema->default_)
		item = config_item_parse
			(schema->default_, strlen (schema->default_), true, &error);
	else
		item = config_item_null ();

	if (item)
		item->user_data = user_data;

	if (error || !config_item_validate_by_schema (item, schema, &error))
	{
		error_set (e, "invalid default for configuration item `%s': %s",
			schema->name, error->message);
		error_free (error);

		if (item)
			config_item_destroy (item);
		return NULL;
	}

	// This will free the old item if there was any
	str_map_set (&parent->value.object, schema->name, item);

keep_current:
	// Make sure the string subtype fits the schema
	if (config_item_type_is_string (item->type)
	 && config_item_type_is_string (schema->type))
		item->type = schema->type;

	item->schema = schema;
	return item;
}

/// Assign schemas and user_data to multiple items at once;
/// feel free to copy over and modify to suit your particular needs
static void
config_schema_apply_to_object (struct config_schema *schema_array,
	struct config_item *object, void *user_data)
{
	while (schema_array->name)
	{
		struct error *warning = NULL, *e = NULL;
		config_schema_initialize_item
			(schema_array++, object, user_data, &warning, &e);

		if (warning)
		{
			print_warning ("%s", warning->message);
			error_free (warning);
		}
		if (e)
			exit_fatal ("%s", e->message);
	}
}

static void
config_schema_call_changed (struct config_item *item)
{
	if (item->type == CONFIG_ITEM_OBJECT)
	{
		struct str_map_iter iter;
		str_map_iter_init (&iter, &item->value.object);

		struct config_item *child;
		while ((child = str_map_iter_next (&iter)))
			config_schema_call_changed (child);
	}
	else if (item->schema && item->schema->on_change)
		item->schema->on_change (item);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// XXX: the callbacks may be overdesigned and of little to no practical use

typedef void (*config_module_load_fn)
	(struct config_item *subtree, void *user_data);

struct config_module
{
	char *name;                         ///< Name of the subtree
	config_module_load_fn loader;       ///< Module config subtree loader
	void *user_data;                    ///< User data
};

static void
config_module_destroy (struct config_module *self)
{
	free (self->name);
	free (self);
}

struct config
{
	struct str_map modules;             ///< Toplevel modules
	struct config_item *root;           ///< CONFIG_ITEM_OBJECT
};

static void
config_init (struct config *self)
{
	memset (self, 0, sizeof *self);
	str_map_init (&self->modules);
	self->modules.free = (str_map_free_fn) config_module_destroy;
}

static void
config_free (struct config *self)
{
	str_map_free (&self->modules);
	if (self->root)
		config_item_destroy (self->root);
}

static void
config_register_module (struct config *self,
	const char *name, config_module_load_fn loader, void *user_data)
{
	struct config_module *module = xcalloc (1, sizeof *module);
	module->name = xstrdup (name);
	module->loader = loader;
	module->user_data = user_data;

	str_map_set (&self->modules, name, module);
}

static void
config_load (struct config *self, struct config_item *root)
{
	hard_assert (root->type == CONFIG_ITEM_OBJECT);
	if (self->root)
		config_item_destroy (self->root);
	self->root = root;

	struct str_map_iter iter;
	str_map_iter_init (&iter, &self->modules);

	struct config_module *module;
	while ((module = str_map_iter_next (&iter)))
	{
		struct config_item *subtree = str_map_find
			(&root->value.object, module->name);
		// Silently fix inputs that only a lunatic user could create
		if (!subtree || subtree->type != CONFIG_ITEM_OBJECT)
			str_map_set (&root->value.object, module->name,
				(subtree = config_item_object ()));
		if (module->loader)
			module->loader (subtree, module->user_data);
	}
}

// --- Protocol modules --------------------------------------------------------

#include "liberty-proto.c"