aboutsummaryrefslogtreecommitdiff
path: root/degesch.c
blob: 765fdd7122158b46b5546fe2adc09631cc16e42d (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
/*
 * degesch.c: the experimental IRC client
 *
 * Copyright (c) 2015, Přemysl Janouch <p.janouch@gmail.com>
 * All rights reserved.
 *
 * 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.
 *
 */

/// Some arbitrary limit for the history file
#define HISTORY_LIMIT 10000

// String constants for all attributes we use for output
#define ATTR_PROMPT    "attr_prompt"
#define ATTR_RESET     "attr_reset"
#define ATTR_WARNING   "attr_warning"
#define ATTR_ERROR     "attr_error"

// User data for logger functions to enable formatted logging
#define print_fatal_data    ATTR_ERROR
#define print_error_data    ATTR_ERROR
#define print_warning_data  ATTR_WARNING

#include "config.h"
#undef PROGRAM_NAME
#define PROGRAM_NAME "degesch"

#include "common.c"
#include "kike-replies.c"

#include <langinfo.h>
#include <locale.h>
#include <pwd.h>

#include <curses.h>
#include <term.h>

// Literally cancer
#undef lines
#undef columns

#include <readline/readline.h>
#include <readline/history.h>

// --- Configuration (application-specific) ------------------------------------

// TODO: reject all junk present in the configuration; there can be newlines

static struct config_item g_config_table[] =
{
	{ "nickname",        NULL,    "IRC nickname"                             },
	{ "username",        NULL,    "IRC user name"                            },
	{ "realname",        NULL,    "IRC real name/e-mail"                     },

	{ "irc_host",        NULL,    "Address of the IRC server"                },
	{ "irc_port",        "6667",  "Port of the IRC server"                   },
	{ "ssl",             "off",   "Whether to use SSL"                       },
	{ "ssl_cert",        NULL,    "Client SSL certificate (PEM)"             },
	{ "ssl_verify",      "on",    "Whether to verify certificates"           },
	{ "ssl_ca_file",     NULL,    "OpenSSL CA bundle file"                   },
	{ "ssl_ca_path",     NULL,    "OpenSSL CA bundle path"                   },
	{ "autojoin",        NULL,    "Channels to join on start"                },
	{ "reconnect",       "on",    "Whether to reconnect on error"            },
	{ "reconnect_delay", "5",     "Time between reconnecting"                },

	{ "socks_host",      NULL,    "Address of a SOCKS 4a/5 proxy"            },
	{ "socks_port",      "1080",  "SOCKS port number"                        },
	{ "socks_username",  NULL,    "SOCKS auth. username"                     },
	{ "socks_password",  NULL,    "SOCKS auth. password"                     },

	{ "isolate_buffers", "off",   "Isolate global/server buffers"            },

	{ ATTR_PROMPT,       NULL,    "Terminal attributes for the prompt"       },
	{ ATTR_RESET,        NULL,    "String to reset terminal attributes"      },
	{ ATTR_WARNING,      NULL,    "Terminal attributes for warnings"         },
	{ ATTR_ERROR,        NULL,    "Terminal attributes for errors"           },

	{ NULL,              NULL,    NULL                                       }
};

// --- Application data --------------------------------------------------------

// All text stored in our data structures is encoded in UTF-8.
// Or at least should be.  The exception is IRC identifiers.

/// Shorthand to set an error and return failure from the function
#define FAIL(...)                                                              \
	BLOCK_START                                                                \
		error_set (e, __VA_ARGS__);                                            \
		return false;                                                          \
	BLOCK_END

struct user;
static void user_unref (struct user *self);

struct channel;
static void channel_unref (struct channel *self);

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

// We need a few reference countable objects with support
// for both strong and weak references

/// Callback just before a reference counted object is destroyed
typedef void (*destroy_cb_fn) (void *object, void *user_data);

#define REF_COUNTABLE_HEADER                                                   \
	size_t ref_count;                   /**< Reference count                */ \
	destroy_cb_fn on_destroy;           /**< To remove any weak references  */ \
	void *user_data;                    /**< User data for callbacks        */

#define REF_COUNTABLE_METHODS(name)                                            \
	static struct name *                                                       \
	name ## _ref (struct name *self)                                           \
	{                                                                          \
		self->ref_count++;                                                     \
		return self;                                                           \
	}                                                                          \
																			   \
	static void                                                                \
	name ## _unref (struct name *self)                                         \
	{                                                                          \
		if (--self->ref_count)                                                 \
			return;                                                            \
		if (self->on_destroy)                                                  \
			self->on_destroy (self, self->user_data);                          \
		name ## _destroy (self);                                               \
	}

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

struct user_channel
{
	LIST_HEADER (struct user_channel)

	struct channel *channel;            ///< Reference to channel
};

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

static void
user_channel_destroy (struct user_channel *self)
{
	channel_unref (self->channel);
	free (self);
}

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

// We keep references to user information in channels and buffers,
// and weak references in the name lookup table.

struct user
{
	REF_COUNTABLE_HEADER

	// TODO: eventually a reference to the server

	char *nickname;                     ///< Literal nickname
	// TODO: write code to poll for the away status
	bool away;                          ///< User is away

	struct user_channel *channels;      ///< Channels the user is on
};

static struct user *
user_new (void)
{
	struct user *self = xcalloc (1, sizeof *self);
	self->ref_count = 1;
	return self;
}

static void
user_destroy (struct user *self)
{
	free (self->nickname);
	LIST_FOR_EACH (struct user_channel, iter, self->channels)
		user_channel_destroy (iter);
	free (self);
}

REF_COUNTABLE_METHODS (user)

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

struct channel_user
{
	LIST_HEADER (struct channel_user)

	struct user *user;                  ///< Reference to user
	char *modes;                        ///< Op/voice/... characters
};

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

static void
channel_user_destroy (struct channel_user *self)
{
	user_unref (self->user);
	free (self->modes);
	free (self);
}

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

// We keep references to channels in their users and buffers,
// and weak references in the name lookup table.

struct channel
{
	REF_COUNTABLE_HEADER

	// TODO: eventually a reference to the server

	char *name;                         ///< Channel name
	char *mode;                         ///< Channel mode
	char *topic;                        ///< Channel topic

	struct channel_user *users;         ///< Channel users
	struct str_vector names_buf;        ///< Buffer for RPL_NAMREPLY
};

static struct channel *
channel_new (void)
{
	struct channel *self = xcalloc (1, sizeof *self);
	self->ref_count = 1;
	str_vector_init (&self->names_buf);
	return self;
}

static void
channel_destroy (struct channel *self)
{
	free (self->name);
	free (self->mode);
	free (self->topic);
	LIST_FOR_EACH (struct channel_user, iter, self->users)
		channel_user_destroy (iter);
	str_vector_free (&self->names_buf);
	free (self);
}

REF_COUNTABLE_METHODS (channel)

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

enum buffer_line_flags
{
	BUFFER_LINE_HIGHLIGHT   = 1 << 0    ///< The user was highlighted by this
};

enum buffer_line_type
{
	BUFFER_LINE_PRIVMSG,                ///< PRIVMSG
	BUFFER_LINE_ACTION,                 ///< PRIVMSG ACTION
	BUFFER_LINE_NOTICE,                 ///< NOTICE
	BUFFER_LINE_JOIN,                   ///< JOIN
	BUFFER_LINE_PART,                   ///< PART
	BUFFER_LINE_KICK,                   ///< KICK
	BUFFER_LINE_NICK,                   ///< NICK
	BUFFER_LINE_TOPIC,                  ///< TOPIC
	BUFFER_LINE_QUIT,                   ///< QUIT
	BUFFER_LINE_STATUS,                 ///< Whatever status messages
	BUFFER_LINE_ERROR                   ///< Whatever error messages
};

struct buffer_line
{
	LIST_HEADER (struct buffer_line)

	// We use the "type" and "flags" mostly just as formatting hints

	enum buffer_line_type type;         ///< Type of the event
	int flags;                          ///< Flags

	time_t when;                        ///< Time of the event
	char *who;                          ///< Name of the origin or NULL (user)
	char *object;                       ///< Text of message, object of action
	char *reason;                       ///< Reason for PART, KICK, QUIT
};

struct buffer_line *
buffer_line_new (void)
{
	struct buffer_line *self = xcalloc (1, sizeof *self);
	return self;
}

static void
buffer_line_destroy (struct buffer_line *self)
{
	free (self->who);
	free (self->object);
	free (self->reason);
	free (self);
}

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

enum buffer_type
{
	BUFFER_GLOBAL,                      ///< Global information
	BUFFER_SERVER,                      ///< Server-related messages
	BUFFER_CHANNEL,                     ///< Channels
	BUFFER_PM                           ///< Private messages (query)
};

struct buffer
{
	LIST_HEADER (struct buffer)

	enum buffer_type type;              ///< Type of the buffer
	char *name;                         ///< The name of the buffer

	// Readline state:

	HISTORY_STATE *history;             ///< Saved history state
	char *saved_line;                   ///< Saved line
	int saved_point;                    ///< Saved position in line
	int saved_mark;                     ///< Saved mark

	// Buffer contents:

	struct buffer_line *lines;          ///< All lines in this buffer
	struct buffer_line *lines_tail;     ///< The tail of buffer lines
	unsigned lines_count;               ///< How many lines we have

	unsigned unseen_messages_count;     ///< # messages since last visited

	// Origin information:

	struct user *user;                  ///< Reference to user
	struct channel *channel;            ///< Reference to channel

	// TODO: eventually a reference to the server for server buffers
};

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

static void
buffer_destroy (struct buffer *self)
{
	free (self->name);
	// Can't really free "history" here
	free (self->saved_line);
	LIST_FOR_EACH (struct buffer_line, iter, self->lines)
		buffer_line_destroy (iter);
	if (self->user)
		user_unref (self->user);
	if (self->channel)
		channel_unref (self->channel);
	free (self);
}

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

enum color_mode
{
	COLOR_AUTO,                         ///< Autodetect if colours are available
	COLOR_ALWAYS,                       ///< Always use coloured output
	COLOR_NEVER                         ///< Never use coloured output
};

struct app_context
{
	// Configuration:

	struct str_map config;              ///< User configuration
	enum color_mode color_mode;         ///< Colour output mode
	bool reconnect;                     ///< Whether to reconnect on conn. fail.
	unsigned long reconnect_delay;      ///< Reconnect delay in seconds
	bool isolate_buffers;               ///< Isolate global/server buffers

	// Server connection:

	int irc_fd;                         ///< Socket FD of the server
	struct str read_buffer;             ///< Input yet to be processed
	struct poller_fd irc_event;         ///< IRC FD event
	bool irc_ready;                     ///< Whether we may send messages now

	SSL_CTX *ssl_ctx;                   ///< SSL context
	SSL *ssl;                           ///< SSL connection

	// TODO: an output queue to prevent excess floods (this will be needed
	//   especially for away status polling)

	// XXX: there can be buffers for non-existent users
	// TODO: initialize key_strxfrm according to server properties;
	//   note that collisions may arise on reconnecting
	// TODO: when disconnected, get rid of all users everywhere;
	//   maybe also broadcast all buffers about the disconnection event
	// TODO: when getting connected again, rejoin all current channels

	struct str_map irc_users;           ///< IRC user data
	struct str_map irc_channels;        ///< IRC channel data
	struct str_map irc_buffer_map;      ///< Maps IRC identifiers to buffers

	struct user *irc_user;              ///< Our own user
	char *irc_user_mode;                ///< Our current user mode
	char *irc_user_host;                ///< Our current user@host

	// Events:

	struct poller_fd tty_event;         ///< Terminal input event
	struct poller_fd signal_event;      ///< Signal FD event

	struct poller_timer ping_tmr;       ///< We should send a ping
	struct poller_timer timeout_tmr;    ///< Connection seems to be dead
	struct poller_timer reconnect_tmr;  ///< We should reconnect now

	struct poller poller;               ///< Manages polled descriptors
	bool quitting;                      ///< User requested quitting
	bool polling;                       ///< The event loop is running

	// Buffers:

	struct buffer *buffers;             ///< All our buffers in order
	struct buffer *buffers_tail;        ///< The tail of our buffers

	// XXX: when we go multiserver, there will be collisions
	// TODO: make buffer names unique like weechat does
	struct str_map buffers_by_name;     ///< Excludes GLOBAL and SERVER

	struct buffer *global_buffer;       ///< The global buffer
	struct buffer *server_buffer;       ///< The server buffer
	struct buffer *current_buffer;      ///< The current buffer

	// TODO: So that we always output proper date change messages
	time_t last_displayed_msg_time;     ///< Time of last displayed message

	// Terminal:

	iconv_t term_to_utf8;               ///< Terminal encoding to UTF-8
	iconv_t term_from_utf8;             ///< UTF-8 to terminal encoding
	iconv_t latin1_to_utf8;             ///< ISO Latin 1 to UTF-8

	int lines;                          ///< Current terminal height
	int columns;                        ///< Current ternimal width

	char *readline_prompt;              ///< The prompt we use for readline
	bool readline_prompt_shown;         ///< Whether the prompt is shown now
}
*g_ctx;

static void on_irc_ping_timeout (void *user_data);
static void on_irc_timeout (void *user_data);
static void on_irc_reconnect_timeout (void *user_data);

static void
app_context_init (struct app_context *self)
{
	memset (self, 0, sizeof *self);

	str_map_init (&self->config);
	self->config.free = free;
	load_config_defaults (&self->config, g_config_table);

	self->irc_fd = -1;
	str_init (&self->read_buffer);
	self->irc_ready = false;

	str_map_init (&self->irc_users);
	self->irc_users.key_xfrm = irc_strxfrm;
	str_map_init (&self->irc_channels);
	self->irc_channels.key_xfrm = irc_strxfrm;
	str_map_init (&self->irc_buffer_map);
	self->irc_buffer_map.key_xfrm = irc_strxfrm;

	poller_init (&self->poller);

	str_map_init (&self->buffers_by_name);
	self->buffers_by_name.key_xfrm = irc_strxfrm;

	self->last_displayed_msg_time = time (NULL);

	char *encoding = nl_langinfo (CODESET);
#ifdef __linux__
	encoding = xstrdup_printf ("%s//TRANSLIT", encoding);
#else // ! __linux__
	encoding = xstrdup (encoding);
#endif // ! __linux__

	if ((self->term_from_utf8 =
		iconv_open (encoding, "UTF-8")) == (iconv_t) -1
	 || (self->latin1_to_utf8 =
		iconv_open ("UTF-8", "ISO-8859-1")) == (iconv_t) -1
	 || (self->term_to_utf8 =
		iconv_open ("UTF-8", nl_langinfo (CODESET))) == (iconv_t) -1)
		exit_fatal ("creating the UTF-8 conversion object failed: %s",
			strerror (errno));

	free (encoding);
}

static void
app_context_free (struct app_context *self)
{
	str_map_free (&self->config);
	str_free (&self->read_buffer);

	if (self->irc_fd != -1)
	{
		xclose (self->irc_fd);
		poller_fd_reset (&self->irc_event);
	}
	if (self->ssl)
		SSL_free (self->ssl);
	if (self->ssl_ctx)
		SSL_CTX_free (self->ssl_ctx);

	if (self->irc_user)
		user_unref (self->irc_user);
	free (self->irc_user_mode);
	free (self->irc_user_host);

	str_map_free (&self->irc_users);
	str_map_free (&self->irc_channels);
	str_map_free (&self->irc_buffer_map);

	poller_free (&self->poller);

	LIST_FOR_EACH (struct buffer, iter, self->buffers)
		buffer_destroy (iter);
	str_map_free (&self->buffers_by_name);

	iconv_close (self->latin1_to_utf8);
	iconv_close (self->term_from_utf8);
	iconv_close (self->term_to_utf8);

	free (self->readline_prompt);
}

static void refresh_prompt (struct app_context *ctx);
static char *irc_cut_nickname (const char *prefix);
static const char *irc_find_userhost (const char *prefix);

// --- Attributed output -------------------------------------------------------

static struct
{
	bool initialized;                   ///< Terminal is available
	bool stdout_is_tty;                 ///< `stdout' is a terminal
	bool stderr_is_tty;                 ///< `stderr' is a terminal

	char *color_set[8];                 ///< Codes to set the foreground colour
}
g_terminal;

static bool
init_terminal (void)
{
	int tty_fd = -1;
	if ((g_terminal.stderr_is_tty = isatty (STDERR_FILENO)))
		tty_fd = STDERR_FILENO;
	if ((g_terminal.stdout_is_tty = isatty (STDOUT_FILENO)))
		tty_fd = STDOUT_FILENO;

	int err;
	if (tty_fd == -1 || setupterm (NULL, tty_fd, &err) == ERR)
		return false;

	// Make sure all terminal features used by us are supported
	if (!set_a_foreground || !enter_bold_mode || !exit_attribute_mode)
	{
		del_curterm (cur_term);
		return false;
	}

	for (size_t i = 0; i < N_ELEMENTS (g_terminal.color_set); i++)
		g_terminal.color_set[i] = xstrdup (tparm (set_a_foreground,
			i, 0, 0, 0, 0, 0, 0, 0, 0));

	return g_terminal.initialized = true;
}

static void
free_terminal (void)
{
	if (!g_terminal.initialized)
		return;

	for (size_t i = 0; i < N_ELEMENTS (g_terminal.color_set); i++)
		free (g_terminal.color_set[i]);
	del_curterm (cur_term);
}

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

struct app_readline_state
{
	char *saved_line;
	int saved_point;
	int saved_mark;
};

static void
app_readline_hide (struct app_readline_state *state)
{
	state->saved_point = rl_point;
	state->saved_mark = rl_mark;
	state->saved_line = rl_copy_text (0, rl_end);
	rl_set_prompt ("");
	rl_replace_line ("", 0);
	rl_redisplay ();
}

static void
app_readline_restore (struct app_readline_state *state, const char *prompt)
{
	rl_set_prompt (prompt);
	rl_replace_line (state->saved_line, 0);
	rl_point = state->saved_point;
	rl_mark = state->saved_mark;
	rl_redisplay ();
	free (state->saved_line);
}

static void
app_readline_erase_to_bol (const char *prompt)
{
	rl_set_prompt ("");
	rl_replace_line ("", 0);
	rl_point = rl_mark = 0;
	rl_redisplay ();
	rl_set_prompt (prompt);
}

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

typedef int (*terminal_printer_fn) (int);

static int
putchar_stderr (int c)
{
	return fputc (c, stderr);
}

static terminal_printer_fn
get_attribute_printer (FILE *stream)
{
	if (stream == stdout && g_terminal.stdout_is_tty)
		return putchar;
	if (stream == stderr && g_terminal.stderr_is_tty)
		return putchar_stderr;
	return NULL;
}

static void
vprint_attributed (struct app_context *ctx,
	FILE *stream, const char *attribute, const char *fmt, va_list ap)
{
	terminal_printer_fn printer = get_attribute_printer (stream);
	if (!attribute)
		printer = NULL;

	if (printer)
	{
		const char *value = str_map_find (&ctx->config, attribute);
		tputs (value, 1, printer);
	}

	vfprintf (stream, fmt, ap);

	if (printer)
	{
		const char *value = str_map_find (&ctx->config, ATTR_RESET);
		tputs (value, 1, printer);
	}
}

static void
print_attributed (struct app_context *ctx,
	FILE *stream, const char *attribute, const char *fmt, ...)
{
	va_list ap;
	va_start (ap, fmt);
	vprint_attributed (ctx, stream, attribute, fmt, ap);
	va_end (ap);
}

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

	struct app_readline_state state;
	if (g_ctx->readline_prompt_shown)
		app_readline_hide (&state);

	print_attributed (g_ctx, stream, user_data, "%s", quote);
	vprint_attributed (g_ctx, stream, user_data, fmt, ap);
	fputs ("\n", stream);

	if (g_ctx->readline_prompt_shown)
		app_readline_restore (&state, g_ctx->readline_prompt);
}

static void
init_colors (struct app_context *ctx)
{
	bool have_ti = init_terminal ();

	// Use escape sequences from terminfo if possible, and SGR as a fallback
#define INIT_ATTR(id, ti, vt100) \
	str_map_set (&ctx->config, (id), xstrdup (have_ti ? (ti) : (vt100)));

	INIT_ATTR (ATTR_PROMPT,   enter_bold_mode,         "\x1b[1m");
	INIT_ATTR (ATTR_RESET,    exit_attribute_mode,     "\x1b[0m");
	INIT_ATTR (ATTR_WARNING,  g_terminal.color_set[3], "\x1b[33m");
	INIT_ATTR (ATTR_ERROR,    g_terminal.color_set[1], "\x1b[31m");

#undef INIT_ATTR

	switch (ctx->color_mode)
	{
	case COLOR_ALWAYS:
		g_terminal.stdout_is_tty = true;
		g_terminal.stderr_is_tty = true;
		break;
	case COLOR_AUTO:
		if (!g_terminal.initialized)
		{
	case COLOR_NEVER:
			g_terminal.stdout_is_tty = false;
			g_terminal.stderr_is_tty = false;
		}
	}

	g_log_message_real = log_message_attributed;
}

// --- Signals -----------------------------------------------------------------

static int g_signal_pipe[2];            ///< A pipe used to signal... signals

/// Program termination has been requested by a signal
static volatile sig_atomic_t g_termination_requested;
/// The window has changed in size
static volatile sig_atomic_t g_winch_received;

static void
sigterm_handler (int signum)
{
	(void) signum;

	g_termination_requested = true;

	int original_errno = errno;
	if (write (g_signal_pipe[1], "t", 1) == -1)
		soft_assert (errno == EAGAIN);
	errno = original_errno;
}

static void
sigwinch_handler (int signum)
{
	(void) signum;

	g_winch_received = true;

	int original_errno = errno;
	if (write (g_signal_pipe[1], "w", 1) == -1)
		soft_assert (errno == EAGAIN);
	errno = original_errno;
}

static void
setup_signal_handlers (void)
{
	if (pipe (g_signal_pipe) == -1)
		exit_fatal ("%s: %s", "pipe", strerror (errno));

	set_cloexec (g_signal_pipe[0]);
	set_cloexec (g_signal_pipe[1]);

	// So that the pipe cannot overflow; it would make write() block within
	// the signal handler, which is something we really don't want to happen.
	// The same holds true for read().
	set_blocking (g_signal_pipe[0], false);
	set_blocking (g_signal_pipe[1], false);

	signal (SIGPIPE, SIG_IGN);

	struct sigaction sa;
	sa.sa_flags = SA_RESTART;
	sa.sa_handler = sigwinch_handler;
	sigemptyset (&sa.sa_mask);

	if (sigaction (SIGWINCH, &sa, NULL) == -1)
		exit_fatal ("sigaction: %s", strerror (errno));

	sa.sa_handler = sigterm_handler;
	if (sigaction (SIGINT, &sa, NULL) == -1
	 || sigaction (SIGTERM, &sa, NULL) == -1)
		exit_fatal ("sigaction: %s", strerror (errno));
}

// --- Buffers -----------------------------------------------------------------

static void buffer_send (struct app_context *ctx, struct buffer *buffer,
	enum buffer_line_type type, int flags, const char *origin,
	const char *reason, const char *format, ...) ATTRIBUTE_PRINTF (7, 8);

static void
buffer_update_time (struct app_context *ctx, time_t now)
{
	struct tm last, current;
	if (!localtime_r (&ctx->last_displayed_msg_time, &last)
	 || !localtime_r (&now, &current))
	{
		// Strange but nonfatal
		print_error ("%s: %s", "localtime_r", strerror (errno));
		return;
	}

	ctx->last_displayed_msg_time = now;
	if (last.tm_year == current.tm_year
	 && last.tm_mon  == current.tm_mon
	 && last.tm_mday == current.tm_mday)
		return;

	char buf[32] = "";
	if (soft_assert (strftime (buf, sizeof buf, "%F", &current)))
		print_status ("%s", buf);
	// Else the buffer was too small, which is pretty weird
}

static void
buffer_line_display (struct app_context *ctx, struct buffer_line *line)
{
	// Normal timestamps don't include the date, this way the user won't be
	// confused as to when an event has happened
	buffer_update_time (ctx, line->when);

	struct str text;
	str_init (&text);

	struct tm current;
	if (!localtime_r (&line->when, &current))
		print_error ("%s: %s", "localtime_r", strerror (errno));
	else
		str_append_printf (&text, "%02d:%02d:%02d ",
			current.tm_hour, current.tm_min, current.tm_sec);

	char *who    = iconv_xstrdup (ctx->term_from_utf8, line->who,    -1, NULL);
	char *object = iconv_xstrdup (ctx->term_from_utf8, line->object, -1, NULL);
	char *reason = iconv_xstrdup (ctx->term_from_utf8, line->reason, -1, NULL);

	// TODO: colorize the output, note that we shouldn't put everything through
	//   tputs but only the attribute strings.  That might prove a bit
	//   challenging.  Maybe we could create a helper object to pust text
	//   and formatting into.  We could have a varargs function to make it a bit
	//   more friendly, e.g. push(&x, ATTR_JOIN, "--> ", ATTR_RESET, who, NULL)

	char *nick = NULL;
	const char *userhost = NULL;

	if (*who)
	{
		nick = irc_cut_nickname (who);
		userhost = irc_find_userhost (who);
	}

	switch (line->type)
	{
	case BUFFER_LINE_PRIVMSG:
		str_append_printf (&text, "<%s> %s", nick, object);
		break;
	case BUFFER_LINE_ACTION:
		str_append_printf (&text, " *  %s %s", nick, object);
		break;
	case BUFFER_LINE_NOTICE:
		str_append_printf (&text, " -  Notice(%s): %s", nick, object);
		break;
	case BUFFER_LINE_JOIN:
		if (*who)
			str_append_printf (&text, "--> %s (%s) has joined %s",
				nick, userhost, object);
		else
			str_append_printf (&text, "--> You have joined %s", object);
		break;
	case BUFFER_LINE_PART:
		if (*who)
			str_append_printf (&text, "<-- %s (%s) has left %s (%s)",
				nick, userhost, object, reason);
		else
			str_append_printf (&text, "<-- You have left %s (%s)",
				object, reason);
		break;
	case BUFFER_LINE_KICK:
		if (*who)
			str_append_printf (&text, "<-- %s has kicked %s (%s)",
				nick, object, reason);
		else
			str_append_printf (&text, "<-- You have kicked %s (%s)",
				object, reason);
		break;
	case BUFFER_LINE_NICK:
		if (*who)
			str_append_printf (&text, " -  %s is now known as %s",
				nick, object);
		else
			str_append_printf (&text, " -  You are now known as %s", object);
		break;
	case BUFFER_LINE_TOPIC:
		if (*who)
			str_append_printf (&text,
				" -  %s has changed the topic to: %s", nick, object);
		else
			str_append_printf (&text,
				" -  You have changed the topic to: %s", object);
		break;
	case BUFFER_LINE_QUIT:
		if (*who)
			str_append_printf (&text, "<-- %s (%s) has quit (%s)",
				nick, userhost, reason);
		else
			str_append_printf (&text, "<-- You have quit (%s)", reason);
		break;
	case BUFFER_LINE_STATUS:
		str_append_printf (&text, " -  %s", object);
		break;
	case BUFFER_LINE_ERROR:
		str_append_printf (&text, "=!= %s", object);
	}

	free (nick);

	free (who);
	free (object);
	free (reason);

	struct app_readline_state state;
	if (ctx->readline_prompt_shown)
		app_readline_hide (&state);

	// TODO: write the line to a log file; note that the global and server
	//   buffers musn't collide with filenames

	printf ("%s\n", text.str);
	str_free (&text);

	if (ctx->readline_prompt_shown)
		app_readline_restore (&state, ctx->readline_prompt);
}

static void
buffer_send (struct app_context *ctx, struct buffer *buffer,
	enum buffer_line_type type, int flags,
	const char *origin, const char *reason, const char *format, ...)
{
	va_list ap;
	va_start (ap, format);
	struct str text;
	str_init (&text);
	str_append_vprintf (&text, format, ap);
	va_end (ap);

	struct buffer_line *line = buffer_line_new ();
	line->type = type;
	line->flags = flags;
	line->when = time (NULL);
	line->who = xstrdup (origin ? origin : "");
	line->object = str_steal (&text);
	line->reason = xstrdup (reason ? reason : "");

	LIST_APPEND_WITH_TAIL (buffer->lines, buffer->lines_tail, line);
	buffer->lines_count++;

	if (buffer == ctx->current_buffer)
		buffer_line_display (ctx, line);
	else if (!ctx->isolate_buffers &&
		(buffer == ctx->global_buffer || buffer == ctx->server_buffer))
		// TODO: show this in another color or something
		buffer_line_display (ctx, line);
	else
	{
		buffer->unseen_messages_count++;
		refresh_prompt (ctx);
	}
}

#define buffer_send_status(ctx, buffer, ...) \
	buffer_send (ctx, buffer, BUFFER_LINE_STATUS, 0, NULL, NULL, __VA_ARGS__)
#define buffer_send_error(ctx, buffer, ...) \
	buffer_send (ctx, buffer, BUFFER_LINE_ERROR, 0, NULL, NULL, __VA_ARGS__)

static struct buffer *
buffer_by_name (struct app_context *ctx, const char *name)
{
	return str_map_find (&ctx->buffers_by_name, name);
}

static void
buffer_add (struct app_context *ctx, struct buffer *buffer)
{
	hard_assert (!buffer_by_name (ctx, buffer->name));

	str_map_set (&ctx->buffers_by_name, buffer->name, buffer);
	LIST_APPEND_WITH_TAIL (ctx->buffers, ctx->buffers_tail, buffer);

	// In theory this can't cause changes in the prompt
	refresh_prompt (ctx);
}

static void
buffer_remove (struct app_context *ctx, struct buffer *buffer)
{
	hard_assert (buffer != ctx->current_buffer);

	// TODO: part from the channel if needed

	// rl_clear_history, being the only way I know of to get rid of the complete
	// history including attached data, is a pretty recent addition.  *sigh*
#if RL_READLINE_VERSION >= 0x0603
	if (buffer->history)
	{
		// See buffer_activate() for why we need to do this BS
		rl_free_undo_list ();

		// This is probably the only way we can free the history fully
		HISTORY_STATE *state = history_get_history_state ();

		history_set_history_state (buffer->history);
		rl_clear_history ();

		history_set_history_state (state);
		free (state);
	}
#endif // RL_READLINE_VERSION

	// And make sure to unlink the buffer from "irc_buffer_map"
	if (buffer->channel)
		str_map_set (&ctx->irc_buffer_map, buffer->channel->name, NULL);
	if (buffer->user)
		str_map_set (&ctx->irc_buffer_map, buffer->user->nickname, NULL);

	str_map_set (&ctx->buffers_by_name, buffer->name, NULL);
	LIST_UNLINK_WITH_TAIL (ctx->buffers, ctx->buffers_tail, buffer);
	buffer_destroy (buffer);

	// It's not a good idea to remove these buffers, but it's even a worse
	// one to leave the pointers point to invalid memory
	if (buffer == ctx->global_buffer)
		ctx->global_buffer = NULL;
	if (buffer == ctx->server_buffer)
		ctx->server_buffer = NULL;

	refresh_prompt (ctx);
}

static void
buffer_activate (struct app_context *ctx, struct buffer *buffer)
{
	if (ctx->current_buffer == buffer)
		return;

	print_status ("%s", buffer->name);

	// That is, minus the buffer switch line and the readline prompt
	int to_display = MAX (10, ctx->lines - 2);
	struct buffer_line *line = buffer->lines_tail;
	while (line && line->prev && --to_display > 0)
		line = line->prev;

	// Once we've found where we want to start with the backlog, print it
	for (; line; line = line->next)
		buffer_line_display (ctx, line);
	buffer->unseen_messages_count = 0;

	// The following part shows you why it's not a good idea to use
	// GNU Readline for this kind of software.  Or for anything else, really.

	// There could possibly be occurences of the current undo list in some
	// history entry.  We either need to free the undo list, or move it
	// somewhere else to load back later, as the buffer we're switching to
	// has its own history state.
	rl_free_undo_list ();

	// Save this buffer's history so that it's independent for each buffer
	if (ctx->current_buffer)
	{
		ctx->current_buffer->history = history_get_history_state ();
		ctx->current_buffer->saved_line = rl_copy_text (0, rl_end);
		ctx->current_buffer->saved_point = rl_point;
		ctx->current_buffer->saved_mark = rl_mark;
	}
	else
		// Just throw it away; there should always be an active buffer however
#if RL_READLINE_VERSION >= 0x0603
		rl_clear_history ();
#else // RL_READLINE_VERSION < 0x0603
		// At least something... this may leak undo entries
		clear_history ();
#endif // RL_READLINE_VERSION < 0x0603

	// Restore the target buffer's history
	if (buffer->history)
	{
		// history_get_history_state() just allocates a new HISTORY_STATE
		// and fills it with its current internal data.  We don't need that
		// shell anymore after reviving it.
		history_set_history_state (buffer->history);
		free (buffer->history);
		buffer->history = NULL;
	}
	else
	{
		// This should get us a clean history while keeping the flags.
		// Note that we've either saved the previous history entries, or we've
		// cleared them altogether, so there should be nothing to leak.
		HISTORY_STATE *state = history_get_history_state ();
		state->offset = state->length = state->size = 0;
		history_set_history_state (state);
		free (state);
	}

	// Try to restore the target buffer's readline state
	if (buffer->saved_line)
	{
		rl_replace_line (buffer->saved_line, 0);
		rl_point = buffer->saved_point;
		rl_mark = buffer->saved_mark;
		free (buffer->saved_line);

		if (ctx->readline_prompt_shown)
			rl_redisplay ();
	}

	// Now at last we can switch the pointers
	ctx->current_buffer = buffer;

	refresh_prompt (ctx);
}

static void
buffer_merge (struct app_context *ctx,
	struct buffer *buffer, struct buffer *merged)
{
	// TODO: try to merge the buffers as best as we can
}

static void
buffer_rename (struct app_context *ctx,
	struct buffer *buffer, const char *new_name)
{
	hard_assert (buffer->type == BUFFER_PM);

	struct buffer *collision =
		str_map_find (&ctx->irc_buffer_map, new_name);
	if (collision)
	{
		// TODO: use full weechat-style buffer names
		//   to prevent name collisions with the global buffer
		hard_assert (collision->type == BUFFER_PM);

		// When there's a collision, there's not much else we can do
		// other than somehow trying to merge them
		buffer_merge (ctx, collision, buffer);
		// TODO: log a status message about the merge
		if (ctx->current_buffer == buffer)
			buffer_activate (ctx, collision);
		buffer_remove (ctx, buffer);
	}
	else
	{
		// Otherwise we just rename the buffer and that's it
		str_map_set (&ctx->buffers_by_name, buffer->name, NULL);
		str_map_set (&ctx->buffers_by_name, new_name, buffer);

		free (buffer->name);
		buffer->name = xstrdup (new_name);

		// We might have renamed the current buffer
		refresh_prompt (ctx);
	}
}

static struct buffer *
buffer_at_index (struct app_context *ctx, int n)
{
	int i = 0;
	LIST_FOR_EACH (struct buffer, iter, ctx->buffers)
		if (++i == n)
			return iter;
	return NULL;
}

static struct buffer *
buffer_next (struct app_context *ctx, int count)
{
	struct buffer *new_buffer = ctx->current_buffer;
	while (count-- > 0)
		if (!(new_buffer = new_buffer->next))
			new_buffer = ctx->buffers;
	return new_buffer;
}

static struct buffer *
buffer_previous (struct app_context *ctx, int count)
{
	struct buffer *new_buffer = ctx->current_buffer;
	while (count-- > 0)
		if (!(new_buffer = new_buffer->prev))
			new_buffer = ctx->buffers_tail;
	return new_buffer;
}

static bool
buffer_goto (struct app_context *ctx, int n)
{
	struct buffer *buffer = buffer_at_index (ctx, n);
	if (!buffer)
		return false;

	buffer_activate (ctx, buffer);
	return true;
}

static int
buffer_get_index (struct app_context *ctx, struct buffer *buffer)
{
	int index = 1;
	LIST_FOR_EACH (struct buffer, iter, ctx->buffers)
	{
		if (iter == buffer)
			return index;
		index++;
	}
	return -1;
}

static void
init_buffers (struct app_context *ctx)
{
	// At the moment  we have only two global everpresent buffers
	struct buffer *global = ctx->global_buffer = buffer_new ();
	struct buffer *server = ctx->server_buffer = buffer_new ();

	global->type = BUFFER_GLOBAL;
	global->name = xstrdup (PROGRAM_NAME);

	server->type = BUFFER_SERVER;
	server->name = xstrdup (str_map_find (&ctx->config, "irc_host"));

	LIST_APPEND_WITH_TAIL (ctx->buffers, ctx->buffers_tail, global);
	LIST_APPEND_WITH_TAIL (ctx->buffers, ctx->buffers_tail, server);
}

// --- Users, channels ---------------------------------------------------------

static void
irc_user_on_destroy (void *object, void *user_data)
{
	struct user *user = object;
	struct app_context *ctx = user_data;
	str_map_set (&ctx->irc_users, user->nickname, NULL);
}

static struct user *
irc_make_user (struct app_context *ctx, char *nickname)
{
	hard_assert (!str_map_find (&ctx->irc_users, nickname));

	struct user *user = user_new ();
	user->on_destroy = irc_user_on_destroy;
	user->user_data = ctx;
	user->nickname = nickname;
	str_map_set (&ctx->irc_users, user->nickname, user);
	return user;
}

static struct buffer *
irc_get_user_buffer (struct app_context *ctx, const char *nickname)
{
	struct buffer *buffer = str_map_find (&ctx->irc_buffer_map, nickname);
	if (buffer)
		return buffer;

	struct user *user = str_map_find (&ctx->irc_users, nickname);
	if (!user)
		user = irc_make_user (ctx, xstrdup (nickname));

	// Open a new buffer for the user
	buffer = buffer_new ();
	buffer->type = BUFFER_PM;
	buffer->name = xstrdup (nickname);
	buffer->user = user_ref (user);
	LIST_APPEND_WITH_TAIL (ctx->buffers, ctx->buffers_tail, buffer);
	str_map_set (&ctx->irc_buffer_map, user->nickname, buffer);
	return buffer;
}

static void
irc_channel_on_destroy (void *object, void *user_data)
{
	struct channel *channel = object;
	struct app_context *ctx = user_data;
	str_map_set (&ctx->irc_channels, channel->name, NULL);
}

static struct channel *
irc_make_channel (struct app_context *ctx, char *name)
{
	hard_assert (!str_map_find (&ctx->irc_channels, name));

	struct channel *channel = channel_new ();
	channel->on_destroy = irc_channel_on_destroy;
	channel->user_data = ctx;
	channel->name = name;
	channel->mode = xstrdup ("");
	channel->topic = NULL;
	str_map_set (&ctx->irc_channels, channel->name, channel);
	return channel;
}

static void
irc_unlink_user_from_channel (struct user *user, struct channel *channel)
{
	// The order is important here as the channel can hold the last reference
	LIST_FOR_EACH (struct user_channel, iter, user->channels)
		if (iter->channel == channel)
		{
			LIST_UNLINK (user->channels, iter);
			user_channel_destroy (iter);
		}
	LIST_FOR_EACH (struct channel_user, iter, channel->users)
		if (iter->user == user)
		{
			LIST_UNLINK (channel->users, iter);
			channel_user_destroy (iter);
		}
}

// --- Supporting code ---------------------------------------------------------

static char *
irc_cut_nickname (const char *prefix)
{
	return xstrndup (prefix, strcspn (prefix, "!@"));
}

static const char *
irc_find_userhost (const char *prefix)
{
	const char *p = strchr (prefix, '!');
	return p ? p + 1 : NULL;
}

static bool
irc_is_this_us (struct app_context *ctx, const char *prefix)
{
	char *nick = irc_cut_nickname (prefix);
	bool result = !irc_strcmp (nick, ctx->irc_user->nickname);
	free (nick);
	return result;
}

static bool
irc_is_channel (struct app_context *ctx, const char *ident)
{
	(void) ctx;  // TODO: parse prefixes from server features

	return *ident && !!strchr ("#&+!", *ident);
}

static void
irc_shutdown (struct app_context *ctx)
{
	// TODO: set a timer after which we cut the connection?
	// Generally non-critical
	if (ctx->ssl)
		soft_assert (SSL_shutdown (ctx->ssl) != -1);
	else
		soft_assert (shutdown (ctx->irc_fd, SHUT_WR) == 0);
}

static void
try_finish_quit (struct app_context *ctx)
{
	if (ctx->quitting && ctx->irc_fd == -1)
		ctx->polling = false;
}

static void
initiate_quit (struct app_context *ctx)
{
	// First get rid of readline
	if (ctx->readline_prompt_shown)
	{
		app_readline_erase_to_bol (ctx->readline_prompt);
		ctx->readline_prompt_shown = false;
	}

	// This is okay as long as we're not called from within readline
	rl_callback_handler_remove ();

	// Initiate a connection close
	buffer_send_status (ctx, ctx->global_buffer, "Shutting down");
	if (ctx->irc_fd != -1)
		// XXX: when we go async, we'll have to flush output buffers first
		irc_shutdown (ctx);

	ctx->quitting = true;
	try_finish_quit (ctx);
}

static bool irc_send (struct app_context *ctx,
	const char *format, ...) ATTRIBUTE_PRINTF (2, 3);

static bool
irc_send (struct app_context *ctx, const char *format, ...)
{
	va_list ap;

	if (g_debug_mode)
	{
		struct app_readline_state state;
		if (ctx->readline_prompt_shown)
			app_readline_hide (&state);

		fputs ("[IRC] <== \"", stderr);
		va_start (ap, format);
		vfprintf (stderr, format, ap);
		va_end (ap);
		fputs ("\"\n", stderr);

		if (ctx->readline_prompt_shown)
			app_readline_restore (&state, ctx->readline_prompt);
	}

	if (!soft_assert (ctx->irc_fd != -1))
		return false;

	va_start (ap, format);
	struct str str;
	str_init (&str);
	str_append_vprintf (&str, format, ap);
	str_append (&str, "\r\n");
	va_end (ap);

	bool result = true;
	if (ctx->ssl)
	{
		// TODO: call SSL_get_error() to detect if a clean shutdown has occured
		if (SSL_write (ctx->ssl, str.str, str.len) != (int) str.len)
		{
			print_debug ("%s: %s: %s", __func__, "SSL_write",
				ERR_error_string (ERR_get_error (), NULL));
			result = false;
		}
	}
	else if (write (ctx->irc_fd, str.str, str.len) != (ssize_t) str.len)
	{
		print_debug ("%s: %s: %s", __func__, "write", strerror (errno));
		result = false;
	}

	str_free (&str);
	return result;
}

static bool
irc_get_boolean_from_config
	(struct app_context *ctx, const char *name, bool *value, struct error **e)
{
	const char *str = str_map_find (&ctx->config, name);
	hard_assert (str != NULL);

	if (set_boolean_if_valid (value, str))
		return true;

	error_set (e, "invalid configuration value for `%s'", name);
	return false;
}

static bool
irc_initialize_ssl_ctx (struct app_context *ctx, struct error **e)
{
	// XXX: maybe we should call SSL_CTX_set_options() for some workarounds

	bool verify;
	if (!irc_get_boolean_from_config (ctx, "ssl_verify", &verify, e))
		return false;

	if (!verify)
		SSL_CTX_set_verify (ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);

	const char *ca_file = str_map_find (&ctx->config, "ca_file");
	const char *ca_path = str_map_find (&ctx->config, "ca_path");

	struct error *error = NULL;
	if (ca_file || ca_path)
	{
		if (SSL_CTX_load_verify_locations (ctx->ssl_ctx, ca_file, ca_path))
			return true;

		error_set (&error, "%s: %s",
			"Failed to set locations for the CA certificate bundle",
			ERR_reason_error_string (ERR_get_error ()));
		goto ca_error;
	}

	if (!SSL_CTX_set_default_verify_paths (ctx->ssl_ctx))
	{
		error_set (&error, "%s: %s",
			"Couldn't load the default CA certificate bundle",
			ERR_reason_error_string (ERR_get_error ()));
		goto ca_error;
	}
	return true;

ca_error:
	if (verify)
	{
		error_propagate (e, error);
		return false;
	}

	// Only inform the user if we're not actually verifying
	buffer_send_error (ctx, ctx->server_buffer, "%s", error->message);
	error_free (error);
	return true;
}

static bool
irc_initialize_ssl (struct app_context *ctx, struct error **e)
{
	const char *error_info = NULL;
	ctx->ssl_ctx = SSL_CTX_new (SSLv23_client_method ());
	if (!ctx->ssl_ctx)
		goto error_ssl_1;
	if (!irc_initialize_ssl_ctx (ctx, e))
		goto error_ssl_2;

	ctx->ssl = SSL_new (ctx->ssl_ctx);
	if (!ctx->ssl)
		goto error_ssl_2;

	const char *ssl_cert = str_map_find (&ctx->config, "ssl_cert");
	if (ssl_cert)
	{
		char *path = resolve_config_filename (ssl_cert);
		if (!path)
			buffer_send_error (ctx, ctx->global_buffer,
				"%s: %s", "Cannot open file", ssl_cert);
		// XXX: perhaps we should read the file ourselves for better messages
		else if (!SSL_use_certificate_file (ctx->ssl, path, SSL_FILETYPE_PEM)
			|| !SSL_use_PrivateKey_file (ctx->ssl, path, SSL_FILETYPE_PEM))
			buffer_send_error (ctx, ctx->global_buffer,
				"%s: %s", "Setting the SSL client certificate failed",
				ERR_error_string (ERR_get_error (), NULL));
		free (path);
	}

	SSL_set_connect_state (ctx->ssl);
	if (!SSL_set_fd (ctx->ssl, ctx->irc_fd))
		goto error_ssl_3;
	// Avoid SSL_write() returning SSL_ERROR_WANT_READ
	SSL_set_mode (ctx->ssl, SSL_MODE_AUTO_RETRY);

	switch (xssl_get_error (ctx->ssl, SSL_connect (ctx->ssl), &error_info))
	{
	case SSL_ERROR_NONE:
		return true;
	case SSL_ERROR_ZERO_RETURN:
		error_info = "server closed the connection";
	default:
		break;
	}

error_ssl_3:
	SSL_free (ctx->ssl);
	ctx->ssl = NULL;
error_ssl_2:
	SSL_CTX_free (ctx->ssl_ctx);
	ctx->ssl_ctx = NULL;
error_ssl_1:
	// XXX: these error strings are really nasty; also there could be
	//   multiple errors on the OpenSSL stack.
	if (!error_info)
		error_info = ERR_error_string (ERR_get_error (), NULL);
	error_set (e, "%s: %s", "could not initialize SSL", error_info);
	return false;
}

static bool
irc_establish_connection (struct app_context *ctx,
	const char *host, const char *port, struct error **e)
{
	struct addrinfo gai_hints, *gai_result, *gai_iter;
	memset (&gai_hints, 0, sizeof gai_hints);
	gai_hints.ai_socktype = SOCK_STREAM;

	int err = getaddrinfo (host, port, &gai_hints, &gai_result);
	if (err)
	{
		error_set (e, "%s: %s: %s",
			"connection failed", "getaddrinfo", gai_strerror (err));
		return false;
	}

	int sockfd;
	for (gai_iter = gai_result; gai_iter; gai_iter = gai_iter->ai_next)
	{
		sockfd = socket (gai_iter->ai_family,
			gai_iter->ai_socktype, gai_iter->ai_protocol);
		if (sockfd == -1)
			continue;
		set_cloexec (sockfd);

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

		const char *real_host = host;

		// Let's try to resolve the address back into a real hostname;
		// we don't really need this, so we can let it quietly fail
		char buf[NI_MAXHOST];
		err = getnameinfo (gai_iter->ai_addr, gai_iter->ai_addrlen,
			buf, sizeof buf, NULL, 0, NI_NUMERICHOST);
		if (err)
			print_debug ("%s: %s", "getnameinfo", gai_strerror (err));
		else
			real_host = buf;

		char *address = format_host_port_pair (real_host, port);
		buffer_send_status (ctx, ctx->server_buffer,
			"Connecting to %s...", address);
		free (address);

		if (!connect (sockfd, gai_iter->ai_addr, gai_iter->ai_addrlen))
			break;

		xclose (sockfd);
	}

	freeaddrinfo (gai_result);

	if (!gai_iter)
	{
		error_set (e, "connection failed");
		return false;
	}

	ctx->irc_fd = sockfd;
	return true;
}

// --- More readline funky stuff -----------------------------------------------

static char *
make_unseen_prefix (struct app_context *ctx)
{
	struct str active_buffers;
	str_init (&active_buffers);

	size_t i = 0;
	LIST_FOR_EACH (struct buffer, iter, ctx->buffers)
	{
		i++;
		if (!iter->unseen_messages_count)
			continue;

		if (active_buffers.len)
			str_append_c (&active_buffers, ',');
		str_append_printf (&active_buffers, "%zu", i);
	}

	if (active_buffers.len)
		return str_steal (&active_buffers);

	str_free (&active_buffers);
	return NULL;
}

static void
make_prompt (struct app_context *ctx, struct str *output)
{
	struct buffer *buffer = ctx->current_buffer;
	if (!soft_assert (buffer))
		return;

	str_append_c (output, '[');

	char *unseen_prefix = make_unseen_prefix (ctx);
	if (unseen_prefix)
		str_append_printf (output, "(%s) ", unseen_prefix);
	free (unseen_prefix);

	str_append_printf (output, "%d:%s",
		buffer_get_index (ctx, buffer), buffer->name);
	if (buffer->type == BUFFER_CHANNEL && *buffer->channel->mode)
		str_append_printf (output, "(%s)", buffer->channel->mode);

	if (buffer != ctx->global_buffer)
	{
		str_append_c (output, ' ');
		if (!ctx->irc_fd == -1)
			str_append (output, "(disconnected)");
		else
		{
			str_append (output, ctx->irc_user->nickname);
			if (*ctx->irc_user_mode)
				str_append_printf (output, "(%s)", ctx->irc_user_mode);
		}
	}

	str_append_c (output, ']');
}

static void
refresh_prompt (struct app_context *ctx)
{
	bool have_attributes = !!get_attribute_printer (stdout);

	struct str prompt;
	str_init (&prompt);
	make_prompt (ctx, &prompt);
	str_append_c (&prompt, ' ');

	// After building the new prompt, replace the old one
	free (ctx->readline_prompt);

	if (!have_attributes)
		ctx->readline_prompt = xstrdup (prompt.str);
	else
	{
		// XXX: to be completely correct, we should use tputs, but we cannot
		const char *prompt_attrs = str_map_find (&ctx->config, ATTR_PROMPT);
		const char *reset_attrs  = str_map_find (&ctx->config, ATTR_RESET);
		ctx->readline_prompt = xstrdup_printf ("%c%s%c%s%c%s%c",
			RL_PROMPT_START_IGNORE, prompt_attrs, RL_PROMPT_END_IGNORE,
			prompt.str,
			RL_PROMPT_START_IGNORE, reset_attrs,  RL_PROMPT_END_IGNORE);
	}
	str_free (&prompt);

	// First reset the prompt to work around a bug in readline
	rl_set_prompt ("");
	if (ctx->readline_prompt_shown)
		rl_redisplay ();

	rl_set_prompt (ctx->readline_prompt);
	if (ctx->readline_prompt_shown)
		rl_redisplay ();
}

static int
on_readline_goto_buffer (int count, int key)
{
	(void) count;

	int n = UNMETA (key) - '0';
	if (n < 0 || n > 9)
		return 0;

	struct app_context *ctx = g_ctx;
	if (!buffer_goto (ctx, n == 0 ? 10 : n))
		rl_ding ();
	return 0;
}

static int
on_readline_previous_buffer (int count, int key)
{
	(void) key;

	struct app_context *ctx = g_ctx;
	if (ctx->current_buffer)
		buffer_activate (ctx, buffer_previous (ctx, count));
	return 0;
}

static int
on_readline_next_buffer (int count, int key)
{
	(void) key;

	struct app_context *ctx = g_ctx;
	if (ctx->current_buffer)
		buffer_activate (ctx, buffer_next (ctx, count));
	return 0;
}

static int
on_readline_return (int count, int key)
{
	(void) count;
	(void) key;

	struct app_context *ctx = g_ctx;

	// Let readline pass the line to our input handler
	rl_done = 1;

	// Save readline state
	int saved_point = rl_point;
	int saved_mark = rl_mark;
	char *saved_line = rl_copy_text (0, rl_end);

	// Erase the entire line from screen
	rl_set_prompt ("");
	rl_replace_line ("", 0);
	rl_redisplay ();
	ctx->readline_prompt_shown = false;

	// Restore readline state
	rl_set_prompt (ctx->readline_prompt);
	rl_replace_line (saved_line, 0);
	rl_point = saved_point;
	rl_mark = saved_mark;
	free (saved_line);
	return 0;
}

static void
app_readline_bind_meta (char key, rl_command_func_t cb)
{
	// One of these is going to work
	char keyseq[] = { '\\', 'e', key, 0 };
	rl_bind_key (META (key), cb);
	rl_bind_keyseq (keyseq, cb);
}

static int
init_readline (void)
{
	// XXX: maybe use rl_make_bare_keymap() and start from there;
	//   our dear user could potentionally rig things up in a way that might
	//   result in some funny unspecified behaviour

	rl_add_defun ("previous-buffer", on_readline_previous_buffer, -1);
	rl_add_defun ("next-buffer", on_readline_next_buffer, -1);

	// Redefine M-0 through M-9 to switch buffers
	for (int i = 0; i <= 9; i++)
		app_readline_bind_meta ('0' + i, on_readline_goto_buffer);

	rl_bind_keyseq ("\\C-p", rl_named_function ("previous-buffer"));
	rl_bind_keyseq ("\\C-n", rl_named_function ("next-buffer"));
	app_readline_bind_meta ('p', rl_named_function ("previous-history"));
	app_readline_bind_meta ('n', rl_named_function ("next-history"));

	// We need to hide the prompt first
	rl_bind_key (RETURN, on_readline_return);

	return 0;
}

// --- Input handling ----------------------------------------------------------

// TODO: we will need a proper mode parser; to be shared with kike
// TODO: we alse definitely need to parse server capability messages

static char *
irc_to_utf8 (struct app_context *ctx, const char *text)
{
	size_t len = strlen (text) + 1;
	if (utf8_validate (text, len))
		return xstrdup (text);
	return iconv_xstrdup (ctx->latin1_to_utf8, (char *) text, len, NULL);
}

static void
irc_handle_join (struct app_context *ctx, const struct irc_message *msg)
{
	if (!msg->prefix || msg->params.len < 1)
		return;

	const char *channel_name = msg->params.vector[0];
	if (!irc_is_channel (ctx, channel_name))
		return;

	struct channel *channel = str_map_find (&ctx->irc_channels, channel_name);
	struct buffer *buffer = str_map_find (&ctx->irc_buffer_map, channel_name);
	hard_assert ((channel && buffer) ||
		(channel && !buffer) || (!channel && !buffer));

	// We've joined a new channel
	if (!channel && irc_is_this_us (ctx, msg->prefix))
	{
		channel = irc_make_channel (ctx, xstrdup (channel_name));

		buffer = buffer_new ();
		buffer->type = BUFFER_CHANNEL;
		buffer->name = xstrdup (channel_name);
		buffer->channel = channel_ref (channel);
		LIST_APPEND_WITH_TAIL (ctx->buffers, ctx->buffers_tail, buffer);
		str_map_set (&ctx->irc_buffer_map, channel->name, buffer);

		buffer_activate (ctx, buffer);
	}

	// This is weird, ignoring
	if (!channel)
		return;

	// Get or make a user object
	char *nickname = irc_cut_nickname (msg->prefix);
	struct user *user = str_map_find (&ctx->irc_users, nickname);
	if (!user)
		user = irc_make_user (ctx, nickname);
	else
		free (nickname);

	// Link the user with the channel
	struct user_channel *user_channel = user_channel_new ();
	user_channel->channel = channel_ref (channel);
	LIST_PREPEND (user->channels, user_channel);

	struct channel_user *channel_user = channel_user_new ();
	channel_user->user = user_ref (user);
	channel_user->modes = xstrdup ("");
	LIST_PREPEND (channel->users, channel_user);

	// Finally log the message
	if (buffer)
	{
		buffer_send (ctx, buffer, BUFFER_LINE_JOIN, 0,
			msg->prefix, NULL, "%s", channel_name);
	}
}

static void
irc_handle_kick (struct app_context *ctx, const struct irc_message *msg)
{
	if (!msg->prefix || msg->params.len < 2)
		return;

	const char *channel_name = msg->params.vector[0];
	const char *target = msg->params.vector[1];
	if (!irc_is_channel (ctx, channel_name)
	 || irc_is_channel (ctx, target))
		return;

	const char *message = NULL;
	if (msg->params.len > 2)
		message = msg->params.vector[2];

	struct user *user = str_map_find (&ctx->irc_users, target);
	struct channel *channel = str_map_find (&ctx->irc_channels, channel_name);
	struct buffer *buffer = str_map_find (&ctx->irc_buffer_map, channel_name);
	hard_assert ((channel && buffer) ||
		(channel && !buffer) || (!channel && !buffer));

	// It would be is weird for this to be false
	if (user && channel)
		irc_unlink_user_from_channel (user, channel);

	if (buffer)
	{
		buffer_send (ctx, buffer, BUFFER_LINE_KICK, 0,
			msg->prefix, message, "%s", target);
	}
}

static void
irc_handle_mode (struct app_context *ctx, const struct irc_message *msg)
{
	// TODO: parse the mode change and apply it
	// TODO: log a message
}

static void
irc_handle_nick (struct app_context *ctx, const struct irc_message *msg)
{
	if (!msg->prefix || msg->params.len < 1)
		return;

	const char *new_nickname = msg->params.vector[0];

	char *nickname = irc_cut_nickname (msg->prefix);
	struct user *user = str_map_find (&ctx->irc_users, nickname);
	free (nickname);
	if (!user)
		return;

	// What the fuck
	// TODO: probably log a message and force a reconnect
	if (str_map_find (&ctx->irc_users, new_nickname))
		return;

	// Log a message in any PM buffer and rename it;
	// we may even have one for ourselves
	struct buffer *pm_buffer =
		str_map_find (&ctx->irc_buffer_map, user->nickname);
	if (pm_buffer)
	{
		str_map_set (&ctx->irc_buffer_map, new_nickname, user_ref (user));
		str_map_set (&ctx->irc_buffer_map, user->nickname, NULL);

		buffer_send (ctx, pm_buffer, BUFFER_LINE_NICK, 0,
			msg->prefix, NULL, "%s", new_nickname);
		// TODO: use a full weechat-style buffer name here
		buffer_rename (ctx, pm_buffer, new_nickname);
	}

	if (irc_is_this_us (ctx, msg->prefix))
	{
		// Log a message in all open buffers on this server
		struct str_map_iter iter;
		str_map_iter_init (&iter, &ctx->irc_buffer_map);
		struct buffer *buffer;
		while ((buffer = str_map_iter_next (&iter)))
		{
			// We've already done that
			if (buffer == pm_buffer)
				continue;

			buffer_send (ctx, buffer, BUFFER_LINE_NICK, 0,
				NULL, NULL, "%s", new_nickname);
		}
	}
	else
	{
		// Log a message in all channels the user is in
		LIST_FOR_EACH (struct user_channel, iter, user->channels)
		{
			struct buffer *buffer =
				str_map_find (&ctx->irc_buffer_map, iter->channel->name);
			hard_assert (buffer != NULL);
			buffer_send (ctx, buffer, BUFFER_LINE_NICK, 0,
				msg->prefix, NULL, "%s", new_nickname);
		}
	}

	// Finally rename the user
	str_map_set (&ctx->irc_users, new_nickname, user_ref (user));
	str_map_set (&ctx->irc_users, user->nickname, NULL);

	free (user->nickname);
	user->nickname = xstrdup (new_nickname);

	// We might have renamed ourselves
	refresh_prompt (ctx);
}

static void
irc_handle_notice (struct app_context *ctx, const struct irc_message *msg)
{
	// TODO: log a message
}

static void
irc_handle_part (struct app_context *ctx, const struct irc_message *msg)
{
	if (!msg->prefix || msg->params.len < 1)
		return;

	const char *channel_name = msg->params.vector[0];
	if (!irc_is_channel (ctx, channel_name))
		return;

	const char *message = NULL;
	if (msg->params.len > 1)
		message = msg->params.vector[1];

	char *nickname = irc_cut_nickname (msg->prefix);
	struct user *user = str_map_find (&ctx->irc_users, nickname);
	free (nickname);

	struct channel *channel = str_map_find (&ctx->irc_channels, channel_name);
	struct buffer *buffer = str_map_find (&ctx->irc_buffer_map, channel_name);
	hard_assert ((channel && buffer) ||
		(channel && !buffer) || (!channel && !buffer));

	// It would be is weird for this to be false
	if (user && channel)
		irc_unlink_user_from_channel (user, channel);

	if (buffer)
	{
		buffer_send (ctx, buffer, BUFFER_LINE_PART, 0,
			msg->prefix, message, "%s", channel_name);
	}
}

static void
irc_handle_ping (struct app_context *ctx, const struct irc_message *msg)
{
	if (msg->params.len)
		irc_send (ctx, "PONG :%s", msg->params.vector[0]);
	else
		irc_send (ctx, "PONG");
}

static void
irc_handle_privmsg (struct app_context *ctx, const struct irc_message *msg)
{
	if (!msg->prefix || msg->params.len < 2)
		return;

	const char *target = msg->params.vector[0];
	const char *message = msg->params.vector[1];
	struct buffer *buffer = str_map_find (&ctx->irc_buffer_map, target);

	if (irc_is_channel (ctx, target))
	{
		struct channel *channel = str_map_find (&ctx->irc_channels, target);
		hard_assert ((channel && buffer) ||
			(channel && !buffer) || (!channel && !buffer));

		// This is weird, ignoring
		if (!channel)
			return;
	}
	else if (!buffer)
	{
		char *nickname = irc_cut_nickname (msg->prefix);
		buffer = irc_get_user_buffer (ctx, nickname);
		free (nickname);
	}

	if (buffer)
	{
		// TODO: handle CTCP messages
		// TODO: highlights
		buffer_send (ctx, buffer, BUFFER_LINE_PRIVMSG, 0,
			msg->prefix, NULL, "%s", message);
	}
}

static void
irc_handle_quit (struct app_context *ctx, const struct irc_message *msg)
{
	if (!msg->prefix)
		return;

	// What the fuck
	if (irc_is_this_us (ctx, msg->prefix))
		return;

	char *nickname = irc_cut_nickname (msg->prefix);
	struct user *user = str_map_find (&ctx->irc_users, nickname);
	free (nickname);
	if (!user)
		return;

	const char *message = NULL;
	if (msg->params.len > 0)
		message = msg->params.vector[0];

	// Log a message in any PM buffer
	struct buffer *buffer =
		str_map_find (&ctx->irc_buffer_map, user->nickname);
	if (buffer)
	{
		buffer_send (ctx, buffer, BUFFER_LINE_QUIT, 0,
			msg->prefix, message, "");

		// TODO: set some kind of a flag in the buffer and when the user
		//   reappers on a channel (JOIN), log a "is back online" message.
		//   Also set this flag when we receive a "no such nick" numeric
		//   and reset it when we send something to the buffer.
	}

	// Log a message in all channels the user is in
	LIST_FOR_EACH (struct user_channel, iter, user->channels)
	{
		buffer = str_map_find (&ctx->irc_buffer_map, iter->channel->name);
		if (buffer)
			buffer_send (ctx, buffer, BUFFER_LINE_QUIT, 0,
				msg->prefix, message, "");

		// Unlink the user from the channel
		struct channel *channel = iter->channel;
		LIST_FOR_EACH (struct channel_user, iter, channel->users)
			if (iter->user == user)
			{
				LIST_UNLINK (channel->users, iter);
				channel_user_destroy (iter);
			}

		LIST_UNLINK (user->channels, iter);
		user_channel_destroy (iter);
	}
}

static void
irc_handle_topic (struct app_context *ctx, const struct irc_message *msg)
{
	if (!msg->prefix || msg->params.len < 2)
		return;

	const char *channel_name = msg->params.vector[0];
	const char *topic = msg->params.vector[1];
	if (!irc_is_channel (ctx, channel_name))
		return;

	struct channel *channel = str_map_find (&ctx->irc_channels, channel_name);
	struct buffer *buffer = str_map_find (&ctx->irc_buffer_map, channel_name);
	hard_assert ((channel && buffer) ||
		(channel && !buffer) || (!channel && !buffer));

	// It would be is weird for this to be false
	if (channel)
	{
		free (channel->topic);
		channel->topic = xstrdup (topic);
	}

	if (buffer)
	{
		buffer_send (ctx, buffer, BUFFER_LINE_TOPIC, 0,
			msg->prefix, NULL, "%s", topic);
	}
}

static struct irc_handler
{
	char *name;
	void (*handler) (struct app_context *ctx, const struct irc_message *msg);
}
g_irc_handlers[] =
{
	// This list needs to stay sorted
	{ "JOIN",    irc_handle_join    },
	{ "KICK",    irc_handle_kick    },
	{ "MODE",    irc_handle_mode    },
	{ "NICK",    irc_handle_nick    },
	{ "NOTICE",  irc_handle_notice  },
	{ "PART",    irc_handle_part    },
	{ "PING",    irc_handle_ping    },
	{ "PRIVMSG", irc_handle_privmsg },
	{ "QUIT",    irc_handle_quit    },
	{ "TOPIC",   irc_handle_topic   },
};

static int
irc_handler_cmp_by_name (const void *a, const void *b)
{
	const struct irc_handler *first  = a;
	const struct irc_handler *second = b;
	return strcasecmp_ascii (first->name, second->name);
}

static bool
irc_try_parse_word_for_userhost (struct app_context *ctx, const char *word)
{
	regex_t re;
	int err = regcomp (&re, "^[^!@]+!([^!@]+@[^!@]+)$", REG_EXTENDED);
	if (!soft_assert (!err))
		return false;

	regmatch_t matches[2];
	bool result = false;
	if (!regexec (&re, word, 2, matches, 0))
	{
		free (ctx->irc_user_host);
		ctx->irc_user_host = xstrndup (word + matches[1].rm_so,
			matches[1].rm_eo - matches[1].rm_so);
		result = true;
	}
	regfree (&re);
	return result;
}

static void
irc_try_parse_welcome_for_userhost (struct app_context *ctx, const char *m)
{
	struct str_vector v;
	str_vector_init (&v);
	split_str_ignore_empty (m, ' ', &v);
	for (size_t i = 0; i < v.len; i++)
		if (irc_try_parse_word_for_userhost (ctx, v.vector[i]))
			break;
	str_vector_free (&v);
}

static void
irc_process_numeric (struct app_context *ctx,
	const struct irc_message *msg, unsigned long numeric)
{
	// Numerics typically have human-readable information
	// TODO: try to output certain replies in more specific buffers

	// Get rid of the first parameter, if there's any at all,
	// as it contains our nickname and is of no practical use to the user
	struct str_vector copy;
	str_vector_init (&copy);
	str_vector_add_vector (&copy, msg->params.vector + !!msg->params.len);

	// Join the parameter vector back, recode it to our internal encoding
	// and send it to the server buffer
	char *reconstructed = join_str_vector (&copy, ' ');
	str_vector_free (&copy);
	char *utf8 = irc_to_utf8 (ctx, reconstructed);
	free (reconstructed);
	buffer_send_status (ctx, ctx->server_buffer, "%s", utf8);
	free (utf8);

	switch (numeric)
	{
	case IRC_RPL_WELCOME:
		// We still issue a USERHOST anyway as this is in general unreliable
		if (msg->params.len == 1)
			irc_try_parse_welcome_for_userhost (ctx, msg->params.vector[0]);
		break;
	case IRC_RPL_ISUPPORT:
		// TODO: parse this, mainly PREFIX; see
		//   http://www.irc.org/tech_docs/draft-brocklesby-irc-isupport-03.txt
		break;
	case IRC_RPL_NAMREPLY:
		// TODO: find the channel and if found, push nicks to names_buf
		break;
	case IRC_RPL_ENDOFNAMES:
		// TODO: find the channel and if found, overwrite users;
		//   however take care to combine channel user modes
		break;
	case IRC_ERR_NICKNAMEINUSE:
		// TODO: if not connected yet (irc_ready), use a different nick;
		//   either use a number suffix, or accept commas in "nickname" config
		break;
	}
}

static void
irc_process_message (const struct irc_message *msg,
	const char *raw, void *user_data)
{
	struct app_context *ctx = user_data;

	if (g_debug_mode)
	{
		struct app_readline_state state;
		if (ctx->readline_prompt_shown)
			app_readline_hide (&state);

		char *utf8 = irc_to_utf8 (ctx, raw);
		fprintf (stderr, "[IRC] ==> \"%s\"\n", utf8);
		free (utf8);

		if (ctx->readline_prompt_shown)
			app_readline_restore (&state, ctx->readline_prompt);
	}

	// XXX: or is the 001 numeric enough?  For what?
	if (!ctx->irc_ready && (!strcasecmp (msg->command, "MODE")
		|| !strcasecmp (msg->command, "376")    // RPL_ENDOFMOTD
		|| !strcasecmp (msg->command, "422")))  // ERR_NOMOTD
	{
		// XXX: should we really print this?
		buffer_send_status (ctx, ctx->server_buffer, "Successfully connected");
		ctx->irc_ready = true;
		refresh_prompt (ctx);

		// TODO: parse any response and store the result for us in app_context;
		//   this enables proper message splitting on output;
		//   we can also use WHOIS if it's not supported (optional by RFC 2812)
		irc_send (ctx, "USERHOST %s", ctx->irc_user->nickname);

		const char *autojoin = str_map_find (&ctx->config, "autojoin");
		if (autojoin)
			irc_send (ctx, "JOIN :%s", autojoin);
	}

	struct irc_handler key = { .name = msg->command };
	struct irc_handler *handler = bsearch (&key, g_irc_handlers,
		N_ELEMENTS (g_irc_handlers), sizeof key, irc_handler_cmp_by_name);
	if (handler)
		handler->handler (ctx, msg);

	unsigned long numeric;
	if (xstrtoul (&numeric, msg->command, 10))
		irc_process_numeric (ctx, msg, numeric);
}

// --- Message autosplitting magic ---------------------------------------------

static bool
wrap_text (const char *message,
	int line_max, struct str_vector *output, struct error **e)
{
	// Attempt to split the message if it doesn't completely fit into a single
	// IRC protocol message while trying not to break UTF-8.  Unicode can still
	// end up being wrong, though.  As well as any mIRC formatting.
	//
	// TODO: at least try to word-wrap if nothing else

	for (int message_left = strlen (message); message_left; )
	{
		struct str m;
		str_init (&m);

		int part_left = MIN (line_max, message_left);
		bool empty = true;
		while (true)
		{
			const char *next = utf8_next (message, message_left);
			hard_assert (next);

			int char_len = message - next;
			if (char_len > part_left)
				break;

			str_append_data (&m, message, char_len);

			message += char_len;
			message_left -= char_len;
			empty = false;
		}

		if (!empty)
			str_vector_add (output, m.str);

		str_free (&m);

		if (empty)
		{
			// Well, that's just weird
			error_set (e,
				"Message splitting was unsuccessful as there was "
				"too little room for UTF-8 characters");
			return false;
		}
	}
	return true;
}

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

/// Automatically splits messages that arrive at other clients with our prefix
/// so that they don't arrive cut off by the server
static bool
irc_autosplit_message (struct app_context *ctx, const char *message,
	int fixed_part, struct str_vector *output, struct error **e)
{
	// :<nick>!<user>@<host> <fixed-part><message>
	int space_in_one_message = 0;
	if (ctx->irc_user_host)
		space_in_one_message = 510
			- 1 - (int) strlen (ctx->irc_user->nickname)
			- 1 - (int) strlen (ctx->irc_user_host)
			- 1 - fixed_part;

	// However we don't always have the full info for message splitting
	if (!space_in_one_message)
		str_vector_add (output, message);
	else if (!wrap_text (message, space_in_one_message, output, e))
		return false;
	return true;
}

struct send_autosplit_args;

typedef void (*send_autosplit_logger_fn) (struct app_context *ctx,
	struct send_autosplit_args *args, struct buffer *buffer, const char *line);

struct send_autosplit_args
{
	const char *command;                ///< E.g. PRIVMSG or NOTICE
	const char *target;                 ///< User or channel
	const char *message;                ///< A message to be autosplit
	send_autosplit_logger_fn logger;    ///< Logger for all resulting lines
};

static void
send_autosplit_message (struct app_context *ctx, struct send_autosplit_args a)
{
	struct buffer *buffer = str_map_find (&ctx->irc_buffer_map, a.target);
	int fixed_part = strlen (a.command) + 1 + strlen (a.target) + 1 + 1;

	struct str_vector lines;
	str_vector_init (&lines);
	struct error *e = NULL;
	if (!irc_autosplit_message (ctx, a.message, fixed_part, &lines, &e))
	{
		buffer_send_error (ctx,
			buffer ? buffer : ctx->server_buffer, "%s", e->message);
		error_free (e);
		goto end;
	}

	for (size_t i = 0; i < lines.len; i++)
	{
		irc_send (ctx, "%s %s :%s", a.command, a.target, lines.vector[i]);
		a.logger (ctx, &a, buffer, lines.vector[i]);
	}
end:
	str_vector_free (&lines);
}

static void
log_outcoming_privmsg (struct app_context *ctx,
	struct send_autosplit_args *a, struct buffer *buffer, const char *line)
{
	if (buffer)
		buffer_send (ctx, buffer, BUFFER_LINE_PRIVMSG, 0,
			ctx->irc_user->nickname, NULL, "%s", line);
	else
		// TODO: fix logging
		buffer_send (ctx, ctx->server_buffer, BUFFER_LINE_STATUS, 0,
			NULL, NULL, "MSG(%s): %s", a->target, line);
}

#define SEND_AUTOSPLIT_PRIVMSG(ctx, target, message)                           \
	send_autosplit_message ((ctx), (struct send_autosplit_args)                \
		{ "PRIVMSG", (target), (message), log_outcoming_privmsg })

static void
log_outcoming_notice (struct app_context *ctx,
	struct send_autosplit_args *a, struct buffer *buffer, const char *line)
{
	if (buffer)
		buffer_send (ctx, buffer, BUFFER_LINE_NOTICE, 0,
			ctx->irc_user->nickname, NULL, "%s", line);
	else
		// TODO: fix logging
		buffer_send (ctx, ctx->server_buffer, BUFFER_LINE_STATUS, 0,
			NULL, NULL, "Notice -> %s: %s", a->target, line);
}

#define SEND_AUTOSPLIT_NOTICE(ctx, target, message)                            \
	send_autosplit_message ((ctx), (struct send_autosplit_args)                \
		{ "NOTICE", (target), (message), log_outcoming_notice })

// --- User input handling -----------------------------------------------------

static void handle_command_help (struct app_context *, char *);

/// Cuts the longest non-whitespace portion of text and advances the pointer
static char *
cut_word (char **s)
{
	char *start = *s;
	size_t word_len = strcspn (*s, " \t");
	char *end = start + word_len;
	*s = end + strspn (end, " \t");
	*end = '\0';
	return start;
}

static bool
try_handle_buffer_goto (struct app_context *ctx, const char *word)
{
	unsigned long n;
	if (!xstrtoul (&n, word, 10))
		return false;

	if (n > INT_MAX || !buffer_goto (ctx, n))
		buffer_send_error (ctx, ctx->global_buffer,
			"%s: %s", "no such buffer", word);
	return true;
}

static struct buffer *
try_decode_buffer (struct app_context *ctx, const char *word)
{
	unsigned long n;
	struct buffer *buffer = NULL;
	if (xstrtoul (&n, word, 10) && n <= INT_MAX)
		buffer = buffer_at_index (ctx, n);
	if (!buffer)
		buffer = buffer_by_name (ctx, word);
	// TODO: decode the global and server buffers, partial matches
	return buffer;
}

static void
handle_command_buffer (struct app_context *ctx, char *arguments)
{
	char *action = cut_word (&arguments);
	if (try_handle_buffer_goto (ctx, action))
		return;

	struct buffer *buffer = NULL;

	// XXX: also build a prefix map?
	//   It looks like we'll want to split this into functions anyway.
	// TODO: some subcommand to print N last lines from the buffer
	if (!strcasecmp_ascii (action, "list"))
	{
		buffer_send_status (ctx, ctx->global_buffer, "Buffers list:");

		int i = 1;
		LIST_FOR_EACH (struct buffer, iter, ctx->buffers)
			buffer_send_status (ctx, ctx->global_buffer,
				"  [%d] %s", i++, iter->name);
	}
	else if (!strcasecmp_ascii (action, "clear"))
	{
		// TODO
	}
	else if (!strcasecmp_ascii (action, "move"))
	{
		// TODO: unlink the buffer and link it back at index;
		//   we will probably need to extend liberty for this
	}
	else if (!strcasecmp_ascii (action, "close"))
	{
		const char *which = NULL;
		if (!*arguments)
			buffer = ctx->current_buffer;
		else
			buffer = try_decode_buffer (ctx, (which = cut_word (&arguments)));

		if (!buffer)
		{
			buffer_send_error (ctx, ctx->global_buffer,
				"%s: %s", "No such buffer", which);
			return;
		}
		if (buffer == ctx->global_buffer)
		{
			buffer_send_error (ctx, ctx->global_buffer,
				"Can't close the global buffer");
			return;
		}
		if (buffer == ctx->server_buffer)
		{
			buffer_send_error (ctx, ctx->global_buffer,
				"Can't close the server buffer");
			return;
		}

		if (buffer == ctx->current_buffer)
			buffer_activate (ctx, buffer_next (ctx, 1));
		buffer_remove (ctx, buffer);
	}
	else
	{
		// TODO: show usage (or do something else?)
	}
}

static void
handle_command_msg (struct app_context *ctx, char *arguments)
{
	if (ctx->current_buffer->type == BUFFER_GLOBAL)
	{
		buffer_send_error (ctx, ctx->current_buffer,
			"Can't send messages from a global buffer");
		return;
	}

	if (ctx->irc_fd == -1)
	{
		buffer_send_error (ctx, ctx->server_buffer, "Not connected");
		return;
	}

	if (!*arguments)
	{
		// TODO: show usage or something
		return;
	}

	char *target = cut_word (&arguments);
	if (!*arguments)
		buffer_send_error (ctx, ctx->server_buffer, "No text to send");
	else
		SEND_AUTOSPLIT_PRIVMSG (ctx, target, arguments);
}

static void
handle_command_query (struct app_context *ctx, char *arguments)
{
	if (ctx->current_buffer->type == BUFFER_GLOBAL)
	{
		buffer_send_error (ctx, ctx->current_buffer,
			"Can't send messages from a global buffer");
		return;
	}

	if (ctx->irc_fd == -1)
	{
		buffer_send_error (ctx, ctx->server_buffer, "Not connected");
		return;
	}

	if (!*arguments)
	{
		// TODO: show usage or something
		return;
	}

	char *target = cut_word (&arguments);
	if (irc_is_channel (ctx, target))
	{
		buffer_send_error (ctx, ctx->server_buffer, "Cannot query a channel");
		return;
	}

	if (!*arguments)
		buffer_send_error (ctx, ctx->server_buffer, "No text to send");
	else
	{
		buffer_activate (ctx, irc_get_user_buffer (ctx, target));
		SEND_AUTOSPLIT_PRIVMSG (ctx, target, arguments);
	}
}

static void
handle_command_notice (struct app_context *ctx, char *arguments)
{
	if (ctx->current_buffer->type == BUFFER_GLOBAL)
	{
		buffer_send_error (ctx, ctx->current_buffer,
			"Can't send messages from a global buffer");
		return;
	}

	if (ctx->irc_fd == -1)
	{
		buffer_send_error (ctx, ctx->server_buffer, "Not connected");
		return;
	}

	if (!*arguments)
	{
		// TODO: show usage or something
		return;
	}

	char *target = cut_word (&arguments);
	if (!*arguments)
		buffer_send_error (ctx, ctx->server_buffer, "No text to send");
	else
		SEND_AUTOSPLIT_NOTICE (ctx, target, arguments);
}

static void
handle_command_quit (struct app_context *ctx, char *arguments)
{
	if (ctx->irc_fd != -1)
	{
		if (*arguments)
			irc_send (ctx, "QUIT :%s", arguments);
		else
			irc_send (ctx, "QUIT :%s", PROGRAM_NAME " " PROGRAM_VERSION);
	}
	initiate_quit (ctx);
}

static void
handle_command_join (struct app_context *ctx, char *arguments)
{
	if (ctx->current_buffer->type == BUFFER_GLOBAL)
	{
		buffer_send_error (ctx, ctx->current_buffer,
			"Can't join from a global buffer");
		return;
	}

	if (ctx->irc_fd == -1)
	{
		buffer_send_error (ctx, ctx->server_buffer, "Not connected");
		return;
	}

	if (*arguments)
		// TODO: check if the arguments are in the form of
		//   "channel(,channel)* key(,key)*"
		irc_send (ctx, "JOIN %s", arguments);
	else
	{
		if (ctx->current_buffer->type != BUFFER_CHANNEL)
			buffer_send_error (ctx, ctx->current_buffer,
				"%s: %s", "Can't join",
				"no argument given and this buffer is not a channel");
		// TODO: have a better way of checking if we're on the channel
		else if (ctx->current_buffer->channel->users)
			buffer_send_error (ctx, ctx->current_buffer,
				"%s: %s", "Can't join",
				"you already are on the channel");
		else
			// TODO: send the key if known
			irc_send (ctx, "JOIN %s", ctx->current_buffer->channel->name);
	}
}

static void
handle_command_part (struct app_context *ctx, char *arguments)
{
	if (ctx->current_buffer->type == BUFFER_GLOBAL)
	{
		buffer_send_error (ctx, ctx->current_buffer,
			"Can't part from a global buffer");
		return;
	}

	if (ctx->irc_fd == -1)
	{
		buffer_send_error (ctx, ctx->server_buffer, "Not connected");
		return;
	}

	if (*arguments)
		// TODO: check if the arguments are in the form of "channel(,channel)*"
		// TODO: make sure to send the reason as one argument
		irc_send (ctx, "PART %s", arguments);
	else
	{
		if (ctx->current_buffer->type != BUFFER_CHANNEL)
			buffer_send_error (ctx, ctx->current_buffer,
				"%s: %s", "Can't part",
				"no argument given and this buffer is not a channel");
		// TODO: have a better way of checking if we're on the channel
		else if (!ctx->current_buffer->channel->users)
			buffer_send_error (ctx, ctx->current_buffer,
				"%s: %s", "Can't join", "you're not on the channel");
		else
			irc_send (ctx, "PART %s", ctx->current_buffer->channel->name);
	}
}

static void
handle_command_quote (struct app_context *ctx, char *arguments)
{
	if (ctx->current_buffer->type == BUFFER_GLOBAL)
		buffer_send_error (ctx, ctx->current_buffer,
			"Can't do this from a global buffer");
	else
		irc_send (ctx, arguments);
}

static struct command_handler
{
	const char *name;
	void (*handler) (struct app_context *ctx, char *arguments);
	const char *description;
	const char *usage;
}
g_command_handlers[] =
{
	{ "help",    handle_command_help,   "Show help",
	  "[command]" },
	{ "quit",    handle_command_quit,   "Quit the program",
	  "[message]" },
	{ "buffer",  handle_command_buffer, "Manage buffers",
	  "list | clear | move | { close [<number> | <name>] } | <number>" },

	{ "msg",     handle_command_msg,    "Send message to a nick or channel",
	  "<target> <message>" },
	{ "query",   handle_command_query,  "Send a private message to a nick",
	  "<nick> <message>" },
	{ "notice",  handle_command_notice, "Send notice to a nick or channel",
	  "<target> <message>" },
#if 0
	{ "ctcp",    NULL, "", "" },
	{ "me",      NULL, "", "" },
#endif

	{ "join",    handle_command_join,   "Join channels",
	  "[channel...]" },
	{ "part",    handle_command_part,   "Leave channels",
	  "[channel...]" },
#if 0
	{ "cycle",   NULL, "", "" },

	{ "mode",    NULL, "", "" },
	{ "topic",   NULL, "", "" },
	{ "kick",    NULL, "", "" },
	{ "kickban", NULL, "", "" },
	{ "ban",     NULL, "", "" },
	{ "invite",  NULL, "", "" },

	{ "list",    NULL, "", "" },
	{ "names",   NULL, "", "" },
	{ "who",     NULL, "", "" },
	{ "whois",   NULL, "", "" },

	{ "motd",    NULL, "", "" },
	{ "away",    NULL, "", "" },
#endif
	{ "quote",   handle_command_quote,  "Send a raw command to the server",
	  "command" },
};

static void
handle_command_help (struct app_context *ctx, char *arguments)
{
	if (*arguments)
	{
		char *command = cut_word (&arguments);
		// TODO: search for the command and show specific help
		return;
	}

	buffer_send_status (ctx, ctx->global_buffer, "Commands:");
	for (size_t i = 0; i < N_ELEMENTS (g_command_handlers); i++)
	{
		struct command_handler *iter = &g_command_handlers[i];
		buffer_send_status (ctx, ctx->global_buffer,
			"  %s: %s", iter->name, iter->description);
		buffer_send_status (ctx, ctx->global_buffer,
			"    Arguments: %s", iter->usage);
	}
}

static int
command_handler_cmp_by_length (const void *a, const void *b)
{
	const struct command_handler *first  = a;
	const struct command_handler *second = b;
	return strlen (first->name) - strlen (second->name);
}

static void
init_partial_matching_user_command_map (struct str_map *partial)
{
	// Trivially create a partial matching map
	str_map_init (partial);
	partial->key_xfrm = tolower_ascii_strxfrm;

	// We process them from the longest to the shortest one,
	// so that common prefixes favor shorter entries
	struct command_handler *by_length[N_ELEMENTS (g_command_handlers)];
	for (size_t i = 0; i < N_ELEMENTS (by_length); i++)
		by_length[i] = &g_command_handlers[i];
	qsort (by_length, N_ELEMENTS (by_length), sizeof *by_length,
		command_handler_cmp_by_length);

	for (size_t i = N_ELEMENTS (by_length); i--; )
	{
		char *copy = xstrdup (by_length[i]->name);
		for (size_t part = strlen (copy); part; part--)
		{
			copy[part] = '\0';
			str_map_set (partial, copy, by_length[i]);
		}
		free (copy);
	}
}

static void
process_user_command (struct app_context *ctx, char *command)
{
	static bool initialized = false;
	static struct str_map partial;
	if (!initialized)
	{
		init_partial_matching_user_command_map (&partial);
		initialized = true;
	}

	char *name = cut_word (&command);
	if (try_handle_buffer_goto (ctx, name))
		return;

	struct command_handler *handler = str_map_find (&partial, name);
	if (handler)
		handler->handler (ctx, command);
	else
		buffer_send_error (ctx, ctx->global_buffer,
			"%s: %s", "No such command", name);
}

static void
send_message_to_target (struct app_context *ctx,
	const char *target, char *message, struct buffer *buffer)
{
	if (ctx->irc_fd == -1)
	{
		buffer_send_error (ctx, buffer, "Not connected");
		return;
	}

	SEND_AUTOSPLIT_PRIVMSG (ctx, target, message);
}

static void
send_message_to_current_buffer (struct app_context *ctx, char *message)
{
	struct buffer *buffer = ctx->current_buffer;
	hard_assert (buffer != NULL);

	switch (buffer->type)
	{
	case BUFFER_GLOBAL:
	case BUFFER_SERVER:
		buffer_send_error (ctx, buffer, "This buffer is not a channel");
		break;
	case BUFFER_CHANNEL:
		send_message_to_target (ctx, buffer->channel->name, message, buffer);
		break;
	case BUFFER_PM:
		send_message_to_target (ctx, buffer->user->nickname, message, buffer);
		break;
	}
}

static void
process_input (struct app_context *ctx, char *user_input)
{
	char *input;
	size_t len;

	if (!(input = iconv_xstrdup (ctx->term_to_utf8, user_input, -1, &len)))
		print_error ("character conversion failed for `%s'", "user input");
	else if (input[0] != '/')
		send_message_to_current_buffer (ctx, input);
	else if (input[1] == '/')
		send_message_to_current_buffer (ctx, input + 1);
	else
		process_user_command (ctx, input + 1);

	free (input);
}

// --- Supporting code (continued) ---------------------------------------------

enum irc_read_result
{
	IRC_READ_OK,                        ///< Some data were read successfully
	IRC_READ_EOF,                       ///< The server has closed connection
	IRC_READ_AGAIN,                     ///< No more data at the moment
	IRC_READ_ERROR                      ///< General connection failure
};

static enum irc_read_result
irc_fill_read_buffer_ssl (struct app_context *ctx, struct str *buf)
{
	int n_read;
start:
	n_read = SSL_read (ctx->ssl, buf->str + buf->len,
		buf->alloc - buf->len - 1 /* null byte */);

	const char *error_info = NULL;
	switch (xssl_get_error (ctx->ssl, n_read, &error_info))
	{
	case SSL_ERROR_NONE:
		buf->str[buf->len += n_read] = '\0';
		return IRC_READ_OK;
	case SSL_ERROR_ZERO_RETURN:
		return IRC_READ_EOF;
	case SSL_ERROR_WANT_READ:
		return IRC_READ_AGAIN;
	case SSL_ERROR_WANT_WRITE:
	{
		// Let it finish the handshake as we don't poll for writability;
		// any errors are to be collected by SSL_read() in the next iteration
		struct pollfd pfd = { .fd = ctx->irc_fd, .events = POLLOUT };
		soft_assert (poll (&pfd, 1, 0) > 0);
		goto start;
	}
	case XSSL_ERROR_TRY_AGAIN:
		goto start;
	default:
		print_debug ("%s: %s: %s", __func__, "SSL_read", error_info);
		return IRC_READ_ERROR;
	}
}

static enum irc_read_result
irc_fill_read_buffer (struct app_context *ctx, struct str *buf)
{
	ssize_t n_read;
start:
	n_read = recv (ctx->irc_fd, buf->str + buf->len,
		buf->alloc - buf->len - 1 /* null byte */, 0);

	if (n_read > 0)
	{
		buf->str[buf->len += n_read] = '\0';
		return IRC_READ_OK;
	}
	if (n_read == 0)
		return IRC_READ_EOF;

	if (errno == EAGAIN)
		return IRC_READ_AGAIN;
	if (errno == EINTR)
		goto start;

	print_debug ("%s: %s: %s", __func__, "recv", strerror (errno));
	return IRC_READ_ERROR;
}

static bool irc_connect (struct app_context *, struct error **);
static void irc_queue_reconnect (struct app_context *);

static void
irc_cancel_timers (struct app_context *ctx)
{
	poller_timer_reset (&ctx->timeout_tmr);
	poller_timer_reset (&ctx->ping_tmr);
	poller_timer_reset (&ctx->reconnect_tmr);
}

static void
on_irc_reconnect_timeout (void *user_data)
{
	struct app_context *ctx = user_data;

	struct error *e = NULL;
	if (irc_connect (ctx, &e))
		return;

	buffer_send_error (ctx, ctx->server_buffer, "%s", e->message);
	error_free (e);
	irc_queue_reconnect (ctx);
}

static void
irc_queue_reconnect (struct app_context *ctx)
{
	// TODO: exponentional backoff
	hard_assert (ctx->irc_fd == -1);
	buffer_send_status (ctx, ctx->server_buffer,
		"Trying to reconnect in %ld seconds...", ctx->reconnect_delay);
	poller_timer_set (&ctx->reconnect_tmr, ctx->reconnect_delay * 1000);
}

static void
on_irc_disconnected (struct app_context *ctx)
{
	// Get rid of the dead socket and related things
	if (ctx->ssl)
	{
		SSL_free (ctx->ssl);
		ctx->ssl = NULL;
		SSL_CTX_free (ctx->ssl_ctx);
		ctx->ssl_ctx = NULL;
	}

	xclose (ctx->irc_fd);
	ctx->irc_fd = -1;
	ctx->irc_ready = false;

	str_map_set (&ctx->irc_users, ctx->irc_user->nickname, NULL);
	user_unref (ctx->irc_user);
	ctx->irc_user = NULL;

	free (ctx->irc_user_mode);
	ctx->irc_user_mode = NULL;
	free (ctx->irc_user_host);
	ctx->irc_user_host = NULL;

	ctx->irc_event.closed = true;
	poller_fd_reset (&ctx->irc_event);

	// All of our timers have lost their meaning now
	irc_cancel_timers (ctx);

	if (ctx->quitting)
		try_finish_quit (ctx);
	else if (!ctx->reconnect)
		// XXX: not sure if we want this in a client
		initiate_quit (ctx);
	else
		irc_queue_reconnect (ctx);
}

static void
on_irc_ping_timeout (void *user_data)
{
	struct app_context *ctx = user_data;
	buffer_send_error (ctx, ctx->server_buffer, "Connection timeout");
	on_irc_disconnected (ctx);
}

static void
on_irc_timeout (void *user_data)
{
	// Provoke a response from the server
	struct app_context *ctx = user_data;
	irc_send (ctx, "PING :%s",
		(char *) str_map_find (&ctx->config, "nickname"));
}

static void
irc_reset_connection_timeouts (struct app_context *ctx)
{
	irc_cancel_timers (ctx);
	poller_timer_set (&ctx->timeout_tmr, 3 * 60 * 1000);
	poller_timer_set (&ctx->ping_tmr, (3 * 60 + 30) * 1000);
}

static void
on_irc_readable (const struct pollfd *fd, struct app_context *ctx)
{
	if (fd->revents & ~(POLLIN | POLLHUP | POLLERR))
		print_debug ("fd %d: unexpected revents: %d", fd->fd, fd->revents);

	(void) set_blocking (ctx->irc_fd, false);

	struct str *buf = &ctx->read_buffer;
	enum irc_read_result (*fill_buffer)(struct app_context *, struct str *)
		= ctx->ssl
		? irc_fill_read_buffer_ssl
		: irc_fill_read_buffer;
	bool disconnected = false;
	while (true)
	{
		str_ensure_space (buf, 512);
		switch (fill_buffer (ctx, buf))
		{
		case IRC_READ_AGAIN:
			goto end;
		case IRC_READ_ERROR:
			buffer_send_error (ctx, ctx->server_buffer,
				"Reading from the IRC server failed");
			disconnected = true;
			goto end;
		case IRC_READ_EOF:
			buffer_send_error (ctx, ctx->server_buffer,
				"The IRC server closed the connection");
			disconnected = true;
			goto end;
		case IRC_READ_OK:
			break;
		}

		if (buf->len >= (1 << 20))
		{
			buffer_send_error (ctx, ctx->server_buffer,
				"The IRC server seems to spew out data frantically");
			irc_shutdown (ctx);
			goto end;
		}
	}
end:
	(void) set_blocking (ctx->irc_fd, true);
	irc_process_buffer (buf, irc_process_message, ctx);

	if (disconnected)
		on_irc_disconnected (ctx);
	else
		irc_reset_connection_timeouts (ctx);
}

static bool
irc_connect (struct app_context *ctx, struct error **e)
{
	const char *irc_host = str_map_find (&ctx->config, "irc_host");
	const char *irc_port = str_map_find (&ctx->config, "irc_port");

	const char *socks_host = str_map_find (&ctx->config, "socks_host");
	const char *socks_port = str_map_find (&ctx->config, "socks_port");
	const char *socks_username = str_map_find (&ctx->config, "socks_username");
	const char *socks_password = str_map_find (&ctx->config, "socks_password");

	const char *nickname = str_map_find (&ctx->config, "nickname");
	const char *username = str_map_find (&ctx->config, "username");
	const char *realname = str_map_find (&ctx->config, "realname");

	// We have a default value for these
	hard_assert (irc_port && socks_port);

	// These are filled automatically if needed
	hard_assert (nickname && username && realname);

	// TODO: again, get rid of `struct error' in here.  The question is: how
	//   do we tell our caller that he should not try to reconnect?
	bool use_ssl;
	if (!irc_get_boolean_from_config (ctx, "ssl", &use_ssl, e))
		return false;

	if (socks_host)
	{
		char *address = format_host_port_pair (irc_host, irc_port);
		char *socks_address = format_host_port_pair (socks_host, socks_port);
		buffer_send_status (ctx, ctx->server_buffer,
			"Connecting to %s via %s...", address, socks_address);
		free (socks_address);
		free (address);

		struct error *error = NULL;
		int fd = socks_connect (socks_host, socks_port, irc_host, irc_port,
			socks_username, socks_password, &error);
		if (fd == -1)
		{
			error_set (e, "%s: %s", "SOCKS connection failed", error->message);
			error_free (error);
			return false;
		}
		ctx->irc_fd = fd;
	}
	else if (!irc_establish_connection (ctx, irc_host, irc_port, e))
		return false;

	if (use_ssl && !irc_initialize_ssl (ctx, e))
	{
		xclose (ctx->irc_fd);
		ctx->irc_fd = -1;
		return false;
	}
	buffer_send_status (ctx, ctx->server_buffer, "Connection established");

	poller_fd_init (&ctx->irc_event, &ctx->poller, ctx->irc_fd);
	ctx->irc_event.dispatcher = (poller_fd_fn) on_irc_readable;
	ctx->irc_event.user_data = ctx;

	poller_fd_set (&ctx->irc_event, POLLIN);
	irc_reset_connection_timeouts (ctx);

	irc_send (ctx, "NICK %s", nickname);
	irc_send (ctx, "USER %s 8 * :%s", username, realname);

	// XXX: maybe we should wait for the first message from the server
	ctx->irc_user = irc_make_user (ctx, xstrdup (nickname));
	ctx->irc_user_mode = xstrdup ("");
	ctx->irc_user_host = NULL;
	return true;
}

// --- I/O event handlers ------------------------------------------------------

static void
on_signal_pipe_readable (const struct pollfd *fd, struct app_context *ctx)
{
	char dummy;
	(void) read (fd->fd, &dummy, 1);

	if (g_termination_requested && !ctx->quitting)
	{
		// There may be a timer set to reconnect to the server
		irc_cancel_timers (ctx);

		if (ctx->irc_fd != -1)
			irc_send (ctx, "QUIT :Terminated by signal");
		initiate_quit (ctx);
	}

	if (g_winch_received)
	{
		// This fucks up big time on terminals with automatic wrapping such as
		// rxvt-unicode or newer VTE when the current line overflows, however we
		// can't do much about that
		rl_resize_terminal ();
		rl_get_screen_size (&ctx->lines, &ctx->columns);
	}
}

static void
on_tty_readable (const struct pollfd *fd, struct app_context *ctx)
{
	(void) ctx;

	if (fd->revents & ~(POLLIN | POLLHUP | POLLERR))
		print_debug ("fd %d: unexpected revents: %d", fd->fd, fd->revents);

	rl_callback_read_char ();
}

static void
on_readline_input (char *line)
{
	if (line)
	{
		if (*line)
			add_history (line);

		process_input (g_ctx, line);
		free (line);
	}
	else
	{
		app_readline_erase_to_bol (g_ctx->readline_prompt);
		rl_ding ();
	}

	// initiate_quit() disables readline; we just wait then
	if (!g_ctx->quitting)
		g_ctx->readline_prompt_shown = true;
}

// --- Configuration loading ---------------------------------------------------

static bool
read_hexa_escape (const char **cursor, struct str *output)
{
	int i;
	char c, code = 0;

	for (i = 0; i < 2; i++)
	{
		c = tolower (*(*cursor));
		if (c >= '0' && c <= '9')
			code = (code << 4) | (c - '0');
		else if (c >= 'a' && c <= 'f')
			code = (code << 4) | (c - 'a' + 10);
		else
			break;

		(*cursor)++;
	}

	if (!i)
		return false;

	str_append_c (output, code);
	return true;
}

static bool
read_octal_escape (const char **cursor, struct str *output)
{
	int i;
	char c, code = 0;

	for (i = 0; i < 3; i++)
	{
		c = *(*cursor);
		if (c < '0' || c > '7')
			break;

		code = (code << 3) | (c - '0');
		(*cursor)++;
	}

	if (!i)
		return false;

	str_append_c (output, code);
	return true;
}

static bool
read_string_escape_sequence (const char **cursor,
	struct str *output, struct error **e)
{
	int c;
	switch ((c = *(*cursor)++))
	{
	case '?':  str_append_c (output, '?');  break;
	case '"':  str_append_c (output, '"');  break;
	case '\\': str_append_c (output, '\\'); break;
	case 'a':  str_append_c (output, '\a'); break;
	case 'b':  str_append_c (output, '\b'); break;
	case 'f':  str_append_c (output, '\f'); break;
	case 'n':  str_append_c (output, '\n'); break;
	case 'r':  str_append_c (output, '\r'); break;
	case 't':  str_append_c (output, '\t'); break;
	case 'v':  str_append_c (output, '\v'); break;

	case 'e':
	case 'E':
		str_append_c (output, '\x1b');
		break;

	case 'x':
	case 'X':
		if (!read_hexa_escape (cursor, output))
			FAIL ("invalid hexadecimal escape");
		break;

	case '\0':
		FAIL ("premature end of escape sequence");

	default:
		(*cursor)--;
		if (!read_octal_escape (cursor, output))
			FAIL ("unknown escape sequence");
	}
	return true;
}

static bool
unescape_string (const char *s, struct str *output, struct error **e)
{
	int c;
	while ((c = *s++))
	{
		if (c != '\\')
			str_append_c (output, c);
		else if (!read_string_escape_sequence (&s, output, e))
			return false;
	}
	return true;
}

static bool
autofill_user_info (struct app_context *ctx, struct error **e)
{
	const char *nickname = str_map_find (&ctx->config, "nickname");
	const char *username = str_map_find (&ctx->config, "username");
	const char *realname = str_map_find (&ctx->config, "realname");

	if (nickname && username && realname)
		return true;

	// Read POSIX user info and fill the configuration if needed
	struct passwd *pwd = getpwuid (geteuid ());
	if (!pwd)
		FAIL ("cannot retrieve user information: %s", strerror (errno));

	if (!nickname)
		str_map_set (&ctx->config, "nickname", xstrdup (pwd->pw_name));
	if (!username)
		str_map_set (&ctx->config, "username", xstrdup (pwd->pw_name));

	// Not all systems have the GECOS field but the vast majority does
	if (!realname)
	{
		char *gecos = pwd->pw_gecos;

		// The first comma, if any, ends the user's real name
		char *comma = strchr (gecos, ',');
		if (comma)
			*comma = '\0';

		str_map_set (&ctx->config, "realname", xstrdup (gecos));
	}

	return true;
}

static bool
unescape_config (struct str_map *input, struct str_map *output, struct error **e)
{
	struct error *error = NULL;
	struct str_map_iter iter;
	str_map_iter_init (&iter, input);
	while (str_map_iter_next (&iter))
	{
		struct str value;
		str_init (&value);
		if (!unescape_string (iter.link->data, &value, &error))
		{
			error_set (e, "error reading configuration: %s: %s",
				iter.link->key, error->message);
			error_free (error);
			return false;
		}

		str_map_set (output, iter.link->key, str_steal (&value));
	}
	return true;
}

static bool
load_config (struct app_context *ctx, struct error **e)
{
	// TODO: employ a better configuration file format, so that we don't have
	//   to do this convoluted post-processing anymore.

	struct str_map map;
	str_map_init (&map);
	map.free = free;

	bool success = read_config_file (&map, e) &&
		unescape_config (&map, &ctx->config, e) &&
		autofill_user_info (ctx, e);
	str_map_free (&map);
	if (!success)
		return false;

	const char *irc_host = str_map_find (&ctx->config, "irc_host");
	if (!irc_host)
	{
		error_set (e, "no hostname specified in configuration");
		return false;
	}

	if (!irc_get_boolean_from_config (ctx,
		"reconnect", &ctx->reconnect, e)
	 || !irc_get_boolean_from_config (ctx,
		"isolate_buffers", &ctx->isolate_buffers, e))
		return false;

	const char *delay_str = str_map_find (&ctx->config, "reconnect_delay");
	hard_assert (delay_str != NULL);  // We have a default value for this
	if (!xstrtoul (&ctx->reconnect_delay, delay_str, 10))
	{
		error_set (e, "invalid configuration value for `%s'",
			"reconnect_delay");
		return false;
	}
	return true;
}

// --- Main program ------------------------------------------------------------

static void
init_poller_events (struct app_context *ctx)
{
	poller_timer_init (&ctx->timeout_tmr, &ctx->poller);
	ctx->timeout_tmr.dispatcher = on_irc_timeout;
	ctx->timeout_tmr.user_data = ctx;

	poller_timer_init (&ctx->ping_tmr, &ctx->poller);
	ctx->ping_tmr.dispatcher = on_irc_ping_timeout;
	ctx->ping_tmr.user_data = ctx;

	poller_timer_init (&ctx->reconnect_tmr, &ctx->poller);
	ctx->reconnect_tmr.dispatcher = on_irc_reconnect_timeout;
	ctx->reconnect_tmr.user_data = ctx;

	poller_fd_init (&ctx->signal_event, &ctx->poller, g_signal_pipe[0]);
	ctx->signal_event.dispatcher = (poller_fd_fn) on_signal_pipe_readable;
	ctx->signal_event.user_data = ctx;
	poller_fd_set (&ctx->signal_event, POLLIN);

	poller_fd_init (&ctx->tty_event, &ctx->poller, STDIN_FILENO);
	ctx->tty_event.dispatcher = (poller_fd_fn) on_tty_readable;
	ctx->tty_event.user_data = &ctx;
	poller_fd_set (&ctx->tty_event, POLLIN);
}

int
main (int argc, char *argv[])
{
	// We include a generated file from kike including this array we don't use;
	// let's just keep it there and silence the compiler warning instead
	(void) g_default_replies;

	static const struct opt opts[] =
	{
		{ 'd', "debug", NULL, 0, "run in debug mode" },
		{ 'h', "help", NULL, 0, "display this help and exit" },
		{ 'V', "version", NULL, 0, "output version information and exit" },
		{ 'w', "write-default-cfg", "FILENAME",
		  OPT_OPTIONAL_ARG | OPT_LONG_ONLY,
		  "write a default configuration file and exit" },
		{ 0, NULL, NULL, 0, NULL }
	};

	struct opt_handler oh;
	opt_handler_init (&oh, argc, argv, opts, NULL, "Experimental IRC client.");

	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 'V':
		printf (PROGRAM_NAME " " PROGRAM_VERSION "\n");
		exit (EXIT_SUCCESS);
	case 'w':
		call_write_default_config (optarg, g_config_table);
		exit (EXIT_SUCCESS);
	default:
		print_error ("wrong options");
		opt_handler_usage (&oh, stderr);
		exit (EXIT_FAILURE);
	}

	opt_handler_free (&oh);

	print_status (PROGRAM_NAME " " PROGRAM_VERSION " starting");

	// We only need to convert to and from the terminal encoding
	setlocale (LC_CTYPE, "");

	struct app_context ctx;
	app_context_init (&ctx);
	g_ctx = &ctx;

	SSL_library_init ();
	atexit (EVP_cleanup);
	SSL_load_error_strings ();
	atexit (ERR_free_strings);

	using_history ();
	// This can cause memory leaks, or maybe even a segfault.  Funny, eh?
	stifle_history (HISTORY_LIMIT);

	setup_signal_handlers ();

	struct error *e = NULL;
	if (!load_config (&ctx, &e))
	{
		print_error ("%s", e->message);
		error_free (e);
		exit (EXIT_FAILURE);
	}

	init_colors (&ctx);
	init_poller_events (&ctx);
	init_buffers (&ctx);
	ctx.current_buffer = ctx.global_buffer;
	refresh_prompt (&ctx);

	// TODO: connect asynchronously (first step towards multiple servers)
	if (!irc_connect (&ctx, &e))
	{
		buffer_send_error (&ctx, ctx.server_buffer, "%s", e->message);
		error_free (e);
		exit (EXIT_FAILURE);
	}

	rl_startup_hook = init_readline;
	rl_catch_sigwinch = false;
	rl_callback_handler_install (ctx.readline_prompt, on_readline_input);
	rl_get_screen_size (&ctx.lines, &ctx.columns);
	ctx.readline_prompt_shown = true;

	ctx.polling = true;
	while (ctx.polling)
		poller_run (&ctx.poller);

	app_context_free (&ctx);
	free_terminal ();
	return EXIT_SUCCESS;
}