File: libcli.c

package info (click to toggle)
libcli 1.10.7-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 464 kB
  • sloc: ansic: 3,462; makefile: 72
file content (3633 lines) | stat: -rw-r--r-- 118,912 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
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
// vim:sw=2 tw=120 et

#ifdef WIN32
#include <windows.h>
#include <winsock2.h>
#endif

#define _GNU_SOURCE
#include <errno.h>
#include <memory.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#if !defined(__APPLE__) && !defined(__FreeBSD__)
#include <malloc.h>
#endif
#include <ctype.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#ifndef WIN32
#include <regex.h>
#endif
#if defined(LIBCLI_USE_POLL) && !defined(WIN32)
#include <poll.h>
#define CLI_SOCKET_WAIT_PERROR "poll"
#else
#define CLI_SOCKET_WAIT_PERROR "select"
#endif
#include "libcli.h"

#ifdef __GNUC__
#define UNUSED(d) d __attribute__((unused))
#else
#define UNUSED(d) d
#endif

#define MATCH_REGEX 1
#define MATCH_INVERT 2

#ifdef WIN32
// Stupid windows has multiple namespaces for filedescriptors, with different read/write functions required for each ..
int read(int fd, void *buf, unsigned int count) {
  return recv(fd, buf, count, 0);
}

int write(int fd, const void *buf, unsigned int count) {
  return send(fd, buf, count, 0);
}

int vasprintf(char **strp, const char *fmt, va_list args) {
  int size;
  va_list argCopy;

  // Do initial vsnprintf on a copy of the va_list
  va_copy(argCopy, args);
  size = vsnprintf(NULL, 0, fmt, argCopy);
  va_end(argCopy);
  if ((*strp = malloc(size + 1)) == NULL) {
    return -1;
  }

  size = vsnprintf(*strp, size + 1, fmt, args);
  return size;
}

int asprintf(char **strp, const char *fmt, ...) {
  va_list args;
  int size;

  va_start(args, fmt);
  size = vasprintf(strp, fmt, args);

  va_end(args);
  return size;
}

int fprintf(FILE *stream, const char *fmt, ...) {
  va_list args;
  int size;
  char *buf;

  va_start(args, fmt);
  size = vasprintf(&buf, fmt, args);
  if (size < 0) {
    goto out;
  }
  size = write(stream->_file, buf, size);
  free(buf);

out:
  va_end(args);
  return size;
}

// Dummy definitions to allow compilation on Windows
int regex_dummy() {
  return 0;
};
#define regfree(...) regex_dummy()
#define regexec(...) regex_dummy()
#define regcomp(...) regex_dummy()
#define regex_t int
#define REG_NOSUB 0
#define REG_EXTENDED 0
#define REG_ICASE 0
#endif

enum cli_states {
  STATE_LOGIN,
  STATE_PASSWORD,
  STATE_NORMAL,
  STATE_ENABLE_PASSWORD,
  STATE_ENABLE,
};

struct unp {
  char *username;
  char *password;
  struct unp *next;
};

struct cli_filter_cmds {
  const char *cmd;
  const char *help;
};

// Free and zero (to avoid double-free)
#define free_z(p) \
  do {            \
    if (p) {      \
      free(p);    \
      (p) = 0;    \
    }             \
  } while (0)

// Forward defines of *INTERNAL* library function as static here
static int cli_search_flags_validator(struct cli_def *cli, const char *word, const char *value);
static int cli_match_filter_init(struct cli_def *cli, int argc, char **argv, struct cli_filter *filt);
static int cli_range_filter_init(struct cli_def *cli, int argc, char **argv, struct cli_filter *filt);
static int cli_count_filter_init(struct cli_def *cli, int argc, char **argv, struct cli_filter *filt);
static int cli_match_filter(struct cli_def *cli, const char *string, void *data);
static int cli_range_filter(struct cli_def *cli, const char *string, void *data);
static int cli_count_filter(struct cli_def *cli, const char *string, void *data);
static void cli_int_parse_optargs(struct cli_def *cli, struct cli_pipeline_stage *stage, struct cli_command *cmd,
                                  char lastchar, struct cli_comphelp *comphelp);
static int cli_int_enter_buildmode(struct cli_def *cli, struct cli_pipeline_stage *stage, char *mode_text);
static char *cli_int_buildmode_extend_cmdline(char *, char *word);
static void cli_int_free_buildmode(struct cli_def *cli);
static void cli_free_command(struct cli_def *cli, struct cli_command *cmd);
static int cli_int_unregister_command_core(struct cli_def *cli, const char *command, int command_type);
static int cli_int_unregister_buildmode_command(struct cli_def *cli, const char *command) __attribute__((unused));
static struct cli_command *cli_int_register_buildmode_command(struct cli_def *cli, struct cli_command *parent,
                                                              const char *command,
                                                              int (*callback)(struct cli_def *cli, const char *,
                                                                              char **, int),
                                                              int flags, int privilege, int mode, const char *help);
static void cli_int_buildmode_reset_unset_help(struct cli_def *cli);
static int cli_int_buildmode_cmd_cback(struct cli_def *cli, const char *command, char *argv[], int argc);
static int cli_int_buildmode_flag_cback(struct cli_def *cli, const char *command, char *argv[], int argc);
static int cli_int_buildmode_flag_multiple_cback(struct cli_def *cli, const char *command, char *argv[], int argc);
static int cli_int_buildmode_cancel_cback(struct cli_def *cli, const char *command, char *argv[], int argc);
static int cli_int_buildmode_execute_cback(struct cli_def *cli, const char *command, char *argv[], int argc);
static int cli_int_buildmode_show_cback(struct cli_def *cli, const char *command, char *argv[], int argc);
static int cli_int_buildmode_unset_cback(struct cli_def *cli, const char *command, char *argv[], int argc);
static int cli_int_buildmode_unset_completor(struct cli_def *cli, const char *name, const char *word,
                                             struct cli_comphelp *comphelp);
static int cli_int_buildmode_unset_validator(struct cli_def *cli, const char *name, const char *value);
static int cli_int_execute_buildmode(struct cli_def *cli);
static void cli_int_free_found_optargs(struct cli_optarg_pair **optarg_pair);
static void cli_int_unset_optarg_value(struct cli_def *cli, const char *name);
static struct cli_pipeline *cli_int_generate_pipeline(struct cli_def *cli, const char *command);
static int cli_int_validate_pipeline(struct cli_def *cli, struct cli_pipeline *pipeline);
static int cli_int_execute_pipeline(struct cli_def *cli, struct cli_pipeline *pipeline);
inline void cli_int_show_pipeline(struct cli_def *cli, struct cli_pipeline *pipeline);
static void cli_int_free_pipeline(struct cli_pipeline *pipeline);
static struct cli_command *cli_register_command_core(struct cli_def *cli, struct cli_command *parent,
                                                     struct cli_command *c);
static void cli_int_wrap_help_line(char *nameptr, char *helpptr, struct cli_comphelp *comphelp);
static int cli_socket_wait(int sockfd, struct timeval *tm);

static char DELIM_OPT_START[] = "[";
static char DELIM_OPT_END[] = "]";
static char DELIM_ARG_START[] = "<";
static char DELIM_ARG_END[] = ">";
static char DELIM_NONE[] = "";

static ssize_t _write(int fd, const void *buf, size_t count) {
  size_t written = 0;
  ssize_t thisTime = 0;
  while (count != written) {
    thisTime = write(fd, (char *)buf + written, count - written);
    if (thisTime == -1) {
      if (errno == EINTR)
        continue;
      else
        return -1;
    }
    written += thisTime;
  }
  return written;
}

char *cli_int_command_name(struct cli_def *cli, struct cli_command *command) {
  char *name;
  char *o;

  if (command->full_command_name) {
    free(command->full_command_name);
    command->full_command_name = NULL;
  }

  if (!(name = calloc(1, 1))) return NULL;

  while (command) {
    o = name;
    if (asprintf(&name, "%s%s%s", command->command, *o ? " " : "", o) == -1) {
      fprintf(stderr, "Couldn't allocate memory for command_name: %s", strerror(errno));
      free(o);
      return NULL;
    }
    command = command->parent;
    free(o);
  }
  return name;
}

char *cli_command_name(struct cli_def *cli, struct cli_command *command) {
  return command->full_command_name;
}

void cli_set_auth_callback(struct cli_def *cli, int (*auth_callback)(const char *, const char *)) {
  cli->auth_callback = auth_callback;
}

void cli_set_enable_callback(struct cli_def *cli, int (*enable_callback)(const char *)) {
  cli->enable_callback = enable_callback;
}

void cli_allow_user(struct cli_def *cli, const char *username, const char *password) {
  struct unp *u, *n;
  if (!(n = malloc(sizeof(struct unp)))) {
    fprintf(stderr, "Couldn't allocate memory for user: %s", strerror(errno));
    return;
  }
  if (!(n->username = strdup(username))) {
    fprintf(stderr, "Couldn't allocate memory for username: %s", strerror(errno));
    free(n);
    return;
  }
  if (!(n->password = strdup(password))) {
    fprintf(stderr, "Couldn't allocate memory for password: %s", strerror(errno));
    free(n->username);
    free(n);
    return;
  }
  n->next = NULL;

  if (!cli->users) {
    cli->users = n;
  } else {
    for (u = cli->users; u && u->next; u = u->next)
      ;
    if (u) u->next = n;
  }
}

void cli_allow_enable(struct cli_def *cli, const char *password) {
  free_z(cli->enable_password);
  if (!(cli->enable_password = strdup(password))) {
    fprintf(stderr, "Couldn't allocate memory for enable password: %s", strerror(errno));
  }
}

void cli_deny_user(struct cli_def *cli, const char *username) {
  struct unp *u, *p = NULL;
  if (!cli->users) return;
  for (u = cli->users; u; u = u->next) {
    if (strcmp(username, u->username) == 0) {
      if (p)
        p->next = u->next;
      else
        cli->users = u->next;
      free(u->username);
      free(u->password);
      free(u);
      break;
    }
    p = u;
  }
}

void cli_set_banner(struct cli_def *cli, const char *banner) {
  free_z(cli->banner);
  if (banner && *banner) cli->banner = strdup(banner);
}

void cli_set_hostname(struct cli_def *cli, const char *hostname) {
  free_z(cli->hostname);
  if (hostname && *hostname) cli->hostname = strdup(hostname);
}

void cli_set_promptchar(struct cli_def *cli, const char *promptchar) {
  free_z(cli->promptchar);
  cli->promptchar = strdup(promptchar);
}

static int cli_build_shortest(struct cli_def *cli, struct cli_command *commands) {
  struct cli_command *c, *p;
  char *cp, *pp;
  unsigned len;

  for (c = commands; c; c = c->next) {
    c->unique_len = strlen(c->command);
    if ((c->mode != MODE_ANY && c->mode != cli->mode) || c->privilege > cli->privilege) continue;

    c->unique_len = 1;
    for (p = commands; p; p = p->next) {
      if (c == p) continue;
      if (c->command_type != p->command_type) continue;
      if ((p->mode != MODE_ANY && p->mode != cli->mode) || p->privilege > cli->privilege) continue;

      cp = c->command;
      pp = p->command;
      len = 1;

      while (*cp && *pp && *cp++ == *pp++) len++;

      if (len > c->unique_len) c->unique_len = len;
    }

    if (c->children) cli_build_shortest(cli, c->children);
  }

  return CLI_OK;
}

int cli_set_privilege(struct cli_def *cli, int priv) {
  int old = cli->privilege;
  cli->privilege = priv;

  if (priv != old) {
    cli_set_promptchar(cli, priv == PRIVILEGE_PRIVILEGED ? "# " : "> ");
    cli_build_shortest(cli, cli->commands);
  }

  return old;
}

void cli_set_modestring(struct cli_def *cli, const char *modestring) {
  free_z(cli->modestring);
  if (modestring) cli->modestring = strdup(modestring);
}

int cli_set_configmode(struct cli_def *cli, int mode, const char *config_desc) {
  int old = cli->mode;
  cli->mode = mode;

  if (mode != old) {
    if (!cli->mode) {
      // Not config mode
      cli_set_modestring(cli, NULL);
    } else if (config_desc && *config_desc) {
      char string[64];
      snprintf(string, sizeof(string), "(config-%s)", config_desc);
      cli_set_modestring(cli, string);
    } else {
      cli_set_modestring(cli, "(config)");
    }

    cli_build_shortest(cli, cli->commands);
  }

  return old;
}

struct cli_command *cli_register_command_core(struct cli_def *cli, struct cli_command *parent, struct cli_command *c) {
  struct cli_command *p = NULL;

  if (!c) return NULL;

  c->parent = parent;

  /* Go build the 'full command name' now that told it who its parent is.
   * If this fails, clean it up and return a NULL w/o proceeding.
   */
  if (!(c->full_command_name = cli_int_command_name(cli, c))) {
    cli_free_command(cli, c);
    return NULL;
  }
  /*
   * Figure out we have a chain, or would be the first element on it.
   * If we'd be the first element, assign as such.
   * Otherwise find the lead element so we can trace it below.
   */

  if (parent) {
    if (!parent->children) {
      parent->children = c;
    } else {
      p = parent->children;
    }
  } else {
    if (!cli->commands) {
      cli->commands = c;
    } else {
      p = cli->commands;
    }
  }

  /*
   * If we have a chain (p is not null), run down to the last element and place this command at the end
   */
  for (; p && p->next; p = p->next)
    ;

  if (p) {
    p->next = c;
    c->previous = p;
  }
  return c;
}

struct cli_command *cli_register_command(struct cli_def *cli, struct cli_command *parent, const char *command,
                                         int (*callback)(struct cli_def *cli, const char *, char **, int),
                                         int privilege, int mode, const char *help) {
  struct cli_command *c;

  if (!command) return NULL;
  if (!(c = calloc(1, sizeof(struct cli_command)))) return NULL;
  c->command_type = CLI_REGULAR_COMMAND;
  c->callback = callback;
  c->next = NULL;
  if (!(c->command = strdup(command))) {
    free(c);
    return NULL;
  }

  c->privilege = privilege;
  c->mode = mode;
  if (help && !(c->help = strdup(help))) {
    free(c->command);
    free(c);
    return NULL;
  }

  return cli_register_command_core(cli, parent, c);
}

static void cli_free_command(struct cli_def *cli, struct cli_command *cmd) {
  struct cli_command *c, *p;

  for (c = cmd->children; c;) {
    p = c->next;
    cli_free_command(cli, c);
    c = p;
  }

  free(cmd->command);
  if (cmd->help) free(cmd->help);
  if (cmd->optargs) cli_unregister_all_optarg(cmd);
  if (cmd->full_command_name) free(cmd->full_command_name);
  /*
   * Ok, update the pointers of anyone who pointed to us.
   * We have 3 pointers to worry about - parent, previous, and next.
   * We don't have to worry about children since they've been cleared above.
   * If both cli->command points to us we need to update cli->command to point to whatever command is 'next'.
   * Otherwise ensure that any item before/behind us points around us.
   *
   * Important - there is no provision for deleting a discrete subcommand.
   * For example, suppose we define foo, then bar with foo as the parent, then baz with bar as the parent.  We cannot
   * delete 'bar' and have a new chain of foo -> baz.
   * The above freeing of children prevents this in the first place.
   */

  if (cmd == cli->commands) {
    cli->commands = cmd->next;
    if (cmd->next) {
      cmd->next->parent = NULL;
      cmd->next->previous = NULL;
    }
  } else {
    if (cmd->previous) {
      cmd->previous->next = cmd->next;
    }
    if (cmd->next) {
      cmd->next->previous = cmd->previous;
    }
  }
  free(cmd);
}

int cli_int_unregister_command_core(struct cli_def *cli, const char *command, int command_type) {
  struct cli_command *c, *p = NULL;

  if (!command) return -1;
  if (!cli->commands) return CLI_OK;

  for (c = cli->commands; c;) {
    p = c->next;
    if (strcmp(c->command, command) == 0 && c->command_type == command_type) {
      cli_free_command(cli, c);
      return CLI_OK;
    }
    c = p;
  }

  return CLI_OK;
}

int cli_unregister_command(struct cli_def *cli, const char *command) {
  return cli_int_unregister_command_core(cli, command, CLI_REGULAR_COMMAND);
}

int cli_show_help(struct cli_def *cli, struct cli_command *c) {
  struct cli_command *p;

  for (p = c; p; p = p->next) {
    if (p->command && p->callback && cli->privilege >= p->privilege && (p->mode == cli->mode || p->mode == MODE_ANY)) {
      cli_error(cli, "  %-20s %s", cli_command_name(cli, p), (p->help != NULL ? p->help : ""));
    }

    if (p->children) cli_show_help(cli, p->children);
  }

  return CLI_OK;
}

int cli_enable(struct cli_def *cli, UNUSED(const char *command), UNUSED(char *argv[]), UNUSED(int argc)) {
  if (cli->privilege == PRIVILEGE_PRIVILEGED) return CLI_OK;

  if (!cli->enable_password && !cli->enable_callback) {
    // No password required, set privilege immediately.
    cli_set_privilege(cli, PRIVILEGE_PRIVILEGED);
    cli_set_configmode(cli, MODE_EXEC, NULL);
  } else {
    // Require password entry
    cli->state = STATE_ENABLE_PASSWORD;
  }

  return CLI_OK;
}

int cli_disable(struct cli_def *cli, UNUSED(const char *command), UNUSED(char *argv[]), UNUSED(int argc)) {
  cli_set_privilege(cli, PRIVILEGE_UNPRIVILEGED);
  cli_set_configmode(cli, MODE_EXEC, NULL);
  return CLI_OK;
}

int cli_help(struct cli_def *cli, UNUSED(const char *command), UNUSED(char *argv[]), UNUSED(int argc)) {
  cli_error(cli, "\nCommands available:");
  cli_show_help(cli, cli->commands);
  return CLI_OK;
}

int cli_history(struct cli_def *cli, UNUSED(const char *command), UNUSED(char *argv[]), UNUSED(int argc)) {
  int i;

  cli_error(cli, "\nCommand history:");
  for (i = 0; i < MAX_HISTORY; i++) {
    if (cli->history[i]) cli_error(cli, "%3d. %s", i, cli->history[i]);
  }

  return CLI_OK;
}

int cli_quit(struct cli_def *cli, UNUSED(const char *command), UNUSED(char *argv[]), UNUSED(int argc)) {
  cli_set_privilege(cli, PRIVILEGE_UNPRIVILEGED);
  cli_set_configmode(cli, MODE_EXEC, NULL);
  return CLI_QUIT;
}

int cli_exit(struct cli_def *cli, const char *command, char *argv[], int argc) {
  if (cli->mode == MODE_EXEC) return cli_quit(cli, command, argv, argc);

  if (cli->mode > MODE_CONFIG)
    cli_set_configmode(cli, MODE_CONFIG, NULL);
  else
    cli_set_configmode(cli, MODE_EXEC, NULL);

  cli->service = NULL;
  return CLI_OK;
}

int cli_int_idle_timeout(struct cli_def *cli) {
  cli_print(cli, "Idle timeout");
  return CLI_QUIT;
}

int cli_int_configure_terminal(struct cli_def *cli, UNUSED(const char *command), UNUSED(char *argv[]),
                               UNUSED(int argc)) {
  cli_set_configmode(cli, MODE_CONFIG, NULL);
  return CLI_OK;
}

struct cli_def *cli_init() {
  struct cli_def *cli;
  struct cli_command *c;

  if (!(cli = calloc(1, sizeof(struct cli_def)))) return 0;

  cli->buf_size = 1024;
  if (!(cli->buffer = calloc(cli->buf_size, 1))) {
    cli_done(cli);
    return 0;
  }
  cli->telnet_protocol = 1;

  cli_register_command(cli, 0, "help", cli_help, PRIVILEGE_UNPRIVILEGED, MODE_ANY, "Show available commands");
  cli_register_command(cli, 0, "quit", cli_quit, PRIVILEGE_UNPRIVILEGED, MODE_ANY, "Disconnect");
  cli_register_command(cli, 0, "logout", cli_quit, PRIVILEGE_UNPRIVILEGED, MODE_ANY, "Disconnect");
  cli_register_command(cli, 0, "exit", cli_exit, PRIVILEGE_UNPRIVILEGED, MODE_ANY, "Exit from current mode");
  cli_register_command(cli, 0, "history", cli_history, PRIVILEGE_UNPRIVILEGED, MODE_ANY,
                       "Show a list of previously run commands");
  cli_register_command(cli, 0, "enable", cli_enable, PRIVILEGE_UNPRIVILEGED, MODE_EXEC, "Turn on privileged commands");
  cli_register_command(cli, 0, "disable", cli_disable, PRIVILEGE_PRIVILEGED, MODE_EXEC, "Turn off privileged commands");

  c = cli_register_command(cli, 0, "configure", 0, PRIVILEGE_PRIVILEGED, MODE_EXEC, "Enter configuration mode");
  if (!c) {
    cli_done(cli);
    return 0;
  }
  cli_register_command(cli, c, "terminal", cli_int_configure_terminal, PRIVILEGE_PRIVILEGED, MODE_EXEC,
                       "Conlfigure from the terminal");

  // And now the built in filters
  c = cli_register_filter(cli, "begin", cli_range_filter_init, cli_range_filter, PRIVILEGE_UNPRIVILEGED, MODE_ANY,
                          "Begin with lines that match");
  if (!c) {
    cli_done(cli);
    return 0;
  }
  cli_register_optarg(c, "range_start", CLI_CMD_ARGUMENT | CLI_CMD_REMAINDER_OF_LINE, PRIVILEGE_UNPRIVILEGED, MODE_ANY,
                      "Begin showing lines that match", NULL, NULL, NULL);

  c = cli_register_filter(cli, "between", cli_range_filter_init, cli_range_filter, PRIVILEGE_UNPRIVILEGED, MODE_ANY,
                          "Between lines that match");
  if (!c) {
    cli_done(cli);
    return 0;
  }
  cli_register_optarg(c, "range_start", CLI_CMD_ARGUMENT, PRIVILEGE_UNPRIVILEGED, MODE_ANY,
                      "Begin showing lines that match", NULL, NULL, NULL);
  cli_register_optarg(c, "range_end", CLI_CMD_ARGUMENT | CLI_CMD_REMAINDER_OF_LINE, PRIVILEGE_UNPRIVILEGED, MODE_ANY,
                      "Stop showing lines that match", NULL, NULL, NULL);

  cli_register_filter(cli, "count", cli_count_filter_init, cli_count_filter, PRIVILEGE_UNPRIVILEGED, MODE_ANY,
                      "Count of lines");

  c = cli_register_filter(cli, "exclude", cli_match_filter_init, cli_match_filter, PRIVILEGE_UNPRIVILEGED, MODE_ANY,
                          "Exclude lines that match");
  if (!c) {
    cli_done(cli);
    return 0;
  }
  cli_register_optarg(c, "search_pattern", CLI_CMD_ARGUMENT | CLI_CMD_REMAINDER_OF_LINE, PRIVILEGE_UNPRIVILEGED,
                      MODE_ANY, "Search pattern", NULL, NULL, NULL);

  c = cli_register_filter(cli, "include", cli_match_filter_init, cli_match_filter, PRIVILEGE_UNPRIVILEGED, MODE_ANY,
                          "Include lines that match");
  if (!c) {
    cli_done(cli);
    return 0;
  }
  cli_register_optarg(c, "search_pattern", CLI_CMD_ARGUMENT | CLI_CMD_REMAINDER_OF_LINE, PRIVILEGE_UNPRIVILEGED,
                      MODE_ANY, "Search pattern", NULL, NULL, NULL);

  c = cli_register_filter(cli, "grep", cli_match_filter_init, cli_match_filter, PRIVILEGE_UNPRIVILEGED, MODE_ANY,
                          "Include lines that match regex (options: -v, -i, -e)");
  if (!c) {
    cli_done(cli);
    return 0;
  }
  cli_register_optarg(c, "search_flags", CLI_CMD_HYPHENATED_OPTION, PRIVILEGE_UNPRIVILEGED, MODE_ANY,
                      "Search flags (-[ivx]", NULL, cli_search_flags_validator, NULL);
  cli_register_optarg(c, "search_pattern", CLI_CMD_ARGUMENT | CLI_CMD_REMAINDER_OF_LINE, PRIVILEGE_UNPRIVILEGED,
                      MODE_ANY, "Search pattern", NULL, NULL, NULL);

  c = cli_register_filter(cli, "egrep", cli_match_filter_init, cli_match_filter, PRIVILEGE_UNPRIVILEGED, MODE_ANY,
                          "Include lines that match extended regex");
  if (!c) {
    cli_done(cli);
    return 0;
  }
  cli_register_optarg(c, "search_flags", CLI_CMD_HYPHENATED_OPTION, PRIVILEGE_UNPRIVILEGED, MODE_ANY,
                      "Search flags (-[ivx]", NULL, cli_search_flags_validator, NULL);
  cli_register_optarg(c, "search_pattern", CLI_CMD_ARGUMENT | CLI_CMD_REMAINDER_OF_LINE, PRIVILEGE_UNPRIVILEGED,
                      MODE_ANY, "Search pattern", NULL, NULL, NULL);

  cli->privilege = cli->mode = -1;
  cli_set_privilege(cli, PRIVILEGE_UNPRIVILEGED);
  cli_set_configmode(cli, MODE_EXEC, 0);

  // Default to 1 second timeout intervals
  cli->timeout_tm.tv_sec = 1;
  cli->timeout_tm.tv_usec = 0;

  // Set default idle timeout callback, but no timeout
  cli_set_idle_timeout_callback(cli, 0, cli_int_idle_timeout);
  return cli;
}

void cli_unregister_tree(struct cli_def *cli, struct cli_command *command, int command_type) {
  struct cli_command *c, *p = NULL;

  if (!command) command = cli->commands;

  for (c = command; c;) {
    p = c->next;
    if (c->command_type == command_type || command_type == CLI_ANY_COMMAND) {
      if (c == cli->commands) cli->commands = c->next;
      // Unregister all child commands
      cli_free_command(cli, c);
    }
    c = p;
  }
}

void cli_unregister_all(struct cli_def *cli, struct cli_command *command) {
  cli_unregister_tree(cli, command, CLI_REGULAR_COMMAND);
}

int cli_done(struct cli_def *cli) {
  if (!cli) return CLI_OK;
  struct unp *u = cli->users, *n;

  cli_free_history(cli);

  // Free all users
  while (u) {
    if (u->username) free(u->username);
    if (u->password) free(u->password);
    n = u->next;
    free(u);
    u = n;
  }

  if (cli->buildmode) cli_int_free_buildmode(cli);
  cli_unregister_tree(cli, cli->commands, CLI_ANY_COMMAND);
  free_z(cli->promptchar);
  free_z(cli->modestring);
  free_z(cli->banner);
  free_z(cli->promptchar);
  free_z(cli->hostname);
  free_z(cli->buffer);
  free_z(cli);

  return CLI_OK;
}

static int cli_add_history(struct cli_def *cli, const char *cmd) {
  int i;
  for (i = 0; i < MAX_HISTORY; i++) {
    if (!cli->history[i]) {
      if (i == 0 || strcasecmp(cli->history[i - 1], cmd))
        if (!(cli->history[i] = strdup(cmd))) return CLI_ERROR;
      return CLI_OK;
    }
  }
  // No space found, drop one off the beginning of the list
  free(cli->history[0]);
  for (i = 0; i < MAX_HISTORY - 1; i++) cli->history[i] = cli->history[i + 1];
  if (!(cli->history[MAX_HISTORY - 1] = strdup(cmd))) return CLI_ERROR;
  return CLI_OK;
}

void cli_free_history(struct cli_def *cli) {
  int i;
  for (i = 0; i < MAX_HISTORY; i++) {
    if (cli->history[i]) free_z(cli->history[i]);
  }
}

static char *cli_int_return_newword(const char *start, const char *end) {
  int len = end - start;
  char *to = NULL;
  char *newword = NULL;

  // allocate space (including terminal NULL, then go through and deal with escaping characters as we copy them

  if (!(newword = calloc(len + 1, 1))) return 0;
  to = newword;
  while (start != end) {
    if (*start == '\\')
      start++;
    else
      *to++ = *start++;
  }
  return newword;
}

static int cli_parse_line(const char *line, char *words[], int max_words) {
  int nwords = 0;
  const char *p = line;
  const char *word_start = 0;
  int inquote = 0;

  while (*p) {
    if (!isspace(*p)) {
      word_start = p;
      break;
    }
    p++;
  }

  while (nwords < max_words - 1) {
    if (*p == '\\' && *(p + 1)) {
      p += 2;
    }

    /*
     * a 'word' terminates at:
     *   - end-of-string, whitespace (if not inside quotes)
     *   - start of quoted section (if word_start != NULL)
     *   - end of a quoted section
     *   - whitespace/pipe unless inside quotes
     */

    if (!*p || *p == inquote || (word_start && !inquote && (isspace(*p) || *p == '|'))) {
      // if we have a word start, extract from there to this character dealing with escapes
      if (word_start) {
        if (!(words[nwords++] = cli_int_return_newword(word_start, p))) return 0;
      }

      // now figure out how to proceed

      // if at end_of_string we're done
      if (!*p) break;

      // found matching quote, eat it
      if (inquote) p++;  // Skip over trailing quote if we have one
      inquote = 0;
      word_start = 0;
    } else if (!inquote && (*p == '"' || *p == '\'')) {
      if (word_start && word_start != p) {
        if (!(words[nwords++] = cli_int_return_newword(word_start, p))) return 0;
      }
      inquote = *p++;
      word_start = p;
    } else {
      if (!word_start) {
        if (*p == '|') {
          if (!(words[nwords++] = strdup("|"))) return 0;
        } else if (!isspace(*p))
          word_start = p;
      }

      p++;
    }
  }

  return nwords;
}

static char *join_words(int argc, char **argv) {
  char *p;
  int len = 0;
  int i;

  for (i = 0; i < argc; i++) {
    if (i) len += 1;

    len += strlen(argv[i]);
  }

  p = malloc(len + 1);
  if (!p) return NULL;
  p[0] = 0;

  for (i = 0; i < argc; i++) {
    if (i) strcat(p, " ");

    strcat(p, argv[i]);
  }

  return p;
}

int cli_run_command(struct cli_def *cli, const char *command) {
  int rc = CLI_ERROR;
  struct cli_pipeline *pipeline;

  // Split command into pipeline stages
  pipeline = cli_int_generate_pipeline(cli, command);

  // cli_int_validate_pipeline will deal with buildmode command setup, and return CLI_BUILDMODE_START if found.
  if (pipeline) rc = cli_int_validate_pipeline(cli, pipeline);

  if (rc == CLI_OK) {
    rc = cli_int_execute_pipeline(cli, pipeline);
  }
  cli_int_free_pipeline(pipeline);
  return rc;
}

void cli_get_completions(struct cli_def *cli, const char *command, char lastchar, struct cli_comphelp *comphelp) {
  struct cli_command *c = NULL;
  struct cli_command *n = NULL;

  int i;
  int command_type;
  struct cli_pipeline *pipeline = NULL;
  struct cli_pipeline_stage *stage;
  char *delim_start = DELIM_NONE;
  char *delim_end = DELIM_NONE;

  if (!(pipeline = cli_int_generate_pipeline(cli, command))) goto out;

  stage = &pipeline->stage[pipeline->num_stages - 1];

  // Check to see if either *no* input, or if the lastchar is a tab.
  if ((!stage->words[0] || (command[strlen(command) - 1] == ' ')) && (stage->words[stage->num_words - 1]))
    stage->num_words++;

  if (cli->buildmode)
    command_type = CLI_BUILDMODE_COMMAND;
  else if (pipeline->num_stages == 1)
    command_type = CLI_REGULAR_COMMAND;
  else
    command_type = CLI_FILTER_COMMAND;

  for (c = cli->commands, i = 0; c && i < stage->num_words; c = n) {
    char *strptr = NULL;
    char *nameptr = NULL;
    n = c->next;

    if (c->command_type != command_type) continue;
    if (cli->privilege < c->privilege) continue;
    if (c->mode != cli->mode && c->mode != MODE_ANY) continue;
    if (stage->words[i] && strncasecmp(c->command, stage->words[i], strlen(stage->words[i]))) continue;

    // Special case for 'buildmode' - skip if the argument for this command was seen, unless MULTIPLE flag is set
    if (cli->buildmode) {
      struct cli_optarg *optarg;
      for (optarg = cli->buildmode->command->optargs; optarg; optarg = optarg->next) {
        if (!strcmp(optarg->name, c->command)) break;
      }
      if (optarg && cli_find_optarg_value(cli, optarg->name, NULL) && !(optarg->flags & (CLI_CMD_OPTION_MULTIPLE)))
        continue;
    }
    if (i < stage->num_words - 1) {
      if (stage->words[i] && (strlen(stage->words[i]) < c->unique_len) && strcmp(stage->words[i], c->command)) continue;

      n = c->children;

      // If we have no more children, we've matched the *command* - remember this
      if (!c->children) break;

      i++;
      continue;
    }

    if (lastchar == '?') {
      delim_start = DELIM_NONE;
      delim_end = DELIM_NONE;

      // Note that buildmode commands need to see if that command is some optinal value

      if (command_type == CLI_BUILDMODE_COMMAND) {
        if (c->flags & (CLI_CMD_OPTIONAL_FLAG | CLI_CMD_OPTIONAL_ARGUMENT)) {
          delim_start = DELIM_OPT_START;
          delim_end = DELIM_OPT_END;
        }
      }
      if (asprintf(&nameptr, "%s%s%s", delim_start, c->command, delim_end) != -1) {
        if (asprintf(&strptr, "  %s", nameptr) != -1) {
          cli_int_wrap_help_line(strptr, c->help, comphelp);
          free_z(strptr);
        }
        free(nameptr);
      }
    } else {
      cli_add_comphelp_entry(comphelp, c->command);
    }
  }

out:
  if (c) {
    // Advance past first word of stage
    i++;
    stage->command = c;
    stage->first_unmatched = i;
    if (c->optargs) {
      cli_int_parse_optargs(cli, stage, c, lastchar, comphelp);
    } else if (lastchar == '?') {
      // Special case for getting help with no defined optargs....
      comphelp->num_entries = -1;
    }
    if (stage->status) {
      // if we had an error here we need to redraw the commandline
      cli_reprompt(cli);
    }
  }

  cli_int_free_pipeline(pipeline);
}

static void cli_clear_line(int sockfd, char *cmd, int l, int cursor) {
  // Use cmd as our buffer, and overwrite contents as needed.
  // Backspace to beginning
  memset((char *)cmd, '\b', cursor);
  _write(sockfd, cmd, cursor);

  // Overwrite existing cmd with spaces
  memset((char *)cmd, ' ', l);
  _write(sockfd, cmd, l);

  // ..and backspace again to beginning
  memset((char *)cmd, '\b', l);
  _write(sockfd, cmd, l);

  // Null cmd buffer
  memset((char *)cmd, 0, l);
}

void cli_reprompt(struct cli_def *cli) {
  if (!cli) return;
  cli->showprompt = 1;
}

void cli_regular(struct cli_def *cli, int (*callback)(struct cli_def *cli)) {
  if (!cli) return;
  cli->regular_callback = callback;
}

void cli_regular_interval(struct cli_def *cli, int seconds) {
  if (seconds < 1) seconds = 1;
  cli->timeout_tm.tv_sec = seconds;
  cli->timeout_tm.tv_usec = 0;
}

#define DES_PREFIX "{crypt}"  // To distinguish clear text from DES crypted
#define MD5_PREFIX "$1$"

// returns 0 on fail/error, 1 if password checks out
static int pass_matches(const char *pass, const char *attempt) {
  int des;
  if ((des = !strncasecmp(pass, DES_PREFIX, sizeof(DES_PREFIX) - 1))) pass += sizeof(DES_PREFIX) - 1;

#ifndef WIN32
  // TODO(dparrish): Find a small crypt(3) function for use on windows
  if (des || !strncmp(pass, MD5_PREFIX, sizeof(MD5_PREFIX) - 1)) attempt = crypt(attempt, pass);
#endif
  if (!attempt) {
    // silent return here...
    return 0;
  }
  return !strcmp(pass, attempt);
}

#define CTRL(c) (c - '@')

static int show_prompt(struct cli_def *cli, int sockfd) {
  int len = 0;

  if (cli->hostname) len += write(sockfd, cli->hostname, strlen(cli->hostname));

  if (cli->modestring) len += write(sockfd, cli->modestring, strlen(cli->modestring));
  if (cli->buildmode) {
    len += write(sockfd, "[", 1);
    len += write(sockfd, cli->buildmode->cname, strlen(cli->buildmode->cname));
    len += write(sockfd, "...", 3);
    if (cli->buildmode->mode_text) len += write(sockfd, cli->buildmode->mode_text, strlen(cli->buildmode->mode_text));
    len += write(sockfd, "]", 1);
  }
  return len + write(sockfd, cli->promptchar, strlen(cli->promptchar));
}

int cli_loop(struct cli_def *cli, int sockfd) {
  int n, l, oldl = 0, is_telnet_option = 0, skip = 0, esc = 0, cursor = 0;
  char *cmd = NULL, *oldcmd = 0;
  char *username = NULL, *password = NULL;

  cli_build_shortest(cli, cli->commands);
  cli->state = STATE_LOGIN;

  cli_free_history(cli);
  if (cli->telnet_protocol) {
    static const char *negotiate =
        "\xFF\xFB\x03"
        "\xFF\xFB\x01"
        "\xFF\xFD\x03"
        "\xFF\xFD\x01";
    _write(sockfd, negotiate, strlen(negotiate));
  }

  if ((cmd = malloc(CLI_MAX_LINE_LENGTH)) == NULL) return CLI_ERROR;

#ifdef WIN32
  /*
   * OMG, HACK
   */
  if (!(cli->client = fdopen(_open_osfhandle(sockfd, 0), "w+"))) return CLI_ERROR;
  cli->client->_file = sockfd;
#else
  if (!(cli->client = fdopen(sockfd, "w+"))) {
    free(cmd);
    return CLI_ERROR;
  }
#endif

#ifndef LIBCLI_USE_POLL
  /* Do a range check *early*, and punt if we were passed a file descriptor
   * that is out of the valid range
   */
  if (sockfd >= FD_SETSIZE) {
    fprintf(stderr, "CLI_LOOP() called with sockfd > FD_SETSIZE - aborting\n");
    cli_error(cli, "CLI_LOOP() called with sockfd > FD_SETSIZE - exiting cli_loop\n");
    return CLI_ERROR;
  }
#endif
  setbuf(cli->client, NULL);
  if (cli->banner) cli_error(cli, "%s", cli->banner);

  // Set the last action now so we don't time immediately
  if (cli->idle_timeout) time(&cli->last_action);

  // Start off in unprivileged mode
  cli_set_privilege(cli, PRIVILEGE_UNPRIVILEGED);
  cli_set_configmode(cli, MODE_EXEC, NULL);

  // No auth required?
  if (!cli->users && !cli->auth_callback) cli->state = STATE_NORMAL;

  while (1) {
    signed int in_history = 0;
    unsigned char lastchar = '\0';
    unsigned char c = '\0';
    struct timeval tm;

    cli->showprompt = 1;

    if (oldcmd) {
      l = cursor = oldl;
      oldcmd[l] = 0;
      cli->showprompt = 1;
      oldcmd = NULL;
      oldl = 0;
    } else {
      memset(cmd, 0, CLI_MAX_LINE_LENGTH);
      l = 0;
      cursor = 0;
    }

    memcpy(&tm, &cli->timeout_tm, sizeof(tm));

    while (1) {
      int sr;

      /*
       * Ensure our transient mode is reset to the starting mode on *each* loop traversal transient mode is valid only
       * while a command is being evaluated/executed.  Also explicitly set the disallow_buildmode flag based on whether
       * or not cli->buildmode is NULL or not.  The cli->buildmode flag can be changed during process, but the
       * enable/disable needs to be set before any processing is entered.
       */
      cli->transient_mode = cli->mode;
      cli->disallow_buildmode = (cli->buildmode) ? 1 : 0;

      if (cli->showprompt) {
        if (cli->state != STATE_PASSWORD && cli->state != STATE_ENABLE_PASSWORD) _write(sockfd, "\r\n", 2);

        switch (cli->state) {
          case STATE_LOGIN:
            _write(sockfd, "Username: ", strlen("Username: "));
            break;

          case STATE_PASSWORD:
            _write(sockfd, "Password: ", strlen("Password: "));
            break;

          case STATE_NORMAL:
          case STATE_ENABLE:
            show_prompt(cli, sockfd);
            _write(sockfd, cmd, l);
            if (cursor < l) {
              int n = l - cursor;
              while (n--) _write(sockfd, "\b", 1);
            }
            break;

          case STATE_ENABLE_PASSWORD:
            _write(sockfd, "Password: ", strlen("Password: "));
            break;
        }

        cli->showprompt = 0;
      }

      if ((sr = cli_socket_wait(sockfd, &tm)) < 0) {
        if (errno == EINTR) continue;
        perror(CLI_SOCKET_WAIT_PERROR);
        l = -1;
        break;
      }

      if (sr == 0) {
        // Timeout every second
        if (cli->regular_callback && cli->regular_callback(cli) != CLI_OK) {
          l = -1;
          break;
        }

        if (cli->idle_timeout) {
          if (time(NULL) - cli->last_action >= cli->idle_timeout) {
            if (cli->idle_timeout_callback) {
              // Call the callback and continue on if successful
              if (cli->idle_timeout_callback(cli) == CLI_OK) {
                // Reset the idle timeout counter
                time(&cli->last_action);
                continue;
              }
            }
            // Otherwise, break out of the main loop
            l = -1;
            break;
          }
        }

        memcpy(&tm, &cli->timeout_tm, sizeof(tm));
        continue;
      }

      if ((n = read(sockfd, &c, 1)) < 0) {
        if (errno == EINTR) continue;

        perror("read");
        l = -1;
        break;
      }

      if (cli->idle_timeout) time(&cli->last_action);

      if (n == 0) {
        l = -1;
        break;
      }

      if (skip) {
        skip--;
        continue;
      }

      if (c == 255 && !is_telnet_option) {
        is_telnet_option++;
        continue;
      }

      if (is_telnet_option) {
        if (c >= 251 && c <= 254) {
          is_telnet_option = c;
          continue;
        }

        if (c != 255) {
          is_telnet_option = 0;
          continue;
        }

        is_telnet_option = 0;
      }

      // Handle ANSI arrows
      if (esc) {
        if (esc == '[') {
          // Remap to readline control codes
          switch (c) {
            case 'A':  // Up
              c = CTRL('P');
              break;

            case 'B':  // Down
              c = CTRL('N');
              break;

            case 'C':  // Right
              c = CTRL('F');
              break;

            case 'D':  // Left
              c = CTRL('B');
              break;

            default:
              c = 0;
          }

          esc = 0;
        } else {
          esc = (c == '[') ? c : 0;
          continue;
        }
      }

      if (c == 0) continue;
      if (c == '\n') continue;

      if (c == '\r') {
        if (cli->state != STATE_PASSWORD && cli->state != STATE_ENABLE_PASSWORD) _write(sockfd, "\r\n", 2);
        break;
      }

      if (c == 27) {
        esc = 1;
        continue;
      }

      if (c == CTRL('C')) {
        _write(sockfd, "\a", 1);
        continue;
      }

      // Back word, backspace/delete
      if (c == CTRL('W') || c == CTRL('H') || c == 0x7f) {
        int back = 0;

        if (c == CTRL('W')) {
          // Word
          int nc = cursor;

          if (l == 0 || cursor == 0) continue;

          while (nc && cmd[nc - 1] == ' ') {
            nc--;
            back++;
          }

          while (nc && cmd[nc - 1] != ' ') {
            nc--;
            back++;
          }
        } else {
          // Char
          if (l == 0 || cursor == 0) {
            _write(sockfd, "\a", 1);
            continue;
          }

          back = 1;
        }

        if (back) {
          while (back--) {
            if (l == cursor) {
              cmd[--cursor] = 0;
              if (cli->state != STATE_PASSWORD && cli->state != STATE_ENABLE_PASSWORD) _write(sockfd, "\b \b", 3);
            } else {
              int i;
              if (cli->state != STATE_PASSWORD && cli->state != STATE_ENABLE_PASSWORD) {
                // Back up one space, then write current buffer followed by a space
                _write(sockfd, "\b", 1);
                _write(sockfd, cmd + cursor, l - cursor);
                _write(sockfd, " ", 1);

                // Move everything one char left
                memmove(cmd + cursor - 1, cmd + cursor, l - cursor);

                // Set former last char to null
                cmd[l - 1] = 0;

                // And reposition cursor
                for (i = l; i >= cursor; i--) _write(sockfd, "\b", 1);
              }
              cursor--;
            }
            l--;
          }

          continue;
        }
      }

      // Redraw
      if (c == CTRL('L')) {
        int i;
        int cursorback = l - cursor;

        if (cli->state == STATE_PASSWORD || cli->state == STATE_ENABLE_PASSWORD) continue;

        _write(sockfd, "\r\n", 2);
        show_prompt(cli, sockfd);
        _write(sockfd, cmd, l);

        for (i = 0; i < cursorback; i++) _write(sockfd, "\b", 1);

        continue;
      }

      // Clear line
      if (c == CTRL('U')) {
        if (cli->state == STATE_PASSWORD || cli->state == STATE_ENABLE_PASSWORD)
          memset(cmd, 0, l);
        else
          cli_clear_line(sockfd, cmd, l, cursor);

        l = cursor = 0;
        continue;
      }

      // Kill to EOL
      if (c == CTRL('K')) {
        if (cursor == l) continue;

        if (cli->state != STATE_PASSWORD && cli->state != STATE_ENABLE_PASSWORD) {
          int cptr;
          for (cptr = cursor; cptr < l; cptr++) _write(sockfd, " ", 1);

          for (cptr = cursor; cptr < l; cptr++) _write(sockfd, "\b", 1);
        }

        memset(cmd + cursor, 0, l - cursor);
        l = cursor;
        continue;
      }

      // EOT
      if (c == CTRL('D')) {
        if (cli->state == STATE_PASSWORD || cli->state == STATE_ENABLE_PASSWORD) break;

        if (l) continue;

        l = -1;
        break;
      }

      // Disable
      if (c == CTRL('Z')) {
        if (cli->mode != MODE_EXEC) {
          if (cli->buildmode) cli_int_free_buildmode(cli);
          cli_clear_line(sockfd, cmd, l, cursor);
          cli_set_configmode(cli, MODE_EXEC, NULL);
          l = cursor = 0;
          cli->showprompt = 1;
        }

        continue;
      }

      // TAB completion
      if (c == CTRL('I')) {
        struct cli_comphelp comphelp = {0};

        if (cli->state == STATE_LOGIN || cli->state == STATE_PASSWORD || cli->state == STATE_ENABLE_PASSWORD) continue;
        if (cursor != l) continue;

        cli_get_completions(cli, cmd, c, &comphelp);
        if (comphelp.num_entries == 0) {
          _write(sockfd, "\a", 1);
        } else if (lastchar == CTRL('I')) {
          // Double tab
          int i;
          for (i = 0; i < comphelp.num_entries; i++) {
            if (i % 4 == 0)
              _write(sockfd, "\r\n", 2);
            else
              _write(sockfd, " ", 1);
            _write(sockfd, comphelp.entries[i], strlen(comphelp.entries[i]));
          }
          _write(sockfd, "\r\n", 2);
          cli->showprompt = 1;
        } else if (comphelp.num_entries == 1) {
          // Single completion - show *unless* the optional/required 'prefix' is present
          if (comphelp.entries[0][0] != '[' && comphelp.entries[0][0] != '<') {
            for (; l > 0; l--, cursor--) {
              if (cmd[l - 1] == ' ' || cmd[l - 1] == '|' || (comphelp.comma_separated && cmd[l - 1] == ',')) break;
              _write(sockfd, "\b", 1);
            }
            strcpy((cmd + l), comphelp.entries[0]);
            l += strlen(comphelp.entries[0]);
            cmd[l++] = ' ';
            cursor = l;
            _write(sockfd, comphelp.entries[0], strlen(comphelp.entries[0]));
            _write(sockfd, " ", 1);
            // And now forget the tab, since we just found a single match
            lastchar = '\0';
          } else {
            // Yes, we had a match, but it wasn't required - remember the tab in case the user double tabs....
            lastchar = CTRL('I');
          }
        } else if (comphelp.num_entries > 1) {
          /*
           * More than one completion.
           * Show as many characters as we can until the completions start to differ.
           */
          lastchar = c;
          int i, j, k = 0;
          char *tptr = comphelp.entries[0];

          /*
           * Quickly try to see where our entries differ.
           * Corner cases:
           * - If all entries are optional, don't show *any* options unless user has provided a letter.
           * - If any entry starts with '<' then don't fill in anything.
           */

          // Skip a leading '['
          k = strlen(tptr);
          if (*tptr == '[')
            tptr++;
          else if (*tptr == '<')
            k = 0;

          for (i = 1; k != 0 && i < comphelp.num_entries; i++) {
            char *wptr = comphelp.entries[i];

            if (*wptr == '[')
              wptr++;
            else if (*wptr == '<')
              k = 0;

            for (j = 0; (j < k) && (j < (int)strlen(wptr)); j++) {
              if (strncasecmp(tptr + j, wptr + j, 1)) break;
            }
            k = j;
          }

          // Try to show minimum match string if we have a non-zero k and the first letter of the last word is not '['.
          if (k && comphelp.entries[comphelp.num_entries - 1][0] != '[') {
            for (; l > 0; l--, cursor--) {
              if (cmd[l - 1] == ' ' || cmd[l - 1] == '|' || (comphelp.comma_separated && cmd[l - 1] == ',')) break;
              _write(sockfd, "\b", 1);
            }
            strncpy(cmd + l, tptr, k);
            l += k;
            cursor = l;
            _write(sockfd, tptr, k);

          } else {
            _write(sockfd, "\a", 1);
          }
        }
        cli_free_comphelp(&comphelp);
        continue;
      }

      // '?' at end of line - generate applicable 'help' messages
      if (c == '?' && cursor == l) {
        struct cli_comphelp comphelp = {0};
        int i;
        int show_cr = 1;

        if (cli->state == STATE_LOGIN || cli->state == STATE_PASSWORD || cli->state == STATE_ENABLE_PASSWORD) continue;
        if (cursor != l) continue;

        cli_get_completions(cli, cmd, c, &comphelp);
        if (comphelp.num_entries == 0) {
          _write(sockfd, "\a", 1);
        } else if (comphelp.num_entries > 0) {
          cli->showprompt = 1;
          _write(sockfd, "\r\n", 2);
          for (i = 0; i < (int)comphelp.num_entries; i++) {
            if (comphelp.entries[i][2] != '[') show_cr = 0;
            cli_error(cli, "%s", comphelp.entries[i]);
          }
          if (show_cr) cli_error(cli, "  <cr>");
        }

        cli_free_comphelp(&comphelp);

        if (comphelp.num_entries >= 0) continue;
      }

      // History
      if (c == CTRL('P') || c == CTRL('N')) {
        int history_found = 0;

        if (cli->state == STATE_LOGIN || cli->state == STATE_PASSWORD || cli->state == STATE_ENABLE_PASSWORD) continue;

        if (c == CTRL('P')) {
          // Up
          in_history--;
          if (in_history < 0) {
            for (in_history = MAX_HISTORY - 1; in_history >= 0; in_history--) {
              if (cli->history[in_history]) {
                history_found = 1;
                break;
              }
            }
          } else {
            if (cli->history[in_history]) history_found = 1;
          }
        } else {
          // Down
          in_history++;
          if (in_history >= MAX_HISTORY || !cli->history[in_history]) {
            int i = 0;
            for (i = 0; i < MAX_HISTORY; i++) {
              if (cli->history[i]) {
                in_history = i;
                history_found = 1;
                break;
              }
            }
          } else {
            if (cli->history[in_history]) history_found = 1;
          }
        }
        if (history_found && cli->history[in_history]) {
          // Show history item
          cli_clear_line(sockfd, cmd, l, cursor);
          memset(cmd, 0, CLI_MAX_LINE_LENGTH);
          strncpy(cmd, cli->history[in_history], CLI_MAX_LINE_LENGTH - 1);
          l = cursor = strlen(cmd);
          _write(sockfd, cmd, l);
        }

        continue;
      }

      // Left/right cursor motion
      if (c == CTRL('B') || c == CTRL('F')) {
        if (c == CTRL('B')) {
          // Left
          if (cursor) {
            if (cli->state != STATE_PASSWORD && cli->state != STATE_ENABLE_PASSWORD) _write(sockfd, "\b", 1);

            cursor--;
          }
        } else {
          // Right
          if (cursor < l) {
            if (cli->state != STATE_PASSWORD && cli->state != STATE_ENABLE_PASSWORD) _write(sockfd, &cmd[cursor], 1);

            cursor++;
          }
        }

        continue;
      }

      if (c == CTRL('A')) {
        // Start of line
        if (cursor) {
          if (cli->state != STATE_PASSWORD && cli->state != STATE_ENABLE_PASSWORD) {
            _write(sockfd, "\r", 1);
            show_prompt(cli, sockfd);
          }

          cursor = 0;
        }

        continue;
      }

      if (c == CTRL('E')) {
        // End of line
        if (cursor < l) {
          if (cli->state != STATE_PASSWORD && cli->state != STATE_ENABLE_PASSWORD)
            _write(sockfd, &cmd[cursor], l - cursor);

          cursor = l;
        }

        continue;
      }

      if (cursor == l) {
        // Normal character typed.
        // Append to end of line if not at end-of-buffer.
        if (l < CLI_MAX_LINE_LENGTH - 1) {
          cmd[cursor] = c;
          l++;
          cursor++;
        } else {
          // End-of-buffer, ensure null terminated
          cmd[cursor] = 0;
          _write(sockfd, "\a", 1);
          continue;
        }
      } else {
        // Middle of text
        int i;
        // Move everything one character to the right
        memmove(cmd + cursor + 1, cmd + cursor, l - cursor);

        // Insert new character
        cmd[cursor] = c;

        // IMPORTANT - if at end of buffer, set last char to NULL and don't change length, otherwise bump length by 1
        if (l == CLI_MAX_LINE_LENGTH - 1) {
          cmd[l] = 0;
        } else {
          l++;
        }

        // Write buffer, then backspace to where we were
        _write(sockfd, cmd + cursor, l - cursor);

        for (i = 0; i < (l - cursor); i++) _write(sockfd, "\b", 1);
        cursor++;
      }

      if (cli->state != STATE_PASSWORD && cli->state != STATE_ENABLE_PASSWORD) {
        if (c == '?' && cursor == l) {
          _write(sockfd, "\r\n", 2);
          oldcmd = cmd;
          oldl = cursor = l - 1;
          break;
        }
        _write(sockfd, &c, 1);
      }

      oldcmd = 0;
      oldl = 0;
      lastchar = c;
    }

    if (l < 0) break;

    if (cli->state == STATE_LOGIN) {
      if (l == 0) continue;

      // Require login
      free_z(username);
      if (!(username = strdup(cmd))) return 0;
      cli->state = STATE_PASSWORD;
      cli->showprompt = 1;
    } else if (cli->state == STATE_PASSWORD) {
      // Require password
      int allowed = 0;

      free_z(password);
      if (!(password = strdup(cmd))) return 0;
      if (cli->auth_callback) {
        if (cli->auth_callback(username, password) == CLI_OK) allowed++;
      }

      if (!allowed) {
        struct unp *u;
        for (u = cli->users; u; u = u->next) {
          if (!strcmp(u->username, username) && pass_matches(u->password, password)) {
            allowed++;
            break;
          }
        }
      }

      if (allowed) {
        cli_error(cli, " ");
        cli->state = STATE_NORMAL;
      } else {
        cli_error(cli, "\n\nAccess denied");
        free_z(username);
        free_z(password);
        cli->state = STATE_LOGIN;
      }

      cli->showprompt = 1;
    } else if (cli->state == STATE_ENABLE_PASSWORD) {
      int allowed = 0;
      if (cli->enable_password) {
        // Check stored static enable password
        if (pass_matches(cli->enable_password, cmd)) allowed++;
      }

      if (!allowed && cli->enable_callback) {
        // Check callback
        if (cli->enable_callback(cmd)) allowed++;
      }

      if (allowed) {
        cli->state = STATE_ENABLE;
        cli_set_privilege(cli, PRIVILEGE_PRIVILEGED);
      } else {
        cli_error(cli, "\n\nAccess denied");
        cli->state = STATE_NORMAL;
      }
    } else {
      int rc;
      if (l == 0) continue;
      if (cmd[l - 1] != '?' && strcasecmp(cmd, "history") != 0) cli_add_history(cli, cmd);

      rc = cli_run_command(cli, cmd);
      switch (rc) {
        case CLI_BUILDMODE_ERROR:
          // Unable to enter buildmode successfully
          cli_print(cli, "Failure entering build mode for '%s'", cli->buildmode->cname);
          cli_int_free_buildmode(cli);
          continue;
        case CLI_BUILDMODE_CANCEL:
          // Called if user enters 'cancel'
          cli_print(cli, "Canceling build mode for '%s'", cli->buildmode->cname);
          cli_int_free_buildmode(cli);
          break;
        case CLI_BUILDMODE_EXIT:
          // Called when user enters exit - rebuild *entire* command line.
          // Recall all located optargs
          cli->found_optargs = cli->buildmode->found_optargs;
          rc = cli_int_execute_buildmode(cli);
          break;
        case CLI_QUIT:
          break;
        case CLI_BUILDMODE_START:
        case CLI_BUILDMODE_EXTEND:
        default:
          break;
      }

      // Process is done if we get a CLI_QUIT,
      if (rc == CLI_QUIT) break;
    }

    // Update the last_action time now as the last command run could take a long time to return
    if (cli->idle_timeout) time(&cli->last_action);
  }

  cli_free_history(cli);
  free_z(username);
  free_z(password);
  free_z(cmd);

  fclose(cli->client);
  cli->client = 0;
  return CLI_OK;
}

int cli_file(struct cli_def *cli, FILE *fh, int privilege, int mode) {
  int oldpriv = cli_set_privilege(cli, privilege);
  int oldmode = cli_set_configmode(cli, mode, NULL);
  char buf[CLI_MAX_LINE_LENGTH];

  while (1) {
    char *p;
    char *cmd;
    char *end;

    // End of file
    if (fgets(buf, CLI_MAX_LINE_LENGTH - 1, fh) == NULL) break;

    if ((p = strpbrk(buf, "#\r\n"))) *p = 0;

    cmd = buf;
    while (isspace(*cmd)) cmd++;

    if (!*cmd) continue;

    for (p = end = cmd; *p; p++)
      if (!isspace(*p)) end = p;

    *++end = 0;
    if (strcasecmp(cmd, "quit") == 0) break;

    if (cli_run_command(cli, cmd) == CLI_QUIT) break;
  }

  cli_set_privilege(cli, oldpriv);
  cli_set_configmode(cli, oldmode, NULL);

  return CLI_OK;
}

static void _print(struct cli_def *cli, int print_mode, const char *format, va_list ap) {
  int n;
  char *p = NULL;

  if (!cli) return;

  n = vasprintf(&p, format, ap);
  if (n < 0) return;
  if (cli->buffer) free(cli->buffer);
  cli->buffer = p;
  cli->buf_size = n;

  p = cli->buffer;
  do {
    char *next = strchr(p, '\n');
    struct cli_filter *f = (print_mode & PRINT_FILTERED) ? cli->filters : 0;
    int print = 1;

    if (next)
      *next++ = 0;
    else if (print_mode & PRINT_BUFFERED)
      break;

    while (print && f) {
      print = (f->filter(cli, p, f->data) == CLI_OK);
      f = f->next;
    }
    if (print) {
      if (cli->print_callback)
        cli->print_callback(cli, p);
      else if (cli->client)
        fprintf(cli->client, "%s\r\n", p);
    }

    p = next;
  } while (p);

  if (p && *p) {
    if (p != cli->buffer) memmove(cli->buffer, p, strlen(p));
  } else
    *cli->buffer = 0;
}

void cli_bufprint(struct cli_def *cli, const char *format, ...) {
  va_list ap;

  va_start(ap, format);
  _print(cli, PRINT_BUFFERED | PRINT_FILTERED, format, ap);
  va_end(ap);
}

void cli_vabufprint(struct cli_def *cli, const char *format, va_list ap) {
  _print(cli, PRINT_BUFFERED, format, ap);
}

void cli_print(struct cli_def *cli, const char *format, ...) {
  va_list ap;

  va_start(ap, format);
  _print(cli, PRINT_FILTERED, format, ap);
  va_end(ap);
}

void cli_error(struct cli_def *cli, const char *format, ...) {
  va_list ap;

  va_start(ap, format);
  _print(cli, PRINT_PLAIN, format, ap);
  va_end(ap);
}

struct cli_match_filter_state {
  int flags;
  union {
    char *string;
    regex_t re;
  } match;
};

int cli_search_flags_validator(struct cli_def *cli, const char *word, const char *value) {
  // Valid search flags starts with a hyphen, then any number of i, v, or e characters.

  if ((*value++ == '-') && (*value) && (strspn(value, "vie") == strlen(value))) return CLI_OK;
  return CLI_ERROR;
}

int cli_match_filter_init(struct cli_def *cli, int argc, char **argv, struct cli_filter *filt) {
  struct cli_match_filter_state *state;
  char *search_pattern = cli_get_optarg_value(cli, "search_pattern", NULL);
  char *search_flags = cli_get_optarg_value(cli, "search_flags", NULL);

  filt->filter = cli_match_filter;
  filt->data = state = calloc(1, sizeof(struct cli_match_filter_state));
  if (!state) return CLI_ERROR;

  if (!strcmp(cli->pipeline->current_stage->words[0], "include")) {
    state->match.string = search_pattern;
  } else if (!strcmp(cli->pipeline->current_stage->words[0], "exclude")) {
    state->match.string = search_pattern;
    state->flags = MATCH_INVERT;
#ifndef WIN32
  } else {
    int rflags = REG_NOSUB;
    if (!strcmp(cli->pipeline->current_stage->words[0], "grep")) {
      state->flags = MATCH_REGEX;
    } else if (!strcmp(cli->pipeline->current_stage->words[0], "egrep")) {
      state->flags = MATCH_REGEX;
      rflags |= REG_EXTENDED;
    }
    if (search_flags) {
      char *p = search_flags++;
      while (*p) {
        switch (*p++) {
          case 'v':
            state->flags |= MATCH_INVERT;
            break;

          case 'i':
            rflags |= REG_ICASE;
            break;

          case 'e':
            // Implies next term is search string, so stop processing flags
            break;
        }
      }
    }
    if (regcomp(&state->match.re, search_pattern, rflags)) {
      if (cli->client) fprintf(cli->client, "Invalid pattern \"%s\"\r\n", search_pattern);
      return CLI_ERROR;
    }
  }
#else
  } else {
    // No regex functions in windows, so return an error.
    return CLI_ERROR;
  }
#endif

  return CLI_OK;
}

int cli_match_filter(UNUSED(struct cli_def *cli), const char *string, void *data) {
  struct cli_match_filter_state *state = data;
  int r = CLI_ERROR;

  if (!string) {
    if (state->flags & MATCH_REGEX) regfree(&state->match.re);

    free(state);
    return CLI_OK;
  }

  if (state->flags & MATCH_REGEX) {
    if (!regexec(&state->match.re, string, 0, NULL, 0)) r = CLI_OK;
  } else {
    if (strstr(string, state->match.string)) r = CLI_OK;
  }

  if (state->flags & MATCH_INVERT) {
    if (r == CLI_OK)
      r = CLI_ERROR;
    else
      r = CLI_OK;
  }

  return r;
}

struct cli_range_filter_state {
  int matched;
  char *from;
  char *to;
};

int cli_range_filter_init(struct cli_def *cli, int argc, char **argv, struct cli_filter *filt) {
  struct cli_range_filter_state *state;
  char *from = cli_get_optarg_value(cli, "range_start", NULL);
  char *to = cli_get_optarg_value(cli, "range_end", NULL);

  // Do not have to check from/to since we would not have gotten here if we were missing a required argument.
  // Note that since those pointers are not NULL, we don't have to strdup them or free them - just use the pointer
  //    from the command line processing and continue

  filt->filter = cli_range_filter;
  filt->data = state = calloc(1, sizeof(struct cli_range_filter_state));
  if (state) {
    state->from = from;
    state->to = to;
    return CLI_OK;
  } else {
    return CLI_ERROR;
  }
}

int cli_range_filter(UNUSED(struct cli_def *cli), const char *string, void *data) {
  struct cli_range_filter_state *state = data;
  int r = CLI_ERROR;

  if (!string) {
    free_z(state);
    return CLI_OK;
  }

  if (!state->matched) state->matched = !!strstr(string, state->from);

  if (state->matched) {
    r = CLI_OK;
    if (state->to && strstr(string, state->to)) state->matched = 0;
  }

  return r;
}

int cli_count_filter_init(struct cli_def *cli, int argc, UNUSED(char **argv), struct cli_filter *filt) {
  if (argc > 1) {
    if (cli->client) fprintf(cli->client, "Count filter does not take arguments\r\n");

    return CLI_ERROR;
  }

  filt->filter = cli_count_filter;
  if (!(filt->data = calloc(1, sizeof(int)))) return CLI_ERROR;

  return CLI_OK;
}

int cli_count_filter(struct cli_def *cli, const char *string, void *data) {
  int *count = data;

  if (!string) {
    // Print count
    if (cli->client) fprintf(cli->client, "%d\r\n", *count);

    free(count);
    return CLI_OK;
  }

  while (isspace(*string)) string++;

  // Only count non-blank lines
  if (*string) (*count)++;

  return CLI_ERROR;
}

void cli_print_callback(struct cli_def *cli, void (*callback)(struct cli_def *, const char *)) {
  cli->print_callback = callback;
}

void cli_set_idle_timeout(struct cli_def *cli, unsigned int seconds) {
  if (seconds < 1) seconds = 0;
  cli->idle_timeout = seconds;
  time(&cli->last_action);
}

void cli_set_idle_timeout_callback(struct cli_def *cli, unsigned int seconds, int (*callback)(struct cli_def *)) {
  cli_set_idle_timeout(cli, seconds);
  cli->idle_timeout_callback = callback;
}

void cli_telnet_protocol(struct cli_def *cli, int telnet_protocol) {
  cli->telnet_protocol = !!telnet_protocol;
}
void cli_set_context(struct cli_def *cli, void *context) {
  cli->user_context = context;
}

void *cli_get_context(struct cli_def *cli) {
  return cli->user_context;
}

struct cli_command *cli_register_filter(struct cli_def *cli, const char *command,
                                        int (*init)(struct cli_def *cli, int, char **, struct cli_filter *),
                                        int (*filter)(struct cli_def *, const char *, void *), int privilege, int mode,
                                        const char *help) {
  struct cli_command *c;

  if (!command) return NULL;
  if (!(c = calloc(1, sizeof(struct cli_command)))) return NULL;

  c->command_type = CLI_FILTER_COMMAND;
  c->init = init;
  c->filter = filter;
  c->next = NULL;
  if (!(c->command = strdup(command))) {
    free(c);
    return NULL;
  }

  c->privilege = privilege;
  c->mode = mode;
  if (help && !(c->help = strdup(help))) {
    free(c->command);
    free(c);
    return NULL;
  }

  // Filters are all registered at the top level.
  return cli_register_command_core(cli, NULL, c);
}

int cli_unregister_filter(struct cli_def *cli, const char *command) {
  return cli_int_unregister_command_core(cli, command, CLI_FILTER_COMMAND);
}

void cli_int_free_found_optargs(struct cli_optarg_pair **optarg_pair) {
  struct cli_optarg_pair *c;

  if (!optarg_pair || !*optarg_pair) return;

  for (c = *optarg_pair; c;) {
    *optarg_pair = c->next;
    free_z(c->name);
    free_z(c->value);
    free_z(c);
    c = *optarg_pair;
  }
}

char *cli_find_optarg_value(struct cli_def *cli, char *name, char *find_after) {
  char *value = NULL;
  struct cli_optarg_pair *optarg_pair;
  if (!name || !cli->found_optargs) return NULL;

  for (optarg_pair = cli->found_optargs; optarg_pair && !value; optarg_pair = optarg_pair->next) {
    if (strcmp(optarg_pair->name, name) == 0) {
      if (find_after && find_after == optarg_pair->value) {
        find_after = NULL;
        continue;
      }
      value = optarg_pair->value;
    }
  }
  return value;
}

static void cli_optarg_build_shortest(struct cli_optarg *optarg) {
  struct cli_optarg *c, *p;
  char *cp, *pp;
  unsigned int len;

  for (c = optarg; c; c = c->next) {
    c->unique_len = 1;
    for (p = optarg; p; p = p->next) {
      if (c == p) continue;
      cp = c->name;
      pp = p->name;
      len = 1;
      while (*cp && *pp && *cp++ == *pp++) len++;
      if (len > c->unique_len) c->unique_len = len;
    }
  }
}

void cli_free_optarg(struct cli_optarg *optarg) {
  free_z(optarg->help);
  free_z(optarg->name);
  free_z(optarg);
}

int cli_optarg_addhelp(struct cli_optarg *optarg, const char *helpname, const char *helptext) {
  char *tstr;

  // put a vertical tab (\v), the new helpname, a horizontal tab (\t), and then the new help text
  if ((!optarg) || (asprintf(&tstr, "%s\v%s\t%s", optarg->help, helpname, helptext) == -1)) {
    return CLI_ERROR;
  } else {
    free(optarg->help);
    optarg->help = tstr;
  }
  return CLI_OK;
}

struct cli_optarg *cli_register_optarg(struct cli_command *cmd, const char *name, int flags, int privilege, int mode,
                                       const char *help,
                                       int (*get_completions)(struct cli_def *cli, const char *, const char *,
                                                              struct cli_comphelp *),
                                       int (*validator)(struct cli_def *cli, const char *, const char *),
                                       int (*transient_mode)(struct cli_def *cli, const char *, const char *)) {
  struct cli_optarg *optarg = NULL;
  struct cli_optarg *lastopt = NULL;
  struct cli_optarg *ptr = NULL;
  int retval = CLI_ERROR;

  // Name must not already exist with this priv/mode
  for (ptr = cmd->optargs, lastopt = NULL; ptr; lastopt = ptr, ptr = ptr->next) {
    if (!strcmp(name, ptr->name) && ptr->mode == mode && ptr->privilege == privilege) {
      goto CLEANUP;
    }
  }
  if (!(optarg = calloc(1, sizeof(struct cli_optarg)))) goto CLEANUP;
  if (!(optarg->name = strdup(name))) goto CLEANUP;
  if (help && !(optarg->help = strdup(help))) goto CLEANUP;

  optarg->mode = mode;
  optarg->privilege = privilege;
  optarg->get_completions = get_completions;
  optarg->validator = validator;
  optarg->transient_mode = transient_mode;
  optarg->flags = flags;

  if (lastopt)
    lastopt->next = optarg;
  else
    cmd->optargs = optarg;
  cli_optarg_build_shortest(cmd->optargs);
  retval = CLI_OK;

CLEANUP:
  if (retval != CLI_OK) {
    cli_free_optarg(optarg);
    optarg = NULL;
  }
  return optarg;
}

int cli_unregister_optarg(struct cli_command *cmd, const char *name) {
  struct cli_optarg *ptr;
  struct cli_optarg *lastptr;
  int retval = CLI_ERROR;
  // Iterate looking for this option name, stopping at end or if name matches
  for (lastptr = NULL, ptr = cmd->optargs; ptr && strcmp(ptr->name, name); lastptr = ptr, ptr = ptr->next)
    ;

  // If ptr, then we found the optarg to delete
  if (ptr) {
    if (lastptr) {
      // Not first optarg
      lastptr->next = ptr->next;
      ptr->next = NULL;
    } else {
      // First optarg
      cmd->optargs = ptr->next;
      ptr->next = NULL;
    }
    cli_free_optarg(ptr);
    cli_optarg_build_shortest(cmd->optargs);
    retval = CLI_OK;
  }
  return retval;
}

void cli_unregister_all_optarg(struct cli_command *c) {
  struct cli_optarg *o, *p;

  for (o = c->optargs; o; o = p) {
    p = o->next;
    cli_free_optarg(o);
  }
}

void cli_int_unset_optarg_value(struct cli_def *cli, const char *name) {
  struct cli_optarg_pair **p, *c;
  for (p = &cli->found_optargs, c = *p; *p;) {
    c = *p;

    if (!strcmp(c->name, name)) {
      *p = c->next;
      free_z(c->name);
      free_z(c->value);
      free_z(c);
    } else {
      p = &(*p)->next;
    }
  }
}

int cli_set_optarg_value(struct cli_def *cli, const char *name, const char *value, int allow_multiple) {
  struct cli_optarg_pair *optarg_pair, **anchor;
  int rc = CLI_ERROR;

  for (optarg_pair = cli->found_optargs, anchor = &cli->found_optargs; optarg_pair;
       anchor = &optarg_pair->next, optarg_pair = optarg_pair->next) {
    // Break if we found this name *and* allow_multiple is false
    if (!strcmp(optarg_pair->name, name) && !allow_multiple) {
      break;
    }
  }
  // If we *didn't* find this, then allocate a new entry before proceeding
  if (!optarg_pair) {
    optarg_pair = (struct cli_optarg_pair *)calloc(1, sizeof(struct cli_optarg_pair));
    *anchor = optarg_pair;
  }
  // Set the value
  if (optarg_pair) {
    // Name is null only if we didn't find it
    if (!optarg_pair->name) optarg_pair->name = strdup(name);

    // Value may be overwritten, so free any old value.
    if (optarg_pair->value) free_z(optarg_pair->value);
    optarg_pair->value = strdup(value);

    rc = CLI_OK;
  }
  return rc;
}

struct cli_optarg_pair *cli_get_all_found_optargs(struct cli_def *cli) {
  if (cli) return cli->found_optargs;
  return NULL;
}

char *cli_get_optarg_value(struct cli_def *cli, const char *name, char *find_after) {
  char *value = NULL;
  struct cli_optarg_pair *optarg_pair;

  for (optarg_pair = cli->found_optargs; !value && optarg_pair; optarg_pair = optarg_pair->next) {
    // Check next entry if this isn't our name
    if (strcasecmp(optarg_pair->name, name)) continue;

    // Did we have a find_after, then ignore anything up until our find_after match
    if (find_after && optarg_pair->value == find_after) {
      find_after = NULL;
      continue;
    } else if (!find_after) {
      value = optarg_pair->value;
    }
  }
  return value;
}

void cli_int_free_buildmode(struct cli_def *cli) {
  if (!cli || !cli->buildmode) return;
  cli_unregister_tree(cli, cli->commands, CLI_BUILDMODE_COMMAND);
  cli->mode = cli->buildmode->mode;
  free_z(cli->buildmode->mode_text);
  cli_int_free_found_optargs(&cli->buildmode->found_optargs);
  free_z(cli->buildmode);
}

int cli_int_enter_buildmode(struct cli_def *cli, struct cli_pipeline_stage *stage, char *mode_text) {
  struct cli_optarg *optarg;
  struct cli_command *c;
  struct cli_optarg *o;
  struct cli_buildmode *buildmode;
  struct cli_optarg *buildmodeOptarg = NULL;
  int rc = CLI_BUILDMODE_START;

  if (!(buildmode = (struct cli_buildmode *)calloc(1, sizeof(struct cli_buildmode)))) {
    cli_error(cli, "Unable to build buildmode mode for command %s", stage->command->command);
    rc = CLI_BUILDMODE_ERROR;
    goto out;
  }

  // Clean up any shrapnel from earlier - shouldn't be any but....
  if (cli->buildmode) cli_int_free_buildmode(cli);

  // Assign it so cli_int_register_buildmode_command() has something to work with
  cli->buildmode = buildmode;
  cli->buildmode->mode = cli->mode;
  cli->buildmode->transient_mode = cli->transient_mode;
  if (mode_text) cli->buildmode->mode_text = strdup(mode_text);

  // Need this to verify we have all *required* arguments
  cli->buildmode->command = stage->command;

  // Build new *limited* list of commands from this commands optargs
  // Currently we only allow a single entry point to a buildmode, so advance t that
  // optarg and proceed from there.
  for (buildmodeOptarg = stage->command->optargs;
       buildmodeOptarg && !(buildmodeOptarg->flags & CLI_CMD_ALLOW_BUILDMODE); buildmodeOptarg = buildmodeOptarg->next)
    ;

  // Now start at this argument and flesh out the rest of the commands available for this buildmode
  for (optarg = buildmodeOptarg; optarg; optarg = optarg->next) {
    // Don't allow anything that could redefine our mode or buildmode mode, or redefine exit/cancel/show/unset
    if (!strcmp(optarg->name, "cancel") || !strcmp(optarg->name, "execute") || !strcmp(optarg->name, "show") ||
        !strcmp(optarg->name, "unset")) {
      cli_error(cli, "Default buildmode command conflicts with optarg named %s", optarg->name);
      rc = CLI_BUILDMODE_ERROR;
      goto out;
    }
    if (optarg->flags & (CLI_CMD_ALLOW_BUILDMODE | CLI_CMD_TRANSIENT_MODE | CLI_CMD_SPOT_CHECK)) continue;
    // accept the first optarg allowing buildmode, but reject any subsequent one
    if (optarg->flags & CLI_CMD_ALLOW_BUILDMODE && (optarg != buildmodeOptarg)) continue;
    if (optarg->mode != cli->mode && optarg->mode != cli->transient_mode)
      continue;
    else if (optarg->flags & (CLI_CMD_OPTIONAL_ARGUMENT | CLI_CMD_ARGUMENT)) {
      if ((c = cli_int_register_buildmode_command(cli, NULL, optarg->name, cli_int_buildmode_cmd_cback, optarg->flags,
                                                  optarg->privilege, cli->mode, optarg->help))) {
        cli_register_optarg(c, optarg->name, CLI_CMD_ARGUMENT | (optarg->flags & CLI_CMD_OPTION_MULTIPLE),
                            optarg->privilege, cli->mode, optarg->help, optarg->get_completions, optarg->validator,
                            NULL);
      } else {
        rc = CLI_BUILDMODE_ERROR;
        goto out;
      }
    } else {
      if (optarg->flags & CLI_CMD_OPTION_MULTIPLE) {
        if (!cli_int_register_buildmode_command(cli, NULL, optarg->name, cli_int_buildmode_flag_multiple_cback,
                                                optarg->flags, optarg->privilege, cli->mode, optarg->help)) {
          rc = CLI_BUILDMODE_ERROR;
          goto out;
        }
      } else {
        if (!cli_int_register_buildmode_command(cli, NULL, optarg->name, cli_int_buildmode_flag_cback, optarg->flags,
                                                optarg->privilege, cli->mode, optarg->help)) {
          rc = CLI_BUILDMODE_ERROR;
          goto out;
        }
      }
    }
  }
  cli->buildmode->cname = cli_command_name(cli, stage->command);
  // Now add the four 'always there' commands to cancel current mode and to execute the command, show settings, and
  // unset
  c = cli_int_register_buildmode_command(cli, NULL, "cancel", cli_int_buildmode_cancel_cback, 0, PRIVILEGE_UNPRIVILEGED,
                                         cli->mode, "Cancel command");
  if (!c) {
    rc = CLI_BUILDMODE_ERROR;
    goto out;
  }
  c = cli_int_register_buildmode_command(cli, NULL, "execute", cli_int_buildmode_execute_cback, 0,
                                         PRIVILEGE_UNPRIVILEGED, cli->mode, "Execute command");
  if (!c) {
    rc = CLI_BUILDMODE_ERROR;
    goto out;
  }
  c = cli_int_register_buildmode_command(cli, NULL, "show", cli_int_buildmode_show_cback, 0, PRIVILEGE_UNPRIVILEGED,
                                         cli->mode, "Show current settings");
  if (!c) {
    rc = CLI_BUILDMODE_ERROR;
    goto out;
  }
  c = cli_int_register_buildmode_command(cli, NULL, "unset", cli_int_buildmode_unset_cback, 0, PRIVILEGE_UNPRIVILEGED,
                                         cli->mode, "Unset a setting");
  if (!c) {
    rc = CLI_BUILDMODE_ERROR;
    goto out;
  }
  o = cli_register_optarg(c, "setting", CLI_CMD_ARGUMENT | CLI_CMD_DO_NOT_RECORD, PRIVILEGE_UNPRIVILEGED, cli->mode,
                          "setting to clear", cli_int_buildmode_unset_completor, cli_int_buildmode_unset_validator,
                          NULL);
  if (!o) {
    rc = CLI_BUILDMODE_ERROR;
    goto out;
  }

out:
  // And lastly set the initial help menu for the unset command
  cli_int_buildmode_reset_unset_help(cli);
  if (rc != CLI_BUILDMODE_START) cli_int_free_buildmode(cli);
  return rc;
}

int cli_int_unregister_buildmode_command(struct cli_def *cli, const char *command) {
  return cli_int_unregister_command_core(cli, command, CLI_BUILDMODE_COMMAND);
}

struct cli_command *cli_int_register_buildmode_command(struct cli_def *cli, struct cli_command *parent,
                                                       const char *command,
                                                       int (*callback)(struct cli_def *cli, const char *, char **, int),
                                                       int flags, int privilege, int mode, const char *help) {
  struct cli_command *c;

  if (!command) return NULL;
  if (!(c = calloc(1, sizeof(struct cli_command)))) return NULL;

  c->flags = flags;
  c->callback = callback;
  c->next = NULL;
  if (!(c->command = strdup(command))) {
    free(c);
    return NULL;
  }

  c->command_type = CLI_BUILDMODE_COMMAND;
  c->privilege = privilege;
  c->mode = mode;
  if (help && !(c->help = strndup(help, strchrnul(help, '\v') - help))) {
    free(c->command);
    free(c);
    return NULL;
  }

  // Buildmode commmands are all registered at the top level
  return cli_register_command_core(cli, NULL, c);
}

int cli_int_execute_buildmode(struct cli_def *cli) {
  struct cli_optarg *optarg = NULL;
  int rc = CLI_OK;
  char *cmdline;
  char *value = NULL;

  cmdline = strdup(cli_command_name(cli, cli->buildmode->command));
  if (!cmdline) {
    cli_error(cli, "Unable to allocate memory to process buildmode commandline");
    rc = CLI_ERROR;
  }
  for (optarg = cli->buildmode->command->optargs; rc == CLI_OK && optarg; optarg = optarg->next) {
    value = NULL;
    do {
      if (cli->privilege < optarg->privilege) continue;
      if ((optarg->mode != cli->buildmode->mode) && (optarg->mode != cli->buildmode->transient_mode) &&
          (optarg->mode != MODE_ANY))
        continue;

      value = cli_get_optarg_value(cli, optarg->name, value);
      if (!value && optarg->flags & CLI_CMD_ARGUMENT) {
        cli_error(cli, "Missing required argument %s", optarg->name);
        rc = CLI_MISSING_ARGUMENT;
      } else if (value) {
        if (optarg->flags & (CLI_CMD_OPTIONAL_FLAG | CLI_CMD_ARGUMENT)) {
          if (!(cmdline = cli_int_buildmode_extend_cmdline(cmdline, value))) {
            cli_error(cli, "Unable to allocate memory to process buildmode commandline");
            rc = CLI_ERROR;
          }
        } else {
          if (!(cmdline = cli_int_buildmode_extend_cmdline(cmdline, optarg->name))) {
            cli_error(cli, "Unable to allocate memory to process buildmode commandline");
            rc = CLI_ERROR;
          }
          if (!(cmdline = cli_int_buildmode_extend_cmdline(cmdline, value))) {
            cli_error(cli, "Unable to allocate memory to process buildmode commandline");
            rc = CLI_ERROR;
          }
        }
      }
    } while (rc == CLI_OK && value && optarg->flags & CLI_CMD_OPTION_MULTIPLE);
  }

  if (rc == CLI_OK) {
    cli_int_free_buildmode(cli);
    cli_add_history(cli, cmdline);
    // disallow processing of buildmode so we don't wind up in a potential loop
    // main loop will also set as required
    cli->disallow_buildmode = 1;
    rc = cli_run_command(cli, cmdline);
  }
  free_z(cmdline);
  return rc;
}

char *cli_int_buildmode_extend_cmdline(char *cmdline, char *word) {
  char *tptr = NULL;
  char *cptr = NULL;
  size_t oldlen = strlen(cmdline);
  size_t wordlen = strlen(word);
  char quoteChar[2] = "";

  // by default we don't add quotes, but if the word is empty, we *must* to preserve that empty string
  // we also need to quote it if there is a space in the word, or any unescaped quotes, so we'll have
  // to walk the word....
  cptr = word;
  if (!wordlen) {
    quoteChar[0] = '"';
  }
  for (cptr = word; *cptr; cptr++) {
    if (*cptr == '\\' && *(cptr + 1)) {
      cptr++;  // skip over escapes blindly
    } else if ((*cptr == ' ') && (quoteChar[0] == '\0')) {
      // if we found a space we need quotes, select double unless we've already selected something
      quoteChar[0] = '"';
    } else if (*cptr == '"') {
      // if our first unescaped quote is a double, then we wrap the string in single quotes
      quoteChar[0] = '\'';
      break;
    } else if (*cptr == '\'') {
      // if our first unescaped quote is a single, then we wrap the string in double quotes
      quoteChar[0] = '"';
      break;
    }
  }

  // Allocate enough space to hold the old string, a space, possible quote, the new string,
  // another possible quote, and the final null terminator).

  if ((tptr = (char *)realloc(cmdline, oldlen + 1 + 1 + wordlen + 1 + 1))) {
    strcat(tptr, " ");
    strcat(tptr, quoteChar);
    strcat(tptr, word);
    strcat(tptr, quoteChar);
  }
  return tptr;
}

// Any time we set or unset a buildmode setting, we need to regerate the 'help' menu for the unset command
void cli_int_buildmode_reset_unset_help(struct cli_def *cli) {
  struct cli_command *cmd;

  // find the buildmode unset command
  for (cmd = cli->commands; cmd; cmd = cmd->next) {
    if ((cmd->command_type == CLI_BUILDMODE_COMMAND) && !strcmp(cmd->command, "unset")) break;
  }

  if (cmd) {
    struct cli_optarg *optarg;
    for (optarg = cmd->optargs; optarg && strcmp(optarg->name, "setting"); optarg = optarg->next)
      ;

    if (optarg) {
      char *endOfMainHelp;
      struct cli_optarg_pair *optarg_pair;
      /*
       * This will ensure that any previously added help is not propogated - this left over space will be freed by the
       * cli_optarg_addhelp() calls a few lines down
       */
      if ((endOfMainHelp = strchr(optarg->help, '\v'))) *endOfMainHelp = '\0';

      for (optarg_pair = cli->found_optargs; optarg_pair; optarg_pair = optarg_pair->next) {
        // Only show vars that are also current 'commands'
        struct cli_command *c = cli->commands;
        for (; c; c = c->next) {
          if (c->command_type != CLI_BUILDMODE_COMMAND) continue;
          if (!strcmp(c->command, optarg_pair->name)) {
            char *tmphelp;
            if (asprintf(&tmphelp, "unset %s", optarg_pair->name) >= 0) {
              cli_optarg_addhelp(optarg, optarg_pair->name, tmphelp);
              free_z(tmphelp);
            }
          }
        }
      }
    }
  }
}

int cli_int_buildmode_cmd_cback(struct cli_def *cli, const char *command, char *argv[], int argc) {
  int rc = CLI_BUILDMODE_EXTEND;

  if (argc) {
    cli_error(cli, "Extra arguments on command line, command ignored.");
    rc = CLI_ERROR;
  }
  cli_int_buildmode_reset_unset_help(cli);
  return rc;
}

// A 'flag' callback has no optargs, so we need to set it ourself based on *this* command
int cli_int_buildmode_flag_cback(struct cli_def *cli, const char *command, char *argv[], int argc) {
  int rc = CLI_BUILDMODE_EXTEND;

  if (argc) {
    cli_error(cli, "Extra arguments on command line, command ignored.");
    rc = CLI_ERROR;
  }
  if (cli_set_optarg_value(cli, command, command, 0)) {
    cli_error(cli, "Problem setting value for optional flag %s", command);
    rc = CLI_ERROR;
  }
  cli_int_buildmode_reset_unset_help(cli);
  return rc;
}

// A 'flag' callback has no optargs, so we need to set it ourself based on *this* command
int cli_int_buildmode_flag_multiple_cback(struct cli_def *cli, const char *command, char *argv[], int argc) {
  int rc = CLI_BUILDMODE_EXTEND;

  if (argc) {
    cli_error(cli, "Extra arguments on command line, command ignored.");
    rc = CLI_ERROR;
  }
  if (cli_set_optarg_value(cli, command, command, CLI_CMD_OPTION_MULTIPLE)) {
    cli_error(cli, "Problem setting value for optional flag %s", command);
    rc = CLI_ERROR;
  }

  cli_int_buildmode_reset_unset_help(cli);
  return rc;
}

int cli_int_buildmode_cancel_cback(struct cli_def *cli, const char *command, char *argv[], int argc) {
  int rc = CLI_BUILDMODE_CANCEL;

  if (argc > 0) {
    cli_error(cli, "Extra arguments on command line, command ignored.");
    rc = CLI_ERROR;
  }
  return rc;
}

int cli_int_buildmode_execute_cback(struct cli_def *cli, const char *command, char *argv[], int argc) {
  int rc = CLI_BUILDMODE_EXIT;

  if (argc > 0) {
    cli_error(cli, "Extra arguments on command line, command ignored.");
    rc = CLI_ERROR;
  }
  return rc;
}

int cli_int_buildmode_show_cback(struct cli_def *cli, const char *command, char *argv[], int argc) {
  struct cli_optarg_pair *optarg_pair;

  for (optarg_pair = cli->found_optargs; optarg_pair; optarg_pair = optarg_pair->next) {
    // Only show vars that are also current 'commands'
    struct cli_command *c = cli->commands;
    for (; c; c = c->next) {
      if (c->command_type != CLI_BUILDMODE_COMMAND) continue;
      if (!strcmp(c->command, optarg_pair->name)) {
        cli_print(cli, "  %-20s = %s", optarg_pair->name, optarg_pair->value);
        break;
      }
    }
  }
  return CLI_OK;
}

int cli_int_buildmode_unset_cback(struct cli_def *cli, const char *command, char *argv[], int argc) {
  // Iterate over our 'set' variables to see if that variable is also a 'valid' command right now
  struct cli_command *c;

  // have to catch this one here due to how buildmode works
  if (!argv[0] || !*argv[0]) {
    cli_error(cli, "Incomplete command, missing required argument 'setting' for command  'unset'");
    return CLI_ERROR;
  }
  // Is this 'optarg' to remove one of the current commands?
  for (c = cli->commands; c; c = c->next) {
    if (c->command_type != CLI_BUILDMODE_COMMAND) continue;
    if (cli->privilege < c->privilege) continue;
    if ((cli->buildmode->mode != c->mode) && (cli->buildmode->transient_mode != c->mode) && (c->mode != MODE_ANY))
      continue;
    if (strcmp(c->command, argv[0])) continue;
    // Go fry anything by this name

    cli_int_unset_optarg_value(cli, argv[0]);
    cli_int_buildmode_reset_unset_help(cli);
    break;
  }

  return CLI_OK;
}

// Generate a list of variables that *have* been set
int cli_int_buildmode_unset_completor(struct cli_def *cli, const char *name, const char *word,
                                      struct cli_comphelp *comphelp) {
  struct cli_optarg_pair *optarg_pair;

  for (optarg_pair = cli->found_optargs; optarg_pair; optarg_pair = optarg_pair->next) {
    // Only complete vars that could be set by current 'commands'
    struct cli_command *c = cli->commands;
    for (; c; c = c->next) {
      if (c->command_type != CLI_BUILDMODE_COMMAND) continue;
      if ((!strcmp(c->command, optarg_pair->name)) && (!word || !strncmp(word, optarg_pair->name, strlen(word)))) {
        cli_add_comphelp_entry(comphelp, optarg_pair->name);
      }
    }
  }
  return CLI_OK;
}

int cli_int_buildmode_unset_validator(struct cli_def *cli, const char *name, const char *value) {
  struct cli_optarg_pair *optarg_pair;

  if (!name || !*name) {
    cli_error(cli, "No setting given to unset");
    return CLI_ERROR;
  }
  for (optarg_pair = cli->found_optargs; optarg_pair; optarg_pair = optarg_pair->next) {
    // Only complete vars that could be set by current 'commands'
    struct cli_command *c = cli->commands;
    for (; c; c = c->next) {
      if (c->command_type != CLI_BUILDMODE_COMMAND) continue;
      if (!strcmp(c->command, optarg_pair->name) && value && !strcmp(optarg_pair->name, value)) {
        return CLI_OK;
      }
    }
  }
  return CLI_ERROR;
}

void cli_set_transient_mode(struct cli_def *cli, int transient_mode) {
  cli->transient_mode = transient_mode;
}

int cli_add_comphelp_entry(struct cli_comphelp *comphelp, const char *entry) {
  int retval = CLI_ERROR;
  if (comphelp && entry) {
    char *dupelement = strdup(entry);
    char **duparray = (char **)realloc((void *)comphelp->entries, sizeof(char *) * (comphelp->num_entries + 1));
    if (dupelement && duparray) {
      comphelp->entries = duparray;
      comphelp->entries[comphelp->num_entries++] = dupelement;
      retval = CLI_OK;
    } else {
      free_z(dupelement);
      free_z(duparray);
    }
  }
  return retval;
}

void cli_free_comphelp(struct cli_comphelp *comphelp) {
  if (comphelp) {
    int idx;

    for (idx = 0; idx < comphelp->num_entries; idx++) free_z(comphelp->entries[idx]);
    free_z(comphelp->entries);
  }
}

static int cli_int_locate_command(struct cli_def *cli, struct cli_command *commands, int command_type, int start_word,
                                  struct cli_pipeline_stage *stage) {
  struct cli_command *c, *again_config = NULL, *again_any = NULL;
  int c_words = stage->num_words;

  for (c = commands; c; c = c->next) {
    if (c->command_type != command_type) continue;
    if (cli->privilege < c->privilege) continue;

    if (strncasecmp(c->command, stage->words[start_word], c->unique_len)) continue;
    if (strncasecmp(c->command, stage->words[start_word], strlen(stage->words[start_word]))) continue;

  AGAIN:
    if (c->mode == cli->mode || (c->mode == MODE_ANY && again_any != NULL)) {
      int rc = CLI_OK;

      // Found a word!
      if (!c->children) {
        // Last word
        if (!c->callback && !c->filter) {
          cli_error(cli, "No callback for \"%s\"", cli_command_name(cli, c));
          return CLI_ERROR;
        }
      } else {
        if (start_word == c_words - 1) {
          if (c->callback) goto CORRECT_CHECKS;

          cli_error(cli, "Incomplete command");
          return CLI_ERROR;
        }
        rc = cli_int_locate_command(cli, c->children, command_type, start_word + 1, stage);
        if (rc == CLI_ERROR_ARG) {
          if (c->callback) {
            rc = CLI_OK;
            goto CORRECT_CHECKS;
          }
          // show the command from word 0 up until the 'bad' word at start_word+1
          cli_error(cli, "Invalid command \"%s %s\"", cli_command_name(cli, c), stage->words[start_word + 1]);
          return CLI_ERROR;
        }
        return rc;
      }

      if (!c->callback && !c->filter) {
        cli_error(cli, "Internal server error processing \"%s\"", cli_command_name(cli, c));
        return CLI_ERROR;
      }

    CORRECT_CHECKS:

      if (rc == CLI_OK) {
        stage->command = c;
        stage->first_unmatched = start_word + 1;
        stage->first_optarg = stage->first_unmatched;
        // cli_int_parse_optargs will display any detected errors...
        cli_int_parse_optargs(cli, stage, c, '\0', NULL);
        rc = stage->status;
      }
      return rc;
    } else if (cli->mode > MODE_CONFIG && c->mode == MODE_CONFIG) {
      // Command matched but from another mode, remember it if we fail to find correct command
      again_config = c;
    } else if (c->mode == MODE_ANY) {
      // Command matched but for any mode, remember it if we fail to find correct command
      again_any = c;
    }
  }

  // Drop out of config submode if we have matched command on MODE_CONFIG
  if (again_config) {
    c = again_config;
    cli_set_configmode(cli, MODE_CONFIG, NULL);
    goto AGAIN;
  }
  if (again_any) {
    c = again_any;
    goto AGAIN;
  }

  // display this if we matched against absolutely nothing....
  if (start_word == 0) cli_error(cli, "Invalid command \"%s\"", stage->words[start_word]);

  return CLI_ERROR_ARG;
}

int cli_int_validate_pipeline(struct cli_def *cli, struct cli_pipeline *pipeline) {
  int i;
  int rc = CLI_OK;
  int command_type;

  if (!pipeline) return CLI_ERROR;
  cli->pipeline = pipeline;

  cli->found_optargs = NULL;

  // If the line is totally empty this is not an error, but we need to return
  // CLI_ERROR to avoid processing it
  if (pipeline->num_words == 0) return CLI_ERROR;

  for (i = 0; i < pipeline->num_stages; i++) {
    // And double check each stage for an empty line - this *is* an error
    if (pipeline->stage[i].num_words == 0) {
      cli_error(cli, "Empty command given");
      return CLI_ERROR;
    }

    // In 'buildmode' we only have one pipeline, but we need to recall if we had started with any optargs
    if (cli->buildmode && i == 0)
      command_type = CLI_BUILDMODE_COMMAND;
    else if (i > 0)
      command_type = CLI_FILTER_COMMAND;
    else
      command_type = CLI_REGULAR_COMMAND;

    cli->pipeline->current_stage = &pipeline->stage[i];
    if (cli->buildmode)
      cli->found_optargs = cli->buildmode->found_optargs;
    else
      cli->found_optargs = NULL;
    rc = cli_int_locate_command(cli, cli->commands, command_type, 0, &pipeline->stage[i]);

    // And save our found optargs for later use
    if (cli->buildmode)
      cli->buildmode->found_optargs = cli->found_optargs;
    else
      pipeline->stage[i].found_optargs = cli->found_optargs;

    if (rc != CLI_OK) break;
  }
  cli->pipeline = NULL;

  return rc;
}

void cli_int_free_pipeline(struct cli_pipeline *pipeline) {
  int i;
  if (!pipeline) return;
  for (i = 0; i < pipeline->num_stages; i++) cli_int_free_found_optargs(&pipeline->stage[i].found_optargs);
  for (i = 0; i < pipeline->num_words; i++) free_z(pipeline->words[i]);
  free_z(pipeline->cmdline);
  free_z(pipeline);
}

void cli_int_show_pipeline(struct cli_def *cli, struct cli_pipeline *pipeline) {
  int i, j;
  struct cli_pipeline_stage *stage;
  char **word;
  struct cli_optarg_pair *optarg_pair;

  for (i = 0, word = pipeline->words; i < pipeline->num_words; i++, word++) printf("[%s] ", *word);
  fprintf(stderr, "\n");
  fprintf(stderr, "#stages=%d, #words=%d\n", pipeline->num_stages, pipeline->num_words);

  for (i = 0; i < pipeline->num_stages; i++) {
    stage = &(pipeline->stage[i]);
    fprintf(stderr, "  #%d(%d words) first_unmatched=%d: ", i, stage->num_words, stage->first_unmatched);
    for (j = 0; j < stage->num_words; j++) {
      fprintf(stderr, " [%s]", stage->words[j]);
    }
    fprintf(stderr, "\n");

    if (stage->command) {
      fprintf(stderr, "  Command: %s\n", stage->command->command);
    }
    for (optarg_pair = stage->found_optargs; optarg_pair; optarg_pair = optarg_pair->next) {
      fprintf(stderr, "    %s: %s\n", optarg_pair->name, optarg_pair->value);
    }
  }
}

// Take an array of words and return a pipeline, using '|' to split command into different 'stages'.
// Pipeline is broken down by '|' characters and within each p.
struct cli_pipeline *cli_int_generate_pipeline(struct cli_def *cli, const char *command) {
  int i;
  struct cli_pipeline_stage *stage;
  char **word;
  struct cli_pipeline *pipeline = NULL;

  cli->found_optargs = NULL;
  if (cli->buildmode) cli->found_optargs = cli->buildmode->found_optargs;
  if (!command) return NULL;
  while (*command && isspace(*command)) command++;

  if (!(pipeline = (struct cli_pipeline *)calloc(1, sizeof(struct cli_pipeline)))) return NULL;
  pipeline->cmdline = (char *)strdup(command);

  pipeline->num_words = cli_parse_line(command, pipeline->words, CLI_MAX_LINE_WORDS);

  pipeline->stage[0].num_words = 0;
  stage = &pipeline->stage[0];
  word = pipeline->words;
  stage->words = word;
  for (i = 0; i < pipeline->num_words; i++, word++) {
    if (*word[0] == '|') {
      if (cli->buildmode) {
        // Can't allow filters in buildmode commands
        cli_int_free_pipeline(pipeline);
        cli_error(cli, "\nPipelines are not allowed in buildmode");
        return NULL;
      }
      stage->stage_num = pipeline->num_stages;
      stage++;
      stage->num_words = 0;
      pipeline->num_stages++;
      stage->words = word + 1;  // First word of the next stage is one past where we are (possibly NULL)
    } else {
      stage->num_words++;
    }
  }
  stage->stage_num = pipeline->num_stages;
  pipeline->num_stages++;
  return pipeline;
}

int cli_int_execute_pipeline(struct cli_def *cli, struct cli_pipeline *pipeline) {
  int stage_num;
  int rc = CLI_OK;
  struct cli_filter **filt = &cli->filters;

  if (!pipeline | !cli) return CLI_ERROR;

  cli->pipeline = pipeline;
  for (stage_num = 1; stage_num < pipeline->num_stages; stage_num++) {
    struct cli_pipeline_stage *stage = &pipeline->stage[stage_num];
    pipeline->current_stage = stage;
    cli->found_optargs = stage->found_optargs;
    *filt = calloc(1, sizeof(struct cli_filter));
    if (*filt) {
      if ((rc = stage->command->init(cli, stage->num_words, stage->words, *filt) != CLI_OK)) {
        break;
      }
      filt = &(*filt)->next;
    }
  }
  pipeline->current_stage = NULL;

  // Did everything init?  If so, execute, otherwise skip execution
  if ((rc == CLI_OK) && pipeline->stage[0].command->callback) {
    struct cli_pipeline_stage *stage = &pipeline->stage[0];

    pipeline->current_stage = &pipeline->stage[0];
    if (pipeline->current_stage->command->command_type == CLI_BUILDMODE_COMMAND)
      cli->found_optargs = cli->buildmode->found_optargs;
    else
      cli->found_optargs = pipeline->stage[0].found_optargs;
    rc = stage->command->callback(cli, cli_command_name(cli, stage->command), stage->words + stage->first_unmatched,
                                  stage->num_words - stage->first_unmatched);
    if (pipeline->current_stage->command->command_type == CLI_BUILDMODE_COMMAND)
      cli->buildmode->found_optargs = cli->found_optargs;
    pipeline->current_stage = NULL;
  }

  // Now teardown any filters
  while (cli->filters) {
    struct cli_filter *filt = cli->filters;
    if (filt->filter) filt->filter(cli, NULL, cli->filters->data);
    cli->filters = filt->next;
    free_z(filt);
  }
  cli->found_optargs = NULL;
  cli->pipeline = NULL;
  return rc;
}

/*
 *  Attempt quick dirty wrapping of helptext taking into account the offset from name, embedded
 *  cr/lf in helptext, and trying to split on last white-text before the right margin.  If there is
 *  no identifiable whitespace to split on, then the split will be done on the last character to fit
 *  that line (currently max line with is 80 characters).  
 *  The firstcolumn width will be a greater of 22 characters or the width of nameptr, which ever is 
 *  greater, and will be offset from the rest of the line by one space.  However, if nameptr is
 *  greater than 22 characters it will be put on a line by itself.  The first column will be formatted
 *  as spaces (22 of em) for all subsequent lines.
.
 *  This routine assumes any 'indenting' of the nameptr field has already been done, and is solely
 *  concerned about wrapping the combination of nameptr and helpptr to look 'nice'.  
 */
 
#define MAX(a,b) ((a) >(b) ? (a) : (b))
#define MAXWIDTHCOL1 22

void cli_int_wrap_help_line(char *nameptr, char *helpptr, struct cli_comphelp *comphelp) {
  int maxwidth = 80;  // temporary assumption, to be fixed later when libcli 'understands' screen dimensions
  int availwidth;
  int namewidth;
  int toprint;
  char *crlf;
  char *line;
  char emptystring[] = "";

  if (!helpptr) helpptr = emptystring;
  /*
   * Now we need to iterate one or more times to only print out at most
   * maxwidth - leftwidth characters of helpptr.  Note that there are no
   * tabs in helpptr, so each 'char' displays as one char
   */

  do {
    if ((nameptr != emptystring) && (strlen(nameptr) > MAXWIDTHCOL1)) {
      if (asprintf(&line, "%s", nameptr) < 0) break;
      cli_add_comphelp_entry(comphelp, line);
      free_z(line);
      nameptr = emptystring;
      namewidth = MAXWIDTHCOL1;
    }
    namewidth = MAX(MAXWIDTHCOL1,strlen(nameptr));
    availwidth = maxwidth - namewidth -1; // subtract 1 for space separating col1 from rest of line
    toprint = strlen(helpptr);
    if (toprint > availwidth) {
      toprint = availwidth;
      while ((toprint >= 0) && !isspace(helpptr[toprint])) toprint--;
      if (toprint < 0) {
        // if we backed up and found no whitespace, dump as much as we can
        toprint = availwidth;
      }
    }  // see if we might have an embedded carriage return or line feed
    if ((crlf = strpbrk(helpptr, "\n\r"))) {
      // crlf is a pointer - see if it is 'before' the toprint index
      if ((crlf - helpptr) < toprint) {
        // ok, crlf is before the wrap, so have line break here.
        toprint = (crlf - helpptr);
      }
    }

    if (asprintf(&line, "%-*.*s %.*s", namewidth, namewidth, nameptr, toprint, helpptr) < 0) break;
    cli_add_comphelp_entry(comphelp, line);
    free_z(line);

    nameptr = emptystring;
    helpptr += toprint;
    // regardless of how long the command is, indent by 20 chars on all following lines
    namewidth = 22;
    // advance to first non whitespace
    while (helpptr && isspace(*helpptr)) helpptr++;
  } while (*helpptr);
}

static void cli_get_optarg_comphelp(struct cli_def *cli, struct cli_optarg *optarg, struct cli_comphelp *comphelp,
                                    int num_candidates, const char lastchar, const char *anchor_word,
                                    const char *next_word) {
  int help_insert = 0;
  char *delim_start = DELIM_NONE;
  char *delim_end = DELIM_NONE;
  int (*get_completions)(struct cli_def *, const char *, const char *, struct cli_comphelp *) = NULL;
  char *tptr = NULL;

  // If we've already seen a value by this exact name, skip it, unless the multiple flag is set
  if (cli_find_optarg_value(cli, optarg->name, NULL) && !(optarg->flags & (CLI_CMD_OPTION_MULTIPLE))) return;

  get_completions = optarg->get_completions;
  if (optarg->flags & CLI_CMD_OPTIONAL_FLAG) {
    if (!(anchor_word && !strncmp(anchor_word, optarg->name, strlen(anchor_word)))) {
      delim_start = DELIM_OPT_START;
      delim_end = DELIM_OPT_END;
      get_completions = NULL;  // No point, completor of field is the name itself
    }
  } else if (optarg->flags & CLI_CMD_HYPHENATED_OPTION) {
    delim_start = DELIM_OPT_START;
    delim_end = DELIM_OPT_END;
  } else if (optarg->flags & CLI_CMD_ARGUMENT) {
    delim_start = DELIM_ARG_START;
    delim_end = DELIM_ARG_END;
  } else if (optarg->flags & CLI_CMD_OPTIONAL_ARGUMENT) {
    /*
     * Optional args can match against the name or the value.
     * Here 'anchor_word' is the name, and 'next_word' is 'value' for said optional argument.
     * So if anchor_word==next_word we're looking at the 'name' of the optarg, otherwise we know the name and are going
     * against the value.
     */
    if (anchor_word != next_word) {
      // Matching against optional argument 'value'
      help_insert = 0;
      if (!get_completions) {
        delim_start = DELIM_ARG_START;
        delim_end = DELIM_ARG_END;
      }
    } else {
      // Matching against optional argument 'name'
      help_insert = 1;
      get_completions = NULL;  // Matching against the name, not the following field value
      if (!(anchor_word && !strncmp(anchor_word, optarg->name, strlen(anchor_word)))) {
        delim_start = DELIM_OPT_START;
        delim_end = DELIM_OPT_END;
      }
    }
  }

  // Fill in with help text or completor value(s) as indicated
  if (lastchar == '?') {
    /*
     *  Note - help is a bit complex, and we could optimize it.  But it isn't done often,
     *  so we're always going to do it on the fly.
     *  Help will consist of '\v' separated lines.  Each line except the first is also '\t'
     *  separated into the name/text fields.  If a line does not have a '\t' separated then the
     *  name will be the name of the optarg, and the help will be that entire line.  The *first*
     *  does get some tweaks to how the name and help is displayed.
     *  The first pass through will be indented 2 spaces on the left with the formated name occupying
     *  20 spaces (expanding if more than 20).  If the command is a 'buildmode' command the first
     *  character of the 'text' will be an asterisk.  The 'rest' of the line (assuming an 80 character '
     *  wide line for now) will be used to wrap the 'text' field honoring embedded newlines, and trying to
     *  wrap on nearest preceeding whitespace when it hits a boundary.  Subsequent lines will be indented
     *  by an additional 2 spaces, and will drop the asterisk.
     */
    char *working = NULL;
    char *nameptr = NULL;
    char *helpptr = NULL;
    char *lineptr = NULL;
    char *savelineptr = NULL;
    char *savetabptr = NULL;
    char *tname = NULL;
    int indent = 2;
    int helplen;
    char emptystring[] = "";

    /*
     * Print out actual text into a working buffer that we can then call 'strtok_r' on it.  This lets
     * us prepend some optional fields nice and easily.  At this point it is one big string, so we can
     * iterate over it making changes (strtok_r) as needed.
     */
    if (help_insert) {
      helplen = asprintf(&working, "%s%s%s%s%s", (optarg->flags & CLI_CMD_ALLOW_BUILDMODE) ? "* " : "", "type '",
                         optarg->name, "' to select ", optarg->name);
    } else {
      helplen = asprintf(&working, "%s%s", (optarg->flags & CLI_CMD_ALLOW_BUILDMODE) ? "* " : "", optarg->help);
    }

    // pull the first line
    helpptr = strtok_r(working, "\v", &savelineptr);
    nameptr = optarg->name;

    if (helplen < 0) {
      helpptr = emptystring;
      working = NULL;
    }

    // break things up into tab separated entities - always show the first entry
    do {
      char *leftcolumn;
      if (asprintf(&tname, "%s%s%s", delim_start, nameptr, delim_end) == -1) break;
      if (asprintf(&leftcolumn, "%*.*s%s", indent, indent, "", tname) == -1) break;

      cli_int_wrap_help_line(leftcolumn, helpptr, comphelp);

      // clear out any delimiter settings and set indent for any subtext
      delim_start = DELIM_NONE;
      delim_end = DELIM_NONE;
      indent = 4;
      free_z(tname);
      free_z(leftcolumn);

      // we may not need to show all off the 'extra help', so loop here
      do {
        lineptr = strtok_r(NULL, "\v", &savelineptr);
        if (lineptr) {
          nameptr = strtok_r(lineptr, "\t", &savetabptr);
          helpptr = strtok_r(NULL, "\t", &savetabptr);
        }
      } while (lineptr && nameptr && helpptr && (next_word && (strncmp(next_word, nameptr, strlen(next_word)))));
    } while (lineptr && nameptr && helpptr);
    free_z(working);
  } else if (lastchar == CTRL('I')) {
    if (get_completions) {
      (*get_completions)(cli, optarg->name, next_word, comphelp);
    } else if ((!anchor_word || !strncmp(anchor_word, optarg->name, strlen(anchor_word))) &&
               (asprintf(&tptr, "%s%s%s", delim_start, optarg->name, delim_end) != -1)) {
      cli_add_comphelp_entry(comphelp, tptr);
      free_z(tptr);
    }
  }
}

static void cli_int_parse_optargs(struct cli_def *cli, struct cli_pipeline_stage *stage, struct cli_command *cmd,
                                  char lastchar, struct cli_comphelp *comphelp) {
  struct cli_optarg *optarg = NULL, *oaptr = NULL;
  int word_idx, value_idx, word_incr, candidate_idx;
  struct cli_optarg *candidates[CLI_MAX_LINE_WORDS];
  char *value;
  int num_candidates = 0;
  int is_last_word = 0;
  int (*validator)(struct cli_def *, const char *name, const char *value);

  if (cli->buildmode)
    cli->found_optargs = cli->buildmode->found_optargs;
  else
    cli->found_optargs = stage->found_optargs;
  /*
   * Tab completion and help are *only* allowed at end of string, but we need to process the entire command to know what
   * has already been found.  There should be no ambiguities before the 'last' word.
   * Note specifically that for tab completions and help the *last* word can be a null pointer.
   */
  stage->error_word = NULL;

  /* Start our optarg and word pointers at the beginning.
   * optarg will be incremented *only* when an argument is identified.
   * word_idx will be incremented either by 1 (optflag or argument) or 2 (optional argument).
   */
  word_idx = stage->first_unmatched;
  optarg = cmd->optargs;
  num_candidates = 0;
  while (optarg && word_idx < stage->num_words && num_candidates <= 1) {
    num_candidates = 0;
    word_incr = 1;  // Assume we're only incrementing by a word - if we match an optional argument bump to 2

    /*
     * The initial loop here is to identify candidates based matching *this* word in order against:
     * - An exact match of the word to the optinal flag/argument name (yield exactly one match and exit the loop)
     * - A partial match for optional flag/argument name
     * - Candidate an argument.
     */

    for (oaptr = optarg; oaptr; oaptr = oaptr->next) {
      // Skip this option unless it matches privileges, MODE_ANY, the current mode, or the transient_mode
      if (cli->privilege < oaptr->privilege) continue;
      if ((oaptr->mode != cli->mode) && (oaptr->mode != cli->transient_mode) && (oaptr->mode != MODE_ANY)) continue;

      /*
       * Special cases:
       * - spot check
       * - a hyphenated option a hyphenated option
       * - an optional flag without validator, but the word matches the optarg name
       * - an optional flag with a validator *and* the word passes the validator,
       * - an optional argument where the word matches the argument name
       * a hit on any of these special cases is an automatic *only* candidate.
       *
       * Otherwise if the word is 'blank', could be an argument, or matches 'enough' of an option/flag it is a
       * candidate.
       * Once we accept an argument as a candidate, we're done looking for candidates as straight arguments are
       * required.
       */
      if (oaptr->flags & CLI_CMD_SPOT_CHECK && num_candidates == 0) {
        stage->status = (*oaptr->validator)(cli, NULL, NULL);
        if (stage->status != CLI_OK) {
          stage->error_word = stage->words[word_idx];
          cli_reprompt(cli);
          goto done;
        }
      } else if (stage->words[word_idx] && stage->words[word_idx][0] == '-' &&
                 (oaptr->flags & (CLI_CMD_HYPHENATED_OPTION))) {
        candidates[0] = oaptr;
        num_candidates = 1;
        break;
      } else if (stage->words[word_idx] && (oaptr->flags & CLI_CMD_OPTIONAL_FLAG) &&
                 ((oaptr->validator && (oaptr->validator(cli, oaptr->name, stage->words[word_idx]) == CLI_OK)) ||
                  (!oaptr->validator && !strcmp(oaptr->name, stage->words[word_idx])))) {
        candidates[0] = oaptr;
        num_candidates = 1;
        break;
      } else if (stage->words[word_idx] && (oaptr->flags & CLI_CMD_OPTIONAL_ARGUMENT) &&
                 !strcmp(oaptr->name, stage->words[word_idx])) {
        candidates[0] = oaptr;
        num_candidates = 1;
        break;
      } else if (!stage->words[word_idx] || (oaptr->flags & CLI_CMD_ARGUMENT) ||
                 !strncasecmp(oaptr->name, stage->words[word_idx], strlen(stage->words[word_idx]))) {
        candidates[num_candidates++] = oaptr;
      }
      if (oaptr->flags & CLI_CMD_ARGUMENT) {
        break;
      }
    }

    /*
     * Iterate over the list of candidates for this word.  There are several early exit cases to consider:
     * - If we have no candidates then we're done - any remaining words must be processed by the command callback
     * - If we have more than one candidate evaluating for execution punt hard after complaining.
     * - If we have more than one candidate and we're not at end-of-line (
     */
    if (num_candidates == 0) break;
    if (num_candidates > 1 && (lastchar == '\0' || word_idx < (stage->num_words - 1))) {
      stage->error_word = stage->words[word_idx];
      stage->status = CLI_AMBIGUOUS;
      cli_error(cli, "\nAmbiguous option/argument for command %s", stage->command->command);
      goto done;
    }

    /*
     * So now we could have one or more candidates.  We need to call get help/completions *only* if this is the
     * 'last-word'.
     * Remember that last word for optional arguments is last or next to last....
     */
    if (lastchar != '\0') {
      int called_comphelp = 0;
      for (candidate_idx = 0; candidate_idx < num_candidates; candidate_idx++) {
        oaptr = candidates[candidate_idx];

        // Need to know *which* word we're trying to complete for optional_args, hence the difference calls
        if (((oaptr->flags & (CLI_CMD_OPTIONAL_FLAG | CLI_CMD_ARGUMENT)) && (word_idx == (stage->num_words - 1))) ||
            (oaptr->flags & (CLI_CMD_OPTIONAL_ARGUMENT | CLI_CMD_HYPHENATED_OPTION) &&
             word_idx == (stage->num_words - 1))) {
          cli_get_optarg_comphelp(cli, oaptr, comphelp, num_candidates, lastchar, stage->words[word_idx],
                                  stage->words[word_idx]);
          called_comphelp = 1;
        } else if (oaptr->flags & CLI_CMD_OPTIONAL_ARGUMENT && word_idx == (stage->num_words - 2)) {
          cli_get_optarg_comphelp(cli, oaptr, comphelp, num_candidates, lastchar, stage->words[word_idx],
                                  stage->words[word_idx + 1]);
          called_comphelp = 1;
        }
      }
      // If we were 'end-of-word' and looked for completions/help, return to user
      if (called_comphelp) {
        stage->status = CLI_OK;
        goto done;
      }
    }

    // Set some values for use later - makes code much easier to read
    value = stage->words[word_idx];
    value_idx = word_idx;
    oaptr = candidates[0];
    validator = oaptr->validator;
    if ((oaptr->flags & (CLI_CMD_OPTIONAL_FLAG | CLI_CMD_ARGUMENT) && word_idx == (stage->num_words - 1)) ||
        (oaptr->flags & CLI_CMD_OPTIONAL_ARGUMENT && word_idx == (stage->num_words - 2))) {
      is_last_word = 1;
    }

    if (oaptr->flags & CLI_CMD_OPTIONAL_ARGUMENT) {
      word_incr = 2;
      if (!stage->words[word_idx + 1] && lastchar == '\0') {
        // Hit an optional argument that does not have a value with it
        cli_error(cli, "Optional argument %s requires a value", stage->words[word_idx]);
        stage->error_word = stage->words[word_idx];
        stage->status = CLI_MISSING_VALUE;
        goto done;
      }
      value = stage->words[word_idx + 1];
      value_idx = word_idx + 1;
    }

    /*
     * We're not at end of string and doing help/completions.
     * So see if our value is 'valid', to save it, and see if we have any extra processing to do such as a transient
     * mode check or enter build mode.
     */

    if (!validator || (*validator)(cli, oaptr->name, value) == CLI_OK) {
      if (oaptr->flags & CLI_CMD_DO_NOT_RECORD) {
        // We want completion and validation, but then leave this 'value' to be seen - used *only* by buildmode as
        // argv[0] with argc=1
        break;
      } else {
        // Need to combine remaining words if the CLI_CMD_REMAINDER_OF_LINE flag it set, then we're done processing
        int set_value_return = 0;

        if (oaptr->flags & CLI_CMD_REMAINDER_OF_LINE) {
          char *combined = NULL;
          combined = join_words(stage->num_words - word_idx, stage->words + word_idx);
          if (!combined) {
            cli_error(cli, "%sUnable to allocate memory for command processing", lastchar == '\0' ? "" : "\n");
            cli_reprompt(cli);
            stage->error_word = stage->words[word_idx];
            stage->status = CLI_ERROR;
            goto done;
          }
          set_value_return = cli_set_optarg_value(cli, oaptr->name, combined, 0);
          free_z(combined);
        } else {
          set_value_return = cli_set_optarg_value(cli, oaptr->name, value, oaptr->flags & CLI_CMD_OPTION_MULTIPLE);
        }

        if (set_value_return != CLI_OK) {
          cli_error(cli, "%sProblem setting value for command argument %s", lastchar == '\0' ? "" : "\n",
                    stage->words[word_idx]);
          cli_reprompt(cli);
          stage->error_word = stage->words[word_idx];
          stage->status = CLI_ERROR;
          goto done;
        }
      }
    } else {
      cli_error(cli, "%sProblem parsing command setting %s with value %s", lastchar == '\0' ? "" : "\n", oaptr->name,
                stage->words[value_idx]);
      cli_reprompt(cli);
      stage->error_word = stage->words[word_idx];
      stage->status = CLI_ERROR;
      goto done;
    }

    // If this optarg can set the transient mode, then evaluate it if we're not at last word
    if (oaptr->transient_mode && oaptr->transient_mode(cli, oaptr->name, value)) {
      stage->error_word = stage->words[word_idx];
      stage->status = CLI_ERROR;
      goto done;
    }

    // Only process CLI_CMD_ALLOW_BUILDMODE if we're not already in buildmode, parsing command (stage 0), and this is
    // the last word
    if (!cli->disallow_buildmode && (stage->status == CLI_OK) && (oaptr->flags & CLI_CMD_ALLOW_BUILDMODE) &&
        is_last_word) {
      stage->status = cli_int_enter_buildmode(cli, stage, value);
      goto done;
    }

    // Optional flags and arguments can appear multiple times, and in any order.  We only advance
    // from our starting optarg if the matching optarg is a true argument.
    if (oaptr->flags & CLI_CMD_ARGUMENT) {
      // Advance past this argument entry
      optarg = oaptr->next;
    }

    word_idx += word_incr;
    stage->first_unmatched = word_idx;
  }

  // If we're evaluating the command for execution, ensure we have all required arguments.
  if (lastchar == '\0') {
    for (; optarg; optarg = optarg->next) {
      if (cli->privilege < optarg->privilege) continue;
      if ((optarg->mode != cli->mode) && (optarg->mode != cli->transient_mode) && (optarg->mode != MODE_ANY)) continue;
      if (optarg->flags & CLI_CMD_DO_NOT_RECORD) continue;
      if (optarg->flags & CLI_CMD_ARGUMENT) {
        cli_error(cli, "Incomplete command, missing required argument '%s' for command '%s'", optarg->name,
                  cmd->command);
        stage->status = CLI_MISSING_ARGUMENT;
        goto done;
      }
    }
  }

done:
  if (cli->buildmode)
    cli->buildmode->found_optargs = cli->found_optargs;
  else
    stage->found_optargs = cli->found_optargs;
  return;
}

void cli_unregister_all_commands(struct cli_def *cli) {
  cli_unregister_tree(cli, cli->commands, CLI_REGULAR_COMMAND);
}

void cli_unregister_all_filters(struct cli_def *cli) {
  cli_unregister_tree(cli, cli->commands, CLI_FILTER_COMMAND);
}

/*
 * Several routines were declared as internal, but would be useful for external use also
 * Rename them so they can be exposed, but have original routines simply call the 'public' ones
 */

int cli_int_quit(struct cli_def *cli, UNUSED(const char *command), UNUSED(char *argv[]), UNUSED(int argc)) {
  return cli_quit(cli, command, argv, argc);
}

int cli_int_help(struct cli_def *cli, UNUSED(const char *command), UNUSED(char *argv[]), UNUSED(int argc)) {
  return cli_help(cli, command, argv, argc);
}

int cli_int_history(struct cli_def *cli, UNUSED(const char *command), UNUSED(char *argv[]), UNUSED(int argc)) {
  return cli_history(cli, command, argv, argc);
}

int cli_int_exit(struct cli_def *cli, const char *command, char *argv[], int argc) {
  return cli_exit(cli, command, argv, argc);
}

int cli_int_enable(struct cli_def *cli, UNUSED(const char *command), UNUSED(char *argv[]), UNUSED(int argc)) {
  return cli_enable(cli, command, argv, argc);
}

int cli_int_disable(struct cli_def *cli, UNUSED(const char *command), UNUSED(char *argv[]), UNUSED(int argc)) {
  return cli_disable(cli, command, argv, argc);
}

void cli_dump_optargs_and_args(struct cli_def *cli, const char *text, char *argv[], int argc) {
  int i;
  struct cli_optarg_pair *optargs;
  cli_print(cli, "%s: mode = %d, transient_mode = %d", text, cli->mode, cli->transient_mode);
  cli_print(cli, "Identified optargs");
  for (optargs = cli_get_all_found_optargs(cli), i = 0; optargs; optargs = optargs->next, i++)
    cli_print(cli, "%2d  %s=%s", i, optargs->name, optargs->value);
  cli_print(cli, "Extra args");
  for (i = 0; i < argc; i++) cli_print(cli, "%2d %s", i, argv[i]);
}

static int cli_socket_wait(int sockfd, struct timeval *tm) {
#if defined(LIBCLI_USE_POLL) && !defined(WIN32)
  struct pollfd pfd = {
      .fd = sockfd,
      .events = POLLIN,
  };

  return poll(&pfd, 1, (tm->tv_sec * 1000) + (tm->tv_usec / 1000));
#else
  fd_set r;
  FD_ZERO(&r);
  FD_SET(sockfd, &r);
  return select(sockfd + 1, &r, NULL, NULL, tm);
#endif
}