File: netplay.cpp

package info (click to toggle)
warzone2100 4.6.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 660,320 kB
  • sloc: cpp: 676,209; ansic: 391,201; javascript: 78,238; python: 16,632; php: 4,294; sh: 4,094; makefile: 2,629; lisp: 1,492; cs: 489; xml: 404; perl: 224; ruby: 156; java: 89
file content (5679 lines) | stat: -rw-r--r-- 191,813 bytes parent folder | download
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
/*
	This file is part of Warzone 2100.
	Copyright (C) 1999-2004  Eidos Interactive
	Copyright (C) 2005-2024  Warzone 2100 Project

	Warzone 2100 is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	Warzone 2100 is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with Warzone 2100; if not, write to the Free Software
	Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
 * @file netplay.c
 *
 * Basic netcode.
 */

#include "lib/framework/frame.h"
#include "lib/framework/wzapp.h"
#include "lib/framework/string_ext.h"
#include "lib/framework/crc.h"
#include "lib/framework/file.h"
#include "lib/gamelib/gtime.h"
#include "lib/exceptionhandler/dumpinfo.h"
#include "src/console.h"
#include "src/component.h"		// FIXME: we need to handle this better
#include "src/modding.h"		// FIXME: we need to handle this better
#include "src/multilobbycommands.h"

#include <time.h>			// for stats
#include <physfs.h>
#include "lib/framework/physfs_ext.h"
#include <string.h>
#include <memory>
#include <thread>
#include <atomic>
#include <limits>
#include <sodium.h>
#include <chrono>

#include "netplay.h"
#include "netlog.h"
#include "netreplay.h"
#include "lib/netplay/byteorder_funcs_wrapper.h"
#include "lib/netplay/client_connection.h"
#include "lib/netplay/listen_socket.h"
#include "lib/netplay/connection_poll_group.h"
#include "lib/netplay/connection_provider_registry.h"
#include "lib/netplay/pending_writes_manager.h"
#include "lib/netplay/pending_writes_manager_map.h"
#include "netpermissions.h"
#include "sync_debug.h"
#include "port_mapping_manager.h"

#include "src/multistat.h"
#include "src/multijoin.h"
#include "src/multiint.h"
#include "src/multiplay.h"
#include "src/hci/quickchat.h"
#include "src/warzoneconfig.h"
#include "src/version.h"
#include "src/loadsave.h"
#include "src/activity.h"
#include "src/stdinreader.h"

#include <LRUCache11/LRUCache11.hpp>
#include <tl/expected.hpp>

#if defined (WZ_OS_MAC)
# include "lib/framework/cocoa_wrapper.h"
#endif

#ifndef WZ_OS_WIN
static const int SOCKET_ERROR = -1;
#else
# include <WinSock2.h> // SOCKET_ERROR
#endif

// WARNING !!! This is initialised via configuration.c !!!
char masterserver_name[255] = {'\0'};
static unsigned int masterserver_port = 0, gameserver_port = 0;
static bool bJoinPrefTryIPv6First = true;
static bool bDefaultHostFreeChatEnabled = true;
static bool bEnableTCPNoDelay = true;

// This is for command line argument override
// Disables port saving and reading from/to config
bool netGameserverPortOverride = false;

static std::shared_ptr<WzConnectionProvider> activeConnProvider = nullptr;

#define NET_TIMEOUT_DELAY	2500		// we wait this amount of time for socket activity
constexpr std::chrono::milliseconds NET_READ_TIMEOUT{ 0 };
/*
*	=== Using new socket code, this might not hold true any longer ===
*	NOTE /rant:  If the buffer size isn't big enough, it will invalidate the socket.
*	Which means that we need to allocate a buffer big enough to handle worst case
*	situations.
*	reference: MaxMsgSize in netplay.h  (currently set to 32K)
*
*/
constexpr size_t NET_BUFFER_SIZE = (MaxMsgSize * 8);	// Would be 256K

// ////////////////////////////////////////////////////////////////////////
// Function prototypes
static void NETplayerCloseSocket(UDWORD index, bool quietSocketClose);
static void NETplayerLeaving(UDWORD player, bool quietSocketClose = false);		// Cleanup sockets on player leaving (nicely)
static void NETplayerDropped(UDWORD player);		// Broadcast NET_PLAYER_DROPPED & cleanup
static void NETallowJoining();
static void NETfixPlayerCount();
static void NETclientHandleHostDisconnected();
/*
 * Network globals, these are part of the new network API
 */
SYNC_COUNTER sync_counter;		// keeps track on how well we are in sync
// ////////////////////////////////////////////////////////////////////////
// Types

struct Statistic
{
	size_t sent;
	size_t received;
};

struct NETSTATS  // data regarding the last one second or so.
{
	Statistic       rawBytes;               // Number of actual bytes, in about 1 sec.
	Statistic       uncompressedBytes;      // Number of bytes sent, before compression, in about 1 sec.
	Statistic       packets;                // Number of calls to writeAll, in about 1 sec.
};

struct NET_PLAYER_DATA
{
	uint16_t        size;
	void           *data;
	size_t          buffer_size;
};

#define SERVER_UPDATE_MIN_INTERVAL 7 * GAME_TICKS_PER_SEC
#define SERVER_UPDATE_MAX_INTERVAL 25 * GAME_TICKS_PER_SEC

class LobbyServerConnectionHandler
{
public:

	void ensureInitialized();
	bool connect();
	bool disconnect();
	void sendUpdate();
	void run();
	std::shared_ptr<WzConnectionProvider> connectionProvider() const { return connProvider; }

private:
	void sendUpdateNow();
	void sendKeepAlive();

	inline bool canSendServerUpdateNow()
	{
		return (currentState == LobbyConnectionState::Connected)
			&& (realTime - lastServerUpdate >= SERVER_UPDATE_MIN_INTERVAL);
	}

	inline bool shouldSendServerKeepAliveNow()
	{
		return (currentState == LobbyConnectionState::Connected)
			&& (realTime - lastServerUpdate >= SERVER_UPDATE_MAX_INTERVAL);
	}
private:
	enum class LobbyConnectionState
	{
		Disconnected,
		Connecting_WaitingForResponse,
		Connected
	};
	LobbyConnectionState currentState = LobbyConnectionState::Disconnected;
	IClientConnection* rs_socket = nullptr;
	IConnectionPollGroup* waitingForConnectionFinalize = nullptr;
	uint32_t lastConnectionTime = 0;
	uint32_t lastServerUpdate = 0;
	bool queuedServerUpdate = false;
	std::shared_ptr<WzConnectionProvider> connProvider = nullptr;
};

class PlayerManagementRecord
{
public:
	void clear()
	{
		identitiesMovedToSpectatorsByHost.clear();
		ipsMovedToSpectatorsByHost.clear();
	}
	// player to spectators
	void movedPlayerToSpectators(const std::string& ipAddress, const EcKey::Key& publicIdentity, bool byHost)
	{
		if (!byHost) { return; }
		ipsMovedToSpectatorsByHost.insert(ipAddress);
		identitiesMovedToSpectatorsByHost.insert(base64Encode(publicIdentity));
	}
	void movedPlayerToSpectators(const PLAYER& player, const EcKey::Key& publicIdentity, bool byHost)
	{
		if (!byHost) { return; }
		ipsMovedToSpectatorsByHost.insert(player.IPtextAddress);
		identitiesMovedToSpectatorsByHost.insert(base64Encode(publicIdentity));
	}
	// spectator to players
	void movedSpectatorToPlayers(const std::string& ipAddress, const EcKey::Key& publicIdentity, bool byHost)
	{
		if (!byHost) { return; }
		ipsMovedToSpectatorsByHost.erase(ipAddress);
		identitiesMovedToSpectatorsByHost.erase(base64Encode(publicIdentity));
	}
	void movedSpectatorToPlayers(const PLAYER& player, const EcKey::Key& publicIdentity, bool byHost)
	{
		if (!byHost) { return; }
		ipsMovedToSpectatorsByHost.erase(player.IPtextAddress);
		identitiesMovedToSpectatorsByHost.erase(base64Encode(publicIdentity));
	}
	bool hostMovedPlayerToSpectators(const std::string& ipAddress)
	{
		return ipsMovedToSpectatorsByHost.count(ipAddress) > 0;
	}
	bool hostMovedPlayerToSpectators(const EcKey::Key& publicIdentity)
	{
		return identitiesMovedToSpectatorsByHost.count(base64Encode(publicIdentity)) > 0;
	}
private:
	std::unordered_set<std::string> identitiesMovedToSpectatorsByHost;
	std::unordered_set<std::string> ipsMovedToSpectatorsByHost;
};

// ////////////////////////////////////////////////////////////////////////
// Variables

NETPLAY	NetPlay;
static bool allow_joining = false;
static bool server_not_there = false;
static bool lobby_disabled = false;
static std::string lobby_disabled_info_link_url;
static GAMESTRUCT	gamestruct;

static std::vector<WZFile> DownloadingWzFiles;

// update flags
bool netPlayersUpdated;

// Server-side socket (host-only) which is used to listen for client connections.
// There's also `rs_socket` held by `LobbyServerConnectionHandler`, which is used to communicate with the lobby server.
static IListenSocket* server_listen_socket = nullptr;

static IClientConnection* bsocket = nullptr;                  ///< Socket used to talk to the host (clients only). If bsocket != NULL, then client_transient_socket == NULL.
static optional<std::string> lastHostAddress = nullopt;
static IClientConnection* connected_bsocket[MAX_CONNECTED_PLAYERS] = { nullptr };  ///< Sockets used to talk to clients (host only).
// Client-side socket set. Contains of only 1 socket at most: `bsocket` (which is a stable client connection to the host).
static IConnectionPollGroup* client_socket_set = nullptr;
// Server-side socket set. Contains up to `MAX_CONNECTED_PLAYERS` sockets:
// `connected_bsocket[i]` - sockets used to communicate with clients during a game session.
static IConnectionPollGroup* server_socket_set = nullptr;

/**
 * Used for connections with clients.
 */
#define NET_PING_TMP_PING_CHALLENGE_SIZE 128

struct TmpSocketInfo
{
	std::string ip;
	std::chrono::steady_clock::time_point connectTime;
	char buffer[10] = {'\0'};
	size_t usedBuffer = 0;
	std::vector<uint8_t> connectChallenge;
	enum class TmpConnectState
	{
		None,
		PendingInitialConnect,
		PendingJoinRequest,
		PendingAsyncApproval,
		ProcessJoin
	};
	TmpConnectState connectState;

	struct ReceivedJoinInfo
	{
		// Information received from a join request - needed for later stages
		char name[64] = {'\0'};
		uint8_t playerType = 0;
		EcKey identity;
		std::unique_ptr<SessionKeys> connectionAuthSessionKeys;
		std::vector<uint8_t> challengeForHost;

		void reset()
		{
			name[0] = '\0';
			playerType = 0;
			identity.clear();
			connectionAuthSessionKeys.reset();
			challengeForHost.clear();
		}
	};
	ReceivedJoinInfo receivedJoinInfo;

	// async join approval
	std::string uniqueJoinID;
	optional<AsyncJoinApprovalAction> asyncJoinApprovalResult = nullopt;
	optional<uint8_t> asyncJoinApprovalExplicitPlayerIdx = nullopt;
	LOBBY_ERROR_TYPES asyncJoinRejectCode = ERROR_NOERROR;
	std::string asyncJoinRejectCustomMessage;

	void reset()
	{
		ip.clear();
		connectTime = std::chrono::steady_clock::time_point();
		memset(buffer, 0, sizeof(buffer));
		usedBuffer = 0;
		connectChallenge.clear();
		connectState = TmpConnectState::None;
		receivedJoinInfo.reset();
		uniqueJoinID.clear();
		asyncJoinApprovalResult = nullopt;
		asyncJoinApprovalExplicitPlayerIdx = nullopt;
		asyncJoinRejectCode = ERROR_NOERROR;
		asyncJoinRejectCustomMessage.clear();
	}
};

static IClientConnection* tmp_socket[MAX_TMP_SOCKETS] = { nullptr };  ///< Sockets used to talk to clients which have not yet been assigned a player number (host only).
static std::array<TmpSocketInfo, MAX_TMP_SOCKETS> tmp_connectState;
static bool bAsyncJoinApprovalEnabled = false;
static std::unordered_map<std::string, size_t> tmp_pendingIPs;

struct TmpBadIPInfo
{
	std::chrono::steady_clock::time_point expiry;
	size_t attempts = 0;
};
static lru11::Cache<std::string, TmpBadIPInfo> tmp_badIPs(512, 64);

static IConnectionPollGroup* tmp_socket_set = nullptr;
static int32_t          NetGameFlags[4] = { 0, 0, 0, 0 };
char iptoconnect[PATH_MAX] = "\0"; // holds IP/hostname from command line
bool cliConnectToIpAsSpectator = false; // for cli option

static NETSTATS nStats              = {{0, 0}, {0, 0}, {0, 0}};
static NETSTATS nStatsLastSec       = {{0, 0}, {0, 0}, {0, 0}};
static NETSTATS nStatsSecondLastSec = {{0, 0}, {0, 0}, {0, 0}};
static const NETSTATS nZeroStats    = {{0, 0}, {0, 0}, {0, 0}};
static int nStatsLastUpdateTime = 0;

unsigned NET_PlayerConnectionStatus[CONNECTIONSTATUS_NORMAL][MAX_CONNECTED_PLAYERS];
std::vector<optional<uint32_t>>	NET_waitingForIndexChangeAckSince = std::vector<optional<uint32_t>>(MAX_CONNECTED_PLAYERS, nullopt);	///< If waiting for the client to acknowledge a player index change, this is the realTime we started waiting

static LobbyServerConnectionHandler lobbyConnectionHandler;
static PlayerManagementRecord playerManagementRecord;

PortMappingAsyncRequestHandle ipv4MappingRequest;

// ////////////////////////////////////////////////////////////////////////////
/************************************************************************************
 **  NOTE (!)  Increment NETCODE_VERSION_MINOR on each release.
 **
 ************************************************************************************
**/
static char const *versionString = version_getVersionString();

#include "lib/netplay/netplay_config.h"

const std::vector<WZFile>& NET_getDownloadingWzFiles()
{
	return DownloadingWzFiles;
}

void NET_addDownloadingWZFile(WZFile&& newFile)
{
	DownloadingWzFiles.push_back(std::move(newFile));
}

void NET_clearDownloadingWZFiles()
{
	// if we were in a middle of transferring a file, then close the file handle
	for (auto &file : DownloadingWzFiles)
	{
		debug(LOG_NET, "closing aborted file");
		file.closeFile();
		ASSERT(!file.filename.empty(), "filename must not be empty");
		PHYSFS_delete(file.filename.c_str()); 		// delete incomplete (map) file
	}
	DownloadingWzFiles.clear();
}

NETPLAY::NETPLAY()
{
	players.resize(MAX_CONNECTED_PLAYERS);
	scriptSetPlayerDataStrings.resize(MAX_PLAYERS);
	playerReferences.resize(MAX_CONNECTED_PLAYERS);
	for (auto i = 0; i < MAX_CONNECTED_PLAYERS; i++)
	{
		playerReferences[i] = std::make_shared<PlayerReference>(i);
	}
}

bool NETisCorrectVersion(uint32_t game_version_major, uint32_t game_version_minor)
{
	return (uint32_t)NETCODE_VERSION_MAJOR == game_version_major && (uint32_t)NETCODE_VERSION_MINOR == game_version_minor;
}

bool NETisGreaterVersion(uint32_t game_version_major, uint32_t game_version_minor)
{
	return (game_version_major > NETCODE_VERSION_MAJOR) || ((game_version_major == NETCODE_VERSION_MAJOR) && (game_version_minor > NETCODE_VERSION_MINOR));
}

uint32_t NETGetMajorVersion()
{
	return NETCODE_VERSION_MAJOR;
}

uint32_t NETGetMinorVersion()
{
	return NETCODE_VERSION_MINOR;
}

bool NETGameIsLocked()
{
	return NetPlay.GamePassworded;
}

bool NET_getLobbyDisabled()
{
	return lobby_disabled;
}

const std::string& NET_getLobbyDisabledInfoLinkURL()
{
	return lobby_disabled_info_link_url;
}

void NET_setLobbyDisabled(const std::string& infoLinkURL)
{
	lobby_disabled = true;
	lobby_disabled_info_link_url = infoLinkURL;
}

uint32_t NET_getCurrentHostedLobbyGameId()
{
	return gamestruct.gameId;
}

//	Sets if the game is password protected or not
void NETGameLocked(bool flag)
{
	NetPlay.GamePassworded = flag;
	bool flagChanged = gamestruct.privateGame != (uint32_t)flag;
	gamestruct.privateGame = flag;
	if (allow_joining && NetPlay.isHost && flagChanged)
	{
		debug(LOG_NET, "Updating game locked status.");
		NETregisterServer(WZ_SERVER_UPDATE);
	}
	if (flagChanged)
	{
		ActivityManager::instance().updateMultiplayGameData(game, ingame, NETGameIsLocked());
	}
	NETlogEntry("Password is", SYNC_FLAG, NetPlay.GamePassworded);
	debug(LOG_NET, "Passworded game is %s", NetPlay.GamePassworded ? "TRUE" : "FALSE");
}

SpectatorInfo SpectatorInfo::currentNetPlayState()
{
	SpectatorInfo latestSpecInfo;
	for (const auto& slot : NetPlay.players)
	{
		if (slot.isSpectator)
		{
			latestSpecInfo.totalSpectatorSlots++;
			if (slot.allocated)
			{
				latestSpecInfo.spectatorsJoined++;
			}
		}
	}
	return latestSpecInfo;
}

SpectatorInfo NETGameGetSpectatorInfo()
{
	if (NetPlay.isHost)
	{
		// we have this as part of the host current gamestruct
		return SpectatorInfo::fromUint32(gamestruct.desc.dwUserFlags[1]);
	}
	else
	{
		return SpectatorInfo::currentNetPlayState();
	}
}

void NETsetLobbyOptField(const char *Value, const NET_LOBBY_OPT_FIELD Field)
{
	switch (Field)
	{
		case NET_LOBBY_OPT_FIELD::GNAME:
			sstrcpy(gamestruct.name, Value);
			break;
		case NET_LOBBY_OPT_FIELD::MAPNAME:
			sstrcpy(gamestruct.mapname, formatGameName(Value).toUtf8().c_str());
			break;
		case NET_LOBBY_OPT_FIELD::HOSTNAME:
			sstrcpy(gamestruct.hostname, Value);
			break;
		default:
			debug(LOG_WARNING, "Invalid field specified for NETsetGameOptField()");
			break;
	}
}

//	Sets the game password
void NETsetGamePassword(const char *password)
{
	sstrcpy(NetPlay.gamePassword, password);
	debug(LOG_NET, "Password entered is: [%s]", NetPlay.gamePassword);
	NETGameLocked(true);
}

//	Resets the game password
void NETresetGamePassword()
{
	NetPlay.gamePassword[0] = '\0';
	debug(LOG_NET, "password was reset");
	NETGameLocked(false);
}

void NETsetAsyncJoinApprovalRequired(bool enabled)
{
	bAsyncJoinApprovalEnabled = enabled;
	if (bAsyncJoinApprovalEnabled)
	{
		debug(LOG_INFO, "Async join approval is required");
	}
}

bool NETgetAsyncJoinApprovalRequired()
{
	return bAsyncJoinApprovalEnabled;
}

//	NOTE: *MUST* be called from the main thread!
bool NETsetAsyncJoinApprovalResult(const std::string& uniqueJoinID, AsyncJoinApprovalAction action, optional<uint8_t> explicitPlayerIdx, LOBBY_ERROR_TYPES rejectedReason, optional<std::string> customRejectionMessage)
{
	if (action == AsyncJoinApprovalAction::Reject && rejectedReason == ERROR_NOERROR)
	{
		debug(LOG_INFO, "Rejecting join with NOERROR reason changed to ERROR_KICKED");
		rejectedReason = ERROR_KICKED;
	}
	for (auto& tmp_info : tmp_connectState)
	{
		if (tmp_info.connectState == TmpSocketInfo::TmpConnectState::PendingAsyncApproval
			&& tmp_info.uniqueJoinID == uniqueJoinID)
		{
			// found a match
			tmp_info.asyncJoinApprovalResult = action;
			tmp_info.asyncJoinApprovalExplicitPlayerIdx = (action == AsyncJoinApprovalAction::Approve) ? explicitPlayerIdx : nullopt;
			tmp_info.asyncJoinRejectCode = (action != AsyncJoinApprovalAction::Reject) ? ERROR_NOERROR : rejectedReason;
			if (customRejectionMessage.has_value())
			{
				tmp_info.asyncJoinRejectCustomMessage = customRejectionMessage.value();
			}
			return true;
		}
	}

	// no matching pending join - may have dropped in the interim, etc
	return false;
}

// *********** Socket with buffer that read NETMSGs ******************

static size_t NET_fillBuffer(IClientConnection** pSocket, IConnectionPollGroup* pSocketSet, uint8_t *bufstart, int bufsize)
{
	IClientConnection* socket = *pSocket;

	if (!socket->readReady())
	{
		return 0;
	}

	size_t rawBytes;
	const auto readResult = socket->readNoInt(bufstart, bufsize, &rawBytes);

	if (readResult.has_value())
	{
		const auto size = readResult.value();

		nStats.rawBytes.received          += rawBytes;
		nStats.uncompressedBytes.received += static_cast<size_t>(size);
		nStats.packets.received           += 1;

		return size;
	}
	else
	{
		if (readResult.error() == std::errc::timed_out || readResult.error() == std::errc::connection_reset)
		{
			debug(LOG_NET, "Connection closed from the other side");
			NETlogEntry("Connection closed from the other side..", SYNC_FLAG, selectedPlayer);
		}
		else
		{
			const auto readErrMsg = readResult.error().message();
			debug(LOG_NET, "%s socket %p is now invalid", readErrMsg.c_str(), static_cast<void*>(socket));
		}

		// an error occurred, or the remote host has closed the connection.
		if (pSocketSet != nullptr)
		{
			pSocketSet->remove(socket);
		}
		if (bsocket == socket)
		{
			debug(LOG_NET, "Host connection was lost!");
			NETlogEntry("Host connection was lost!", SYNC_FLAG, selectedPlayer);
			//Game is pretty much over --should just end everything when HOST dies.
			NETclientHandleHostDisconnected();
			bsocket = nullptr;
			ingame.localJoiningInProgress = false;
			NETclose();
			return 0;
		}
		socket->close();
		*pSocket = nullptr;
	}

	return 0;
}

static int playersPerTeam()
{
	for (int v = game.maxPlayers - 1; v > 1; --v)
	{
		if (game.maxPlayers%v == 0)
		{
			return v;
		}
	}
	return 1;
}

/**
 * Resets network properties of a player to safe defaults. Player slots should always be in this state
 * before attemtping to assign a connectign player to it.
 *
 * Used to reset the player slot in NET_InitPlayer and to reset players slot without modifying ai/team/
 * position configuration for the players.
 */
static void initPlayerNetworkProps(int playerIndex)
{
	NetPlay.players[playerIndex].allocated = false;
	NetPlay.players[playerIndex].autoGame = false;
	NetPlay.players[playerIndex].heartattacktime = 0;
	NetPlay.players[playerIndex].heartbeat = false;
	NetPlay.players[playerIndex].ready = false;

	if (NetPlay.players[playerIndex].wzFiles)
	{
		NetPlay.players[playerIndex].wzFiles->clear();
	}
	else
	{
		ASSERT(false, "PLAYERS.wzFiles is uninitialized??");
	}
	if (playerIndex < MAX_CONNECTED_PLAYERS)
	{
		ingame.JoiningInProgress[playerIndex] = false;
		ingame.PendingDisconnect[playerIndex] = false;
		ingame.joinTimes[playerIndex].reset();
		ingame.lastReadyTimes[playerIndex].reset();
		ingame.lastNotReadyTimes[playerIndex].reset();
		ingame.secondsNotReady[playerIndex] = 0;
		ingame.playerLeftGameTime[playerIndex].reset();
		ingame.hostChatPermissions[playerIndex] = (NetPlay.bComms) ? NETgetDefaultMPHostFreeChatPreference() : true;
	}
}

void NET_InitPlayer(uint32_t i, bool initPosition, bool initTeams, bool initSpectator)
{
	ASSERT_OR_RETURN(, i < NetPlay.players.size(), "Invalid player_id: (%" PRIu32")",  i);

	initPlayerNetworkProps(i);

	NetPlay.players[i].difficulty = AIDifficulty::DISABLED;
	if (ingame.localJoiningInProgress)
	{
		// only clear name outside of games.
		clearPlayerName(i);
	}
	if (initPosition)
	{
		setPlayerColour(i, i);
		NetPlay.players[i].position = i;
		NetPlay.players[i].team = initTeams && i < game.maxPlayers? i/playersPerTeam() : i;
	}
	if (NetPlay.bComms)
	{
		NetPlay.players[i].ai = AI_OPEN;
	}
	else
	{
		NetPlay.players[i].ai = 0;
	}
	NetPlay.players[i].faction = FACTION_NORMAL;
	if (initSpectator)
	{
		NetPlay.players[i].isSpectator = false;
	}
	NetPlay.players[i].isAdmin = false;
}

uint8_t NET_numHumanPlayers(void)
{
	uint8_t RetVal = 0;
	for (uint8_t Inc = 0; Inc < MAX_PLAYERS; ++Inc)
	{
		if (NetPlay.players[Inc].allocated && !NetPlay.players[Inc].isSpectator) ++RetVal;
	}

	return RetVal;
}

std::vector<uint8_t> NET_getHumanPlayers(void)
{
	std::vector<uint8_t> RetVal;
	RetVal.reserve(MAX_PLAYERS);

	for (uint8_t Inc = 0; Inc < MAX_PLAYERS; ++Inc)
	{
		if (NetPlay.players[Inc].allocated && !NetPlay.players[Inc].isSpectator) RetVal.push_back(Inc);
	}

	return RetVal;
}

void NET_InitPlayers(bool initTeams, bool initSpectator)
{
	for (unsigned i = 0; i < MAX_CONNECTED_PLAYERS; ++i)
	{
		NET_InitPlayer(i, true, initTeams, initSpectator);
		ingame.muteChat[i] = false;
		playerSpamMuteReset(i);
		clearPlayerName(i);
		NETinitQueue(NETnetQueue(i));
	}
	resetRecentScoreData();
	NETinitQueue(NETbroadcastQueue());

	NetPlay.hostPlayer = NET_HOST_ONLY;	// right now, host starts always at index zero
	NetPlay.playercount = 0;
	DownloadingWzFiles.clear();
	NET_waitingForIndexChangeAckSince = std::vector<optional<uint32_t>>(MAX_CONNECTED_PLAYERS, nullopt);
	debug(LOG_NET, "Players initialized");
}

static void NETSendNPlayerInfoTo(uint32_t *index, uint32_t indexLen, unsigned to)
{
	ASSERT_HOST_ONLY(return);
	auto w = NETbeginEncode(NETnetQueue(to), NET_PLAYER_INFO);
	NETuint32_t(w, indexLen);
	for (unsigned n = 0; n < indexLen; ++n)
	{
		debug(LOG_NET, "sending player's (%u) info to all players", index[n]);
		NETlogEntry("Sending player's info to all players", SYNC_FLAG, index[n]);
		NETuint32_t(w, index[n]);
		NETbool(w, NetPlay.players[index[n]].allocated);
		NETbool(w, NetPlay.players[index[n]].heartbeat);
		NETbool(w, false); // to maintain message format, send false in place of old "kick" variable // FUTURE TODO: Remove
		if (isBlindPlayerInfoState() // if in blind player info state
			&& index[n] < MAX_PLAYER_SLOTS) // and an actual player slot (not a spectator slot)
		{
			// send a generic player name
			const char* genericName = getPlayerGenericName(index[n]);
			NETstring(w, genericName, static_cast<uint16_t>(strlen(genericName) + 1));
		}
		else
		{
			// send the actual player name
			NETstring(w, NetPlay.players[index[n]].name, static_cast<uint16_t>(sizeof(NetPlay.players[index[n]].name)));
		}
		NETuint32_t(w, NetPlay.players[index[n]].heartattacktime);
		NETint32_t(w, NetPlay.players[index[n]].colour);
		NETint32_t(w, NetPlay.players[index[n]].position);
		NETint32_t(w, NetPlay.players[index[n]].team);
		NETbool(w, NetPlay.players[index[n]].ready);
		NETint8_t(w, NetPlay.players[index[n]].ai);
		NETint8_t(w, static_cast<int8_t>(NetPlay.players[index[n]].difficulty));
		NETuint8_t(w, static_cast<uint8_t>(NetPlay.players[index[n]].faction));
		NETbool(w, NetPlay.players[index[n]].isSpectator);
		NETbool(w, NetPlay.players[index[n]].isAdmin);
	}
	NETend(w);
	ActivityManager::instance().updateMultiplayGameData(game, ingame, NETGameIsLocked());
}

static void NETSendPlayerInfoTo(uint32_t index, unsigned to)
{
	NETSendNPlayerInfoTo(&index, 1, to);
}

void NETSendAllPlayerInfoTo(unsigned to)
{
	static uint32_t indices[MAX_CONNECTED_PLAYERS];
	for (int i = 0; i < MAX_CONNECTED_PLAYERS; ++i)
	{
		indices[i] = i;
	}
	ASSERT_OR_RETURN(, NetPlay.isHost == true, "Invalid call for non-host");

	NETSendNPlayerInfoTo(indices, ARRAY_SIZE(indices), to);
}

void NETBroadcastTwoPlayerInfo(uint32_t index1, uint32_t index2)
{
	ASSERT_HOST_ONLY(return);
	uint32_t indices[2] = {index1, index2};
	NETSendNPlayerInfoTo(indices, 2, NET_ALL_PLAYERS);
}

void NETBroadcastPlayerInfo(uint32_t index)
{
	if (!NetPlay.isHost)
	{
		return;
	}
	NETSendPlayerInfoTo(index, NET_ALL_PLAYERS);
}

// Checks if there are *any* open slots (player *OR* spectator) for an incoming connection
static bool NET_HasAnyOpenSlots()
{
	for (int i = 0; i < MAX_CONNECTED_PLAYERS; ++i)
	{
		if (i == scavengerSlot())
		{
			// do not offer up the scavenger slot (this really needs to be refactored later - why is this a variable slot index?!?)
			continue;
		}
		if (i == PLAYER_FEATURE)
		{
			// do not offer up this "player feature" slot - TODO: maybe remove the need for this slot?
			continue;
		}
		PLAYER const &p = NetPlay.players[i];
		if (!p.allocated && p.ai == AI_OPEN)
		{
			return true;
		}
	}
	return false;
}

static inline bool NET_IsSlotOpenForPlayerJoin(int i, bool forceTakeLowestAvailablePlayerNumber = false, optional<bool> asSpectator = false)
{
	if (!forceTakeLowestAvailablePlayerNumber && !asSpectator.value_or(false) && (i >= game.maxPlayers || i >= MAX_PLAYERS || NetPlay.players[i].position >= game.maxPlayers))
	{
		// Player slots are only supported where the player index and the player position is <= game.maxPlayers
		// Skip otherwise
		return false;
	}
	if (i == scavengerSlot())
	{
		// do not offer up the scavenger slot (this really needs to be refactored later - why is this a variable slot index?!?)
		return false;
	}
	if (i == PLAYER_FEATURE)
	{
		// do not offer up this "player feature" slot - TODO: maybe remove the need for this slot?
		return false;
	}

	PLAYER const &p = NetPlay.players[i];
	if (p.allocated || p.ai != AI_OPEN)
	{
		// not an open slot
		return false;
	}
	if (asSpectator.has_value() && asSpectator.value() != p.isSpectator)
	{
		return false;
	}
	return true;
}

static optional<uint32_t> NET_FindOpenSlotForPlayer(bool forceTakeLowestAvailablePlayerNumber = false, optional<bool> asSpectator = false)
{
	int index = -1;
	int position = INT_MAX;
	for (int i = 0; i < MAX_CONNECTED_PLAYERS; ++i)
	{
		if (!NET_IsSlotOpenForPlayerJoin(i, forceTakeLowestAvailablePlayerNumber, asSpectator))
		{
			continue;
		}
		// find the lowest "position" slot that is available (unless forceTakeLowestAvailablePlayerNumber is set, in which case just take the first available)
		PLAYER const &p = NetPlay.players[i];
		if (p.position < position)
		{
			index = i;
			position = p.position;
			if (forceTakeLowestAvailablePlayerNumber)
			{
				break;
			}
		}
	}

	if (index == -1)
	{
		return nullopt;
	}

	return static_cast<uint32_t>(index);
}

static bool NET_CreatePlayerAtIdx(uint32_t index, char const *name)
{
	ASSERT_OR_RETURN(false, !NetPlay.players[index].allocated, "Player index (%" PRIu32 ")already allocated!", index);

	char buf[250] = {'\0'};

	ssprintf(buf, "A new player has been created. Player, %s, is set to slot %u", name, index);
	debug(LOG_NET, "%s", buf);
	NETlogEntry(buf, SYNC_FLAG, index);
	NET_InitPlayer(index, false);  // re-init everything
	NetPlay.players[index].allocated = true;
	NetPlay.players[index].difficulty = AIDifficulty::HUMAN;
	NetPlay.players[index].heartbeat = true;
	setPlayerName(index, name);
	if (!NetPlay.players[index].isSpectator)
	{
		++NetPlay.playercount;
	}
	++sync_counter.joins;
	return true;
}

static optional<uint32_t> NET_CreatePlayer(char const *name, bool forceTakeLowestAvailablePlayerNumber = false, optional<bool> asSpectator = false)
{
	optional<uint32_t> index = NET_FindOpenSlotForPlayer(forceTakeLowestAvailablePlayerNumber, asSpectator);
	if (!index.has_value())
	{
		debug(LOG_INFO, "Could not find place for %s %s", (!asSpectator.value_or(false)) ? "player" : "spectator", name);
		NETlogEntry((!asSpectator.value_or(false)) ? "Could not find a place for player!" : "Could not find a place for spectator!", SYNC_FLAG, -1);
		return nullopt;
	}

	if (!NET_CreatePlayerAtIdx(index.value(), name))
	{
		// should not happen
		return nullopt;
	}
	return index;
}

static void NET_DestroyPlayer(unsigned int index, bool suppressActivityUpdates = false)
{
	ASSERT_OR_RETURN(, index < NetPlay.players.size(), "Invalid player_id: (%" PRIu32")",  index);
	debug(LOG_NET, "Freeing slot %u for a new player", index);
	NETlogEntry("Freeing slot for a new player.", SYNC_FLAG, index);
	bool wasAllocated = NetPlay.players[index].allocated;
	if (NetPlay.players[index].allocated)
	{
		NetPlay.players[index].allocated = false;
		if (!NetPlay.players[index].isSpectator)
		{
			NetPlay.playercount--;
		}
		gamestruct.desc.dwCurrentPlayers = NetPlay.playercount;
		if (allow_joining && NetPlay.isHost)
		{
			// Update player count in the lobby by disconnecting
			// and reconnecting
			NETregisterServer(WZ_SERVER_UPDATE);
		}
	}
	NET_InitPlayer(index, false);  // reinitialize
	if (wasAllocated && !suppressActivityUpdates)
	{
		ActivityManager::instance().updateMultiplayGameData(game, ingame, NETGameIsLocked());
	}
}

bool NETplayerHasConnection(uint32_t index)
{
	ASSERT_HOST_ONLY(return false);
	ASSERT_OR_RETURN(false, index < MAX_CONNECTED_PLAYERS, "Invalid index: %" PRIu32, index);
	return connected_bsocket[index] != nullptr;
}

/**
 * @note Connection dropped. Handle it gracefully.
 * \param index
 */
static void NETplayerClientsDisconnect(const std::set<uint32_t>& indexes)
{
	if (!NetPlay.isHost)
	{
		ASSERT(false, "Host only routine detected for client!");
		return;
	}

	if (indexes.empty())
	{
		return;
	}

	// 1.) Do a pass just closing the sockets (in case multiple players involved)
	std::vector<uint32_t> playersActuallyDisconnected;
	for (auto index : indexes)
	{
		if (index >= MAX_CONNECTED_PLAYERS)
		{
			ASSERT(index < MAX_CONNECTED_PLAYERS, "Invalid player index: %" PRIu32, index);
			continue;
		}

		if (connected_bsocket[index])
		{
			debug(LOG_NET, "Player (%u) has left unexpectedly, closing socket %p", index, static_cast<void *>(connected_bsocket[index]));

			NETplayerCloseSocket(index, false);
			playersActuallyDisconnected.push_back(index);
		}
		else
		{
			debug(LOG_ERROR, "Player (%u) has left unexpectedly - but socket already closed?", index);
		}
	}

	// 2.) Notify other players about which players were disconnected
	for (auto index : playersActuallyDisconnected)
	{
		if (index >= MAX_CONNECTED_PLAYERS)
		{
			continue;
		}

		NETplayerLeaving(index, true);

		NETlogEntry("Player has left unexpectedly.", SYNC_FLAG, index);
		// Announce to the world. This was really icky, because we may have been calling the send
		// function recursively. We really ought to have had a send queue, and now we finally do...
		if (ingame.localJoiningInProgress)  // Only if game hasn't actually started yet.
		{
			auto w = NETbeginEncode(NETbroadcastQueue(), NET_PLAYER_DROPPED);
			NETuint32_t(w, index);
			NETend(w);
		}
	}
}

static void NETplayerCloseSocket(UDWORD index, bool quietSocketClose)
{
	ASSERT_OR_RETURN(, index < MAX_CONNECTED_PLAYERS, "Invalid index: %" PRIu32, index);
	if (connected_bsocket[index])
	{
		debug(LOG_NET, "Player (%u) has left, closing socket %p", index, static_cast<void *>(connected_bsocket[index]));
		NETlogEntry("Player has left nicely.", SYNC_FLAG, index);

		// Although we can get a error result from DelSocket, it don't really matter here.
		server_socket_set->remove(connected_bsocket[index]);
		connected_bsocket[index]->close();
		connected_bsocket[index] = nullptr;
	}
	else
	{
		debug(LOG_NET, "Player (%u) has left nicely, socket already closed?", index);
	}

	NetPlay.players[index].heartbeat = false; // mark client as dead
}

/**
 * @note When a player leaves nicely (ie, we got a NET_PLAYER_LEAVING
 *       message), we clean up the socket that we used.
 * \param index
 */
static void NETplayerLeaving(UDWORD index, bool quietSocketClose)
{
	ASSERT_OR_RETURN(, index < MAX_CONNECTED_PLAYERS, "Invalid index: %" PRIu32, index);
	bool previousPlayersShouldCheckReadyValue = multiplayPlayersShouldCheckReady();
	NETplayerCloseSocket(index, quietSocketClose);
	sync_counter.left++;
	bool wasSpectator = NetPlay.players[index].isSpectator;
	MultiPlayerLeave(index);		// more cleanup
	if (ingame.localJoiningInProgress)  // Only if game hasn't actually started yet.
	{
		NET_DestroyPlayer(index);       // sets index player's array to false
		if (!wasSpectator)
		{
			resetReadyStatus(false, shouldSkipReadyResetOnPlayerJoinLeaveEvent());		// reset ready status for all players
		}
		handlePossiblePlayersShouldCheckReadyChange(previousPlayersShouldCheckReadyValue);

		wz_command_interface_output_room_status_json(true);
	}
}

/**
 * @note When a player's connection is broken we broadcast the NET_PLAYER_DROPPED
 *       message.
 * \param index
 */
static void NETplayerDropped(UDWORD index)
{
	ASSERT_OR_RETURN(, index < NetPlay.players.size(), "Invalid index: %" PRIu32, index);
	uint32_t id = index;

	if (!NetPlay.isHost)
	{
		ASSERT(false, "Host only routine detected for client!");
		return;
	}

	bool previousPlayersShouldCheckReadyValue = multiplayPlayersShouldCheckReady();

	sync_counter.drops++;
	bool wasSpectator = NetPlay.players[index].isSpectator;
	MultiPlayerLeave(id);			// more cleanup
	if (ingame.localJoiningInProgress)  // Only if game hasn't actually started yet.
	{
		// Send message type specifically for dropped / disconnects
		auto w = NETbeginEncode(NETbroadcastQueue(), NET_PLAYER_DROPPED);
		NETuint32_t(w, id);
		NETend(w);
		debug(LOG_INFO, "sending NET_PLAYER_DROPPED for player %d", id);
		NET_DestroyPlayer(id);          // just clears array
		if (!wasSpectator)
		{
			resetReadyStatus(false, shouldSkipReadyResetOnPlayerJoinLeaveEvent());		// reset ready status for all players
		}
		handlePossiblePlayersShouldCheckReadyChange(previousPlayersShouldCheckReadyValue);

		wz_command_interface_output_room_status_json(true);
	}

	NETsetPlayerConnectionStatus(CONNECTIONSTATUS_PLAYER_DROPPED, id);
}

/**
 * @note Cleanup for when a player is kicked.
 * \param index
 */
void NETplayerKicked(UDWORD index, bool quiet)
{
	ASSERT_OR_RETURN(, index < MAX_CONNECTED_PLAYERS, "NETplayerKicked invalid player_id: (%" PRIu32")", index);

	// kicking a player counts as "leaving nicely", since "nicely" in this case
	// simply means "there wasn't a connection error."
	debug((!quiet) ? LOG_INFO : LOG_NET, "Player %u was kicked.", index);
	sync_counter.kicks++;
	NETlogEntry("Player was kicked.", SYNC_FLAG, index);
	NETplayerLeaving(index);		// need to close socket for the player that left.
	NETsetPlayerConnectionStatus(CONNECTIONSTATUS_PLAYER_LEAVING, index);
}

// ////////////////////////////////////////////////////////////////////////
// rename the local player
bool NETchangePlayerName(UDWORD index, char *newName)
{
	if (!NetPlay.bComms)
	{
		setPlayerName(0, newName);
		return true;
	}
	debug(LOG_NET, "Requesting a change of player name for pid=%u to %s", index, newName);
	NETlogEntry("Player wants a name change.", SYNC_FLAG, index);
	ASSERT_OR_RETURN(false, index < MAX_CONNECTED_PLAYERS, "invalid index: %" PRIu32 "", index);

	setPlayerName(index, newName);
	if (NetPlay.isHost)
	{
		NETSendAllPlayerInfoTo(NET_ALL_PLAYERS);
	}
	else
	{
		ASSERT_OR_RETURN(false, index <= static_cast<uint32_t>(std::numeric_limits<uint8_t>::max()), "index (%" PRIu32 ") exceeds supported bounds", index);
		ASSERT_OR_RETURN(false, index == selectedPlayer, "Clients can only change their own name!");
		uint8_t player = static_cast<uint8_t>(index);
		WzString newNameStr = NetPlay.players[index].name;
		auto w = NETbeginEncode(NETnetQueue(NetPlay.hostPlayer), NET_PLAYERNAME_CHANGEREQUEST);
		NETuint8_t(w, player);
		NETwzstring(w, newNameStr);
		NETend(w);
	}

	return true;
}

void NETfixDuplicatePlayerNames()
{
	char name[StringSize];
	unsigned i, j, pass;
	for (i = 1; i != MAX_CONNECTED_PLAYERS; ++i)
	{
		sstrcpy(name, NetPlay.players[i].name);
		if (name[0] == '\0' || !NetPlay.players[i].allocated)
		{
			continue;  // Ignore empty names.
		}
		for (pass = 0; pass != 101; ++pass)
		{
			if (pass != 0)
			{
				ssprintf(name, "%s_%X", NetPlay.players[i].name, pass + 1);
			}

			for (j = 0; j != i; ++j)
			{
				if (strcmp(name, NetPlay.players[j].name) == 0)
				{
					break;  // Duplicate name.
				}
			}

			if (i == j)
			{
				break;  // Unique name.
			}
		}
		if (pass != 0)
		{
			NETchangePlayerName(i, name);
		}
	}
}

// ////////////////////////////////////////////////////////////////////////
// return one of the four user flags in the current sessiondescription.
SDWORD NETgetGameFlags(UDWORD flag)
{
	if (flag < 1 || flag > 4)
	{
		return 0;
	}
	else
	{
		return NetGameFlags[flag - 1];
	}
}

static void NETsendGameFlags()
{
	ASSERT_HOST_ONLY(return);
	debug(LOG_NET, "sending game flags");
	auto w = NETbeginEncode(NETbroadcastQueue(), NET_GAME_FLAGS);
	{
		// Send the amount of game flags we're about to send
		uint8_t i, count = ARRAY_SIZE(NetGameFlags);
		NETuint8_t(w, count);

		// Send over all game flags
		for (i = 0; i < count; ++i)
		{
			NETint32_t(w, NetGameFlags[i]);
		}
	}
	NETend(w);
}

// ////////////////////////////////////////////////////////////////////////
// Set a game flag
bool NETsetGameFlags(UDWORD flag, SDWORD value)
{
	if (!NetPlay.bComms)
	{
		return true;
	}

	if (flag > 0 && flag < 5)
	{
		return (NetGameFlags[flag - 1] = value);
	}

	NETsendGameFlags();

	return true;
}

static constexpr size_t GAMESTRUCTmessageBufSize()
{
	return sizeof(GAMESTRUCT::GAMESTRUCT_VERSION) +
		sizeof(GAMESTRUCT::name) +
		sizeof(std::declval<GAMESTRUCT>().desc.host) +
		(sizeof(int32_t) * 8) +
		sizeof(GAMESTRUCT::secondaryHosts) +
		sizeof(GAMESTRUCT::extra) +
		sizeof(GAMESTRUCT::hostPort) +
		sizeof(GAMESTRUCT::mapname) +
		sizeof(GAMESTRUCT::hostname) +
		sizeof(GAMESTRUCT::versionstring) +
		sizeof(GAMESTRUCT::modlist) +
		(sizeof(uint32_t) * 9);
}

/**
 * @note \c game is being sent to the master server (if hosting)
 *       The implementation of NETsendGAMESTRUCT <em>must</em> guarantee to
 *       pack it in network byte order (big-endian).
 *
 * @return true on success, false when a socket error has occurred
 *
 * @see GAMESTRUCT,NETrecvGAMESTRUCT
 */
static net::result<void> NETsendGAMESTRUCT(IClientConnection* sock, const GAMESTRUCT *ourgamestruct)
{
	// A buffer that's guaranteed to have the correct size (i.e. it
	// circumvents struct padding, which could pose a problem).  Initialise
	// to zero so that we can be sure we're not sending any (undefined)
	// memory content across the network.
	char buf[GAMESTRUCTmessageBufSize()] = { 0 };
	char *buffer = buf;
	unsigned int i;

	auto push32 = [&](uint32_t value) {
		uint32_t swapped = wz_htonl(value);
		memcpy(buffer, &swapped, sizeof(swapped));
		buffer += sizeof(swapped);
	};

	auto push16 = [&](uint16_t value) {
		uint16_t swapped = wz_htons(value);
		memcpy(buffer, &swapped, sizeof(swapped));
		buffer += sizeof(swapped);
	};

	auto push8 = [&](uint8_t value) {
		memcpy(buffer, &value, sizeof(value));
		buffer += sizeof(value);
	};

	// Now dump the data into the buffer
	// Copy 32bit large big endian numbers
	push32(ourgamestruct->GAMESTRUCT_VERSION);

	// Copy a string
	strlcpy(buffer, ourgamestruct->name, sizeof(ourgamestruct->name));
	buffer += sizeof(ourgamestruct->name);

	// Copy 32bit large big endian numbers
	push32(ourgamestruct->desc.dwSize);

	// Copy various bytes
	push8(ourgamestruct->desc.alliances);
	push8(ourgamestruct->desc.techLevel);
	push8(ourgamestruct->desc.powerLevel);
	push8(ourgamestruct->desc.basesLevel);

	// Copy yet another string
	strlcpy(buffer, ourgamestruct->desc.host, sizeof(ourgamestruct->desc.host));
	buffer += sizeof(ourgamestruct->desc.host);

	// Copy 32bit large big endian numbers
	push32(ourgamestruct->desc.dwMaxPlayers);
	push32(ourgamestruct->desc.dwCurrentPlayers);
	for (i = 0; i < ARRAY_SIZE(ourgamestruct->desc.dwUserFlags); ++i)
	{
		push32(ourgamestruct->desc.dwUserFlags[i]);
	}

	// Copy a string
	for (i = 0; i < ARRAY_SIZE(ourgamestruct->secondaryHosts); ++i)
	{
		strlcpy(buffer, ourgamestruct->secondaryHosts[i], sizeof(ourgamestruct->secondaryHosts[i]));
		buffer += sizeof(ourgamestruct->secondaryHosts[i]);
	}

	// Copy a string
	strlcpy(buffer, ourgamestruct->extra, sizeof(ourgamestruct->extra));
	buffer += sizeof(ourgamestruct->extra);

	// Copy 16bit large big endian number
	push16(ourgamestruct->hostPort);

	// Copy a string
	strlcpy(buffer, ourgamestruct->mapname, sizeof(ourgamestruct->mapname));
	buffer += sizeof(ourgamestruct->mapname);

	// Copy a string
	strlcpy(buffer, ourgamestruct->hostname, sizeof(ourgamestruct->hostname));
	buffer += sizeof(ourgamestruct->hostname);

	// Copy a string
	strlcpy(buffer, ourgamestruct->versionstring, sizeof(ourgamestruct->versionstring));
	buffer += sizeof(ourgamestruct->versionstring);

	// Copy a string
	strlcpy(buffer, ourgamestruct->modlist, sizeof(ourgamestruct->modlist));
	buffer += sizeof(ourgamestruct->modlist);

	// Copy 32bit large big endian numbers
	push32(ourgamestruct->game_version_major);

	// Copy 32bit large big endian numbers
	push32(ourgamestruct->game_version_minor);

	// Copy 32bit large big endian numbers
	push32(ourgamestruct->privateGame);

	// Copy 32bit large big endian numbers
	push32(ourgamestruct->pureMap);

	// Copy 32bit large big endian numbers
	push32(ourgamestruct->Mods);

	// Copy 32bit large big endian numbers
	push32(ourgamestruct->gameId);

	// Copy 32bit large big endian numbers
	push32(ourgamestruct->limits);

	// Copy 32bit large big endian numbers
	push32(ourgamestruct->future3);

	// Copy 32bit large big endian numbers
	push32(ourgamestruct->future4);

	debug(LOG_NET, "sending GAMESTRUCT, size: %u", (unsigned int)sizeof(buf));

	// Send over the GAMESTRUCT
	const auto writeResult = sock->writeAll(buf, sizeof(buf), nullptr);
	if (!writeResult.has_value())
	{
		const auto writeErrMsg = writeResult.error().message();
		// If packet could not be sent, we should inform user of the error.
		debug(LOG_ERROR, "Failed to send GAMESTRUCT. Reason: %s", writeErrMsg.c_str());
		debug(LOG_ERROR, "Please make sure TCP ports %u & %u are open!", masterserver_port, gameserver_port);

		return tl::make_unexpected(writeResult.error());
	}
	return {};
}

/**
 * @note \c game is being retrieved from the master server (if browsing the
 *       lobby). The implementation of NETrecvGAMESTRUCT should assume the data
 *       to be packed in network byte order (big-endian).
 *
 * @see GAMESTRUCT,NETsendGAMESTRUCT
 */
static bool NETrecvGAMESTRUCT(IClientConnection& sock, GAMESTRUCT *ourgamestruct)
{
	// A buffer that's guaranteed to have the correct size (i.e. it
	// circumvents struct padding, which could pose a problem).
	char buf[GAMESTRUCTmessageBufSize()] = { 0 };
	char *buffer = buf;
	unsigned int i;

	auto pop32 = [&]() -> uint32_t {
		uint32_t value = 0;
		memcpy(&value, buffer, sizeof(value));
		value = wz_ntohl(value);
		buffer += sizeof(value);
		return value;
	};

	auto pop16 = [&]() -> uint16_t {
		uint16_t value = 0;
		memcpy(&value, buffer, sizeof(value));
		value = wz_ntohs(value);
		buffer += sizeof(value);
		return value;
	};

	auto pop8 = [&]() -> uint8_t {
		uint8_t value = 0;
		memcpy(&value, buffer, sizeof(value));
		buffer += sizeof(value);
		return value;
	};

	// Read a GAMESTRUCT from the connection
	auto readResult = sock.readAll(buf, sizeof(buf), NET_TIMEOUT_DELAY);
	if (!readResult.has_value())
	{
		if (readResult.error() == std::errc::timed_out || readResult.error() == std::errc::connection_reset)
		{
			debug(LOG_ERROR, "GAMESTRUCT recv failed: timed out");
		}
		else
		{
			const auto readErrMsg = readResult.error().message();
			debug(LOG_ERROR, "Lobby server connection error: %s", readErrMsg.c_str());
		}
		// caller handles invalidating and closing tcp_socket
		return false;
	}

	// Now dump the data into the game struct
	// Copy 32bit large big endian numbers
	ourgamestruct->GAMESTRUCT_VERSION = pop32();
	// Copy a string
	sstrcpy(ourgamestruct->name, buffer);
	buffer += sizeof(ourgamestruct->name);

	// Copy 32bit large big endian numbers
	ourgamestruct->desc.dwSize = pop32();

	// Copy various bytes
	ourgamestruct->desc.alliances = pop8();
	ourgamestruct->desc.techLevel = pop8();
	ourgamestruct->desc.powerLevel = pop8();
	ourgamestruct->desc.basesLevel = pop8();

	// Copy yet another string
	sstrcpy(ourgamestruct->desc.host, buffer);
	buffer += sizeof(ourgamestruct->desc.host);

	// Copy 32bit large big endian numbers
	ourgamestruct->desc.dwMaxPlayers = pop32();
	ourgamestruct->desc.dwCurrentPlayers = pop32();
	for (i = 0; i < ARRAY_SIZE(ourgamestruct->desc.dwUserFlags); ++i)
	{
		ourgamestruct->desc.dwUserFlags[i] = pop32();
	}

	// Copy a string
	for (i = 0; i < ARRAY_SIZE(ourgamestruct->secondaryHosts); ++i)
	{
		sstrcpy(ourgamestruct->secondaryHosts[i], buffer);
		buffer += sizeof(ourgamestruct->secondaryHosts[i]);
	}

	// Copy a string
	sstrcpy(ourgamestruct->extra, buffer);
	buffer += sizeof(ourgamestruct->extra);

	// Copy 16-bit host port
	ourgamestruct->hostPort = pop16();

	// Copy a string
	sstrcpy(ourgamestruct->mapname, buffer);
	buffer += sizeof(ourgamestruct->mapname);

	// Copy a string
	sstrcpy(ourgamestruct->hostname, buffer);
	buffer += sizeof(ourgamestruct->hostname);

	// Copy a string
	sstrcpy(ourgamestruct->versionstring, buffer);
	buffer += sizeof(ourgamestruct->versionstring);

	// Copy a string
	sstrcpy(ourgamestruct->modlist, buffer);
	buffer += sizeof(ourgamestruct->modlist);

	// Copy 32bit large big endian numbers
	ourgamestruct->game_version_major = pop32();
	ourgamestruct->game_version_minor = pop32();
	ourgamestruct->privateGame = pop32();
	ourgamestruct->pureMap = pop32();
	ourgamestruct->Mods = pop32();
	ourgamestruct->gameId = pop32();
	ourgamestruct->limits = pop32();
	ourgamestruct->future3 = pop32();
	ourgamestruct->future4 = pop32();

	debug(LOG_NET, "received GAMESTRUCT");

	return true;
}

static PortMappingInternetProtocol getPreferredPortMappingProtocol(WzConnectionProvider& connProvider)
{
	// We currently support creating only IPV4 port mappings.
	constexpr auto IPV4_PROTOCOL_KINDS = static_cast<PortMappingInternetProtocolMask>(PortMappingInternetProtocol::TCP_IPV4) | static_cast<PortMappingInternetProtocolMask>(PortMappingInternetProtocol::UDP_IPV4);

	const auto supportedProtocolTypes = connProvider.portMappingProtocolTypes();
	const PortMappingInternetProtocol res = static_cast<PortMappingInternetProtocol>(supportedProtocolTypes & IPV4_PROTOCOL_KINDS);
	ASSERT(res == PortMappingInternetProtocol::TCP_IPV4 || res == PortMappingInternetProtocol::UDP_IPV4, "Unexpected port mapping protocol");
	return res;
}

void NETaddRedirects()
{
	ASSERT_OR_RETURN(, activeConnProvider != nullptr, "No active connection provider");
	auto& pmm = PortMappingManager::instance();
	ipv4MappingRequest = pmm.create_port_mapping(gameserver_port, getPreferredPortMappingProtocol(*activeConnProvider));
	if (!ipv4MappingRequest)
	{
		debug(LOG_NET, "Failed to create port mapping!");
		// Workaround: Delay console message until next main loop iteration, to ensure it gets displayed in the chat box
		wzAsyncExecOnMainThread([](){
			std::string msg = _("Failed to create port mapping");
			msg += "\n";
			msg += astringf(_("Manually configure your router/firewall to open port %d!"), NETgetGameserverPort());
			addConsoleMessage(msg.c_str(), DEFAULT_JUSTIFY, NOTIFY_MESSAGE);
		});
		return;
	}
	debug(LOG_NET, "Port mapping creation is in progress...");
	// Report the user-visible status once the discovery is finished.
	pmm.attach_callback(ipv4MappingRequest, [](std::string extIp, uint16_t extPort) // success callback
	{
		std::string msg = astringf(_("Port mapping opened external port: %u"), static_cast<unsigned>(extPort));
		msg += "\n";
		msg += astringf(_("Your external IP is: %s"), extIp.c_str());
		addConsoleMessage(msg.c_str(), DEFAULT_JUSTIFY, NOTIFY_MESSAGE);
	}, [](PortMappingDiscoveryStatus status) // failure callback
	{
		std::string msg;
		if (status == PortMappingDiscoveryStatus::TIMEOUT)
		{
			msg = _("Failed to create port mapping (timeout)");
		}
		else
		{
			msg = _("Failed to create port mapping");
		}
		msg += "\n";
		msg += astringf(_("Manually configure your router/firewall to open port %d!"), NETgetGameserverPort());
		addConsoleMessage(msg.c_str(), DEFAULT_JUSTIFY, NOTIFY_MESSAGE);
	});
}

void NETremRedirects()
{
	if (!ipv4MappingRequest)
	{
		return;
	}
	if (!PortMappingManager::instance().destroy_port_mapping(ipv4MappingRequest))
	{
		debug(LOG_ERROR, "Failed to remove IPv4 port mapping for the game. You must manually remove it from your router.");
		return;
	}
	debug(LOG_NET, "Removed port mapping for port %d (IPv4).", gameserver_port);
	ipv4MappingRequest = nullptr;
}

void NETinitPortMapping()
{
	if (!NetPlay.isPortMappingEnabled)
	{
		debug(LOG_INFO, "Automatic port mapping setup disabled by user.");
		return;
	}
	PortMappingManager::instance().init();
	NETaddRedirects();
}

// ////////////////////////////////////////////////////////////////////////
// setup stuff
int NETinit(ConnectionProviderType pt)
{
	debug(LOG_NET, "NETinit");
	NETlogEntry("NETinit!", SYNC_FLAG, selectedPlayer);
	NET_InitPlayers(true, true);

	ConnectionProviderRegistry::Instance().Register(pt);
	auto connProvider = ConnectionProviderRegistry::Instance().Get(pt);
	ASSERT_OR_RETURN(1, connProvider != nullptr, "Null connectionProvider");
	connProvider->initialize();
	PendingWritesManagerMap::instance().get(*connProvider).initialize(*connProvider);

	ASSERT(activeConnProvider == nullptr || activeConnProvider == connProvider,
		"Active connection provider is already set. Call NETshutdown() first!");
	activeConnProvider = connProvider;

	debug(LOG_NET, "NETPLAY: Init called, MORNIN'");

	wzAsyncExecOnMainThread([pt]() {
		const auto strPt = to_string(pt);
		std::string msg = astringf(_("Using %s network backend."), strPt.c_str());
		addConsoleMessage(msg.c_str(), DEFAULT_JUSTIFY, NOTIFY_MESSAGE);
	});

	// NOTE NetPlay.isPortMappingEnabled is already set in configuration.c!
	NetPlay.bComms = true;
	NetPlay.GamePassworded = false;
	NetPlay.ShowedMOTD = false;
	NetPlay.isHostAlive = false;
	NetPlay.HaveUpgrade = false;
	NetPlay.gamePassword[0] = '\0';
	NETstartLogging();

	NetPlay.MOTD.clear();
	NetPlay.ShowedMOTD = false;
	NetPlay.GamePassworded = false;
	memset(&sync_counter, 0x0, sizeof(sync_counter));	//clear counters

	return 0;
}

// ////////////////////////////////////////////////////////////////////////
// shutdown state related to the active connection
int NETshutdown()
{
	debug(LOG_NET, "NETshutdown");
	NETlogEntry("NETshutdown", SYNC_FLAG, selectedPlayer);
	if (NetPlay.bComms && NetPlay.isPortMappingEnabled)
	{
		NETremRedirects();
		PortMappingManager::instance().shutdown();
	}
	NETstopLogging();
	NETpermissionsShutdown();
	NetPlay.MOTD.clear();
	NETdeleteQueue();

	activeConnProvider = nullptr;

	// Reset net usage statistics.
	nStats = nZeroStats;
	nStatsLastSec = nZeroStats;
	nStatsSecondLastSec = nZeroStats;

	return 0;
}

// ////////////////////////////////////////////////////////////////////////
// shutdown netplay (to be called at app shutdown only)
bool netplayShutDown()
{
	NETshutdown();

	PendingWritesManagerMap::instance().Shutdown();
	ConnectionProviderRegistry::Instance().Shutdown();
	return true;
}

// ////////////////////////////////////////////////////////////////////////
//close the open game..
int NETclose()
{
	unsigned int i;

	// reset flag
	NetPlay.ShowedMOTD = false;
	NEThaltJoining();

	debug(LOG_NET, "Terminating sockets.");

	NetPlay.isHost = false;
	server_not_there = false;
	allow_joining = false;

	for (i = 0; i < MAX_CONNECTED_PLAYERS; i++)
	{
		if (connected_bsocket[i])
		{
			debug(LOG_NET, "Closing connected_bsocket[%u], %p", i, static_cast<void *>(connected_bsocket[i]));
			connected_bsocket[i]->close();
			connected_bsocket[i] = nullptr;
		}
		NET_DestroyPlayer(i, true);
	}

	if (tmp_socket_set)
	{
		debug(LOG_NET, "Freeing tmp_socket_set %p", static_cast<void *>(tmp_socket_set));
		delete tmp_socket_set;
		tmp_socket_set = nullptr;
	}

	for (i = 0; i < MAX_TMP_SOCKETS; i++)
	{
		if (tmp_socket[i])
		{
			// FIXME: need SocketSet_DelSocket() as well, socket_set or tmp_socket_set?
			debug(LOG_NET, "Closing tmp_socket[%d] %p", i, static_cast<void *>(tmp_socket[i]));
			tmp_socket[i]->close();
			tmp_socket[i] = nullptr;
		}
	}

	if (client_socket_set)
	{
		if (bsocket)
		{
			client_socket_set->remove(bsocket);
		}
		debug(LOG_NET, "Freeing socket_set %p", static_cast<void *>(client_socket_set));
		delete client_socket_set;
		client_socket_set = nullptr;
	}
	else if (server_socket_set)
	{
		debug(LOG_NET, "Freeing socket_set %p", static_cast<void*>(server_socket_set));
		delete server_socket_set;
		server_socket_set = nullptr;
	}
	if (server_listen_socket)
	{
		debug(LOG_NET, "Closing server_listen_socket %p", static_cast<void *>(server_listen_socket));
		delete server_listen_socket;
		server_listen_socket = nullptr;
	}
	if (bsocket)
	{
		debug(LOG_NET, "Closing bsocket %p", static_cast<void *>(bsocket));
		bsocket->close();
		bsocket = nullptr;
	}

	playerManagementRecord.clear();

	return 0;
}


// ////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////
// Send and Recv functions

// ////////////////////////////////////////////////////////////////////////
// return bytes of data sent recently.
size_t NETgetStatistic(NetStatisticType type, bool sent, bool isTotal)
{
	size_t Statistic::*statisticType = sent ? &Statistic::sent : &Statistic::received;
	Statistic NETSTATS::*statsType;
	switch (type)
	{
	case NetStatisticRawBytes:          statsType = &NETSTATS::rawBytes;          break;
	case NetStatisticUncompressedBytes: statsType = &NETSTATS::uncompressedBytes; break;
	case NetStatisticPackets:           statsType = &NETSTATS::packets;           break;
	default: ASSERT(false, " "); return 0;
	}

	int time = wzGetTicks();
	if ((unsigned)(time - nStatsLastUpdateTime) >= (unsigned)GAME_TICKS_PER_SEC)
	{
		nStatsLastUpdateTime = time;
		nStatsSecondLastSec = nStatsLastSec;
		nStatsLastSec = nStats;
	}

	if (isTotal)
	{
		return nStats.*statsType.*statisticType;
	}
	return nStatsLastSec.*statsType.*statisticType - nStatsSecondLastSec.*statsType.*statisticType;
}

static std::set<uint32_t> netSendPendingDisconnectPlayerIndexes;

void NETsendProcessDelayedActions()
{
	if (netSendPendingDisconnectPlayerIndexes.empty())
	{
		return;
	}

	// "consume" the netSendPendingDisconnectPlayerIndexes up-front, and do *not* reference it again (as NETplayerClientsDisconnect may lead to calls that mutate it)
	std::set<uint32_t> pendingDisconnectPlayers = netSendPendingDisconnectPlayerIndexes;
	netSendPendingDisconnectPlayerIndexes.clear();

	for (auto player : pendingDisconnectPlayers)
	{
		if (player >= MAX_CONNECTED_PLAYERS)
		{
			ASSERT(player < MAX_CONNECTED_PLAYERS, "Invalid player: %" PRIu32, player);
			continue;
		}
		NETlogEntry("client disconnect?", SYNC_FLAG, player);
	}

	NETplayerClientsDisconnect(pendingDisconnectPlayers);
}

// ////////////////////////////////////////////////////////////////////////
// Send a message to a player, option to guarantee message
bool NETsend(NETQUEUE queue, NetMessage const& message)
{
	uint8_t player = queue.index;

	if (!NetPlay.bComms)
	{
		return true;
	}

	IClientConnection** sockets = connected_bsocket;
	bool isTmpQueue = false;
	switch (queue.queueType)
	{
	case QUEUE_BROADCAST:
		ASSERT_OR_RETURN(false, player == NET_ALL_PLAYERS, "Wrong queue index.");
		break;
	case QUEUE_NET:
		ASSERT_OR_RETURN(false, player < MAX_CONNECTED_PLAYERS, "Wrong queue index.");
		break;
	case QUEUE_TMP:
		sockets = tmp_socket;
		isTmpQueue = true;

		ASSERT_OR_RETURN(false, player < MAX_TMP_SOCKETS && NetPlay.isHost, "Wrong queue index.");
		break;
	default:
		ASSERT_OR_RETURN(false, false, "Wrong queue type.");
	}

	if (NetPlay.isHost)
	{
		int firstPlayer = player == NET_ALL_PLAYERS ? 0                         : player;
		int lastPlayer  = player == NET_ALL_PLAYERS ? MAX_CONNECTED_PLAYERS - 1 : player;
		for (player = firstPlayer; player <= lastPlayer; ++player)
		{
			// We are the host, send directly to player.
			if (sockets[player] != nullptr && player != queue.exclude)
			{
				const auto& rawData = message.rawData();
				if (rawData.empty())
				{
					debug(LOG_FATAL, "Failed to allocate raw data (message type: %" PRIu8 ", player: %d)", message.type(), player);
					abort();
				}
				uint8_t msgType = message.type();
				ssize_t rawLen = rawData.size();
				size_t compressedRawLen;
				const auto writeResult = sockets[player]->writeAll(rawData.data(), rawLen, &compressedRawLen);
				const auto res = writeResult.value_or(SOCKET_ERROR);

				if (res == rawLen)
				{
					nStats.rawBytes.sent          += compressedRawLen;
					nStats.uncompressedBytes.sent += rawLen;
					nStats.packets.sent           += 1;
				}
				else if (res == SOCKET_ERROR)
				{
					const auto writeErrMsg = writeResult.error().message();
					// Write error, most likely client disconnect.
					debug(LOG_ERROR, "Failed to send message (type: %" PRIu8 ", rawLen: %zu, compressedRawLen: %zu) to %" PRIu8 ": %s",
						msgType, rawLen, compressedRawLen, player, writeErrMsg.c_str());
					if (!isTmpQueue)
					{
						netSendPendingDisconnectPlayerIndexes.insert(player);
					}
				}
			}
		}
		return true;
	}
	else if (player == NetPlay.hostPlayer)
	{
		// We are a client, send directly to player, who happens to be the host.
		if (bsocket && NetPlay.isHostAlive)
		{
			const auto& rawData = message.rawData();
			ssize_t rawLen = rawData.size();
			size_t compressedRawLen;
			const auto writeResult = bsocket->writeAll(rawData.data(), rawLen, &compressedRawLen);
			const auto res = writeResult.value_or(SOCKET_ERROR);

			if (res == rawLen)
			{
				nStats.rawBytes.sent          += compressedRawLen;
				nStats.uncompressedBytes.sent += rawLen;
				nStats.packets.sent           += 1;
			}
			else if (res == SOCKET_ERROR)
			{
				const auto writeErrMsg = writeResult.error().message();
				// Write error, most likely host disconnect.
				debug(LOG_ERROR, "Failed to send message: %s", writeErrMsg.c_str());
				debug(LOG_ERROR, "Host connection was broken, socket %p.", static_cast<void *>(bsocket));
				NETlogEntry("write error--client disconnect.", SYNC_FLAG, NetPlay.hostPlayer);
				NETclientHandleHostDisconnected();
			}

			return res == rawLen;
		}
	}
	else
	{
		// We are a client and can't send the data directly, ask the host to send the data to the player.
		uint8_t sender = selectedPlayer;
		auto w = NETbeginEncode(NETnetQueue(NetPlay.hostPlayer), NET_SEND_TO_PLAYER);
		NETuint8_t(w, sender);
		NETuint8_t(w, player);
		NETnetMessage(w, message);
		NETend(w);
		return true;
	}

	return false;
}

static void NETcloseTempSocket(unsigned int i)
{
	std::string joinerPublicKeyB64;
	std::string joinerName;

	if (tmp_connectState[i].connectState == TmpSocketInfo::TmpConnectState::PendingAsyncApproval
		|| tmp_connectState[i].connectState == TmpSocketInfo::TmpConnectState::ProcessJoin)
	{
		// If there's any chance we may have issued an async join approval request, ensure we issue a joinFailed event
		// WZEVENT: joinFailed: <b64pubkey> <b64name> [spec|play] <reason>
		const auto& joinRequestInfo = tmp_connectState[i].receivedJoinInfo;
		joinerPublicKeyB64 = base64Encode(joinRequestInfo.identity.toBytes(EcKey::Public));
		joinerName = joinRequestInfo.name;
		std::string joinerNameB64 = base64Encode(std::vector<unsigned char>(joinerName.begin(), joinerName.end()));
		wz_command_interface_output("WZEVENT: joinFailed: %s %s %s %s\n", joinerPublicKeyB64.c_str(), joinerNameB64.c_str(), (joinRequestInfo.playerType == NET_JOIN_SPECTATOR) ? "spec" : "play", "full");
	}

	std::string rIP = tmp_socket[i]->textAddress();
	tmp_socket_set->remove(tmp_socket[i]);
	tmp_socket[i]->close();
	tmp_socket[i] = nullptr;
	tmp_connectState[i].reset();
	auto it = tmp_pendingIPs.find(rIP);
	if (it != tmp_pendingIPs.end())
	{
		if (it->second > 1)
		{
			it->second--;
		}
		else
		{
			tmp_pendingIPs.erase(it);
		}
	}
	else
	{
		debug(LOG_INFO, "Did not find in pending IPs list: (IP: %s, Identity: %s, Name: %s)", rIP.c_str(), joinerPublicKeyB64.c_str(), joinerName.c_str());
	}
}

static void NETclientHandleHostDisconnected()
{
	ASSERT_OR_RETURN(, !NetPlay.isHost, "Should only be called by clients!");
	// NOTE: Do *not* close the socket or connection group here, as this is called from both send and receiving functions
	// And if this was detected on a send, we still might have buffered data to read!
	ASSERT(NetPlay.hostPlayer < NetPlay.players.size(), "Invalid NetPlay.hostPlayer: %" PRIu32, NetPlay.hostPlayer);
	NetPlay.players[NetPlay.hostPlayer].heartbeat = false;	// mark host as dead
	//Game is pretty much over --should just end everything when HOST dies.
	NetPlay.isHostAlive = false;
}

void NETflush()
{
	if (!NetPlay.bComms)
	{
		return;
	}

	NETflushGameQueues();

	size_t compressedRawLen = 0;
	if (NetPlay.isHost)
	{
		// Preliminary check to see if any player sockets are still valid.
		std::set<uint32_t> invalidPlayerIndices;
		for (int player = 0; player < MAX_CONNECTED_PLAYERS; ++player)
		{
			if (connected_bsocket[player] != nullptr && !connected_bsocket[player]->isValid())
			{
				invalidPlayerIndices.emplace(player);
			}
		}
		// Gracefully handle disconnected players.
		NETplayerClientsDisconnect(invalidPlayerIndices);

		for (int player = 0; player < MAX_CONNECTED_PLAYERS; ++player)
		{
			// We are the host, send directly to player.
			if (!invalidPlayerIndices.count(player) && connected_bsocket[player] != nullptr)
			{
				if (!connected_bsocket[player]->flush(&compressedRawLen).has_value())
				{
					invalidPlayerIndices.emplace(player);
					continue;
				}
				nStats.rawBytes.sent += compressedRawLen;
			}
		}

		// Once again, if any connected client sockets had problems during flush(), consider them disconnected and handle appropriately.
		NETplayerClientsDisconnect(invalidPlayerIndices);

		for (int player = 0; player < MAX_TMP_SOCKETS; ++player)
		{
			// We are the host, send directly to player.
			if (tmp_socket[player] != nullptr)
			{
				if (!tmp_socket[player]->isValid() || !tmp_socket[player]->flush(&compressedRawLen).has_value())
				{
					debug(LOG_NET, "Failed to flush temporary socket for player slot %d", player);
					NETcloseTempSocket(player);
					continue;
				}
				nStats.rawBytes.sent += compressedRawLen;
			}
		}
	}
	else
	{
		if (bsocket != nullptr && NetPlay.isHostAlive)
		{
			if (!bsocket->isValid() || !bsocket->flush(&compressedRawLen).has_value())
			{
				debug(LOG_NET, "Failed to flush socket for host. Host probably disconnected.");
				NETlogEntry("flush error--client disconnect.", SYNC_FLAG, NetPlay.hostPlayer);
				NETclientHandleHostDisconnected();
				return;
			}
			nStats.rawBytes.sent += compressedRawLen;
		}
	}
}

// Player index swapping

// Warning: This should be used with care, and generally should not be called directly.
// Use higher-level functions like NETmovePlayerToSpectatorOnlySlot & NETrequestSpectatorToPlay instead.
static bool swapPlayerIndexes(uint32_t playerIndexA, uint32_t playerIndexB)
{
	ASSERT_OR_RETURN(false, ingame.localJoiningInProgress, "Only supported in lobby, before game starts");
	ASSERT_OR_RETURN(false, playerIndexA < MAX_CONNECTED_PLAYERS, "playerIndexA out of bound: %" PRIu32 "", playerIndexA);
	ASSERT_OR_RETURN(false, playerIndexB < MAX_CONNECTED_PLAYERS, "playerIndexB out of bound: %" PRIu32 "", playerIndexB);
	ASSERT_OR_RETURN(false, playerIndexA != NetPlay.hostPlayer && playerIndexA != NetPlay.hostPlayer && playerIndexB != NetPlay.hostPlayer && playerIndexB != NetPlay.hostPlayer, "Can't swap host player index: (index A: %" PRIu32 ", index B: %" PRIu32 ")", playerIndexA, playerIndexB);

	// Send the NET_SWAPPING_PLAYER_INDEX message *first*
	auto w = NETbeginEncode(NETbroadcastQueue(), NET_PLAYER_SWAP_INDEX);
	NETuint32_t(w, playerIndexA);
	NETuint32_t(w, playerIndexB);
	NETend(w);

	// Then swap the networking stuff for these slots
	std::swap(connected_bsocket[playerIndexA], connected_bsocket[playerIndexB]);
	// should be no need to call SocketSet_AddSocket, since should already be in the socket_set
	NETswapQueues(NETnetQueue(playerIndexA), NETnetQueue(playerIndexB));

	// Backup the old NETPLAY PLAYERS data
	std::array<PLAYER, 2> playersData = {std::move(NetPlay.players[playerIndexA]), std::move(NetPlay.players[playerIndexB])};

	// Instead of calling clearPlayer() which has all kinds of unintended effects,
	// hmmm...
	std::array<uint32_t, 2> playerIndexes = {playerIndexA, playerIndexB};
	for (auto playerIndex : playerIndexes)
	{
		// From MultiPlayerLeave()
		//  From clearPlayer() - this is needed to disconnect PlayerReferences so, for example, old chat messages are still associated with the proper player
		NetPlay.playerReferences[playerIndex]->disconnect();
		NetPlay.playerReferences[playerIndex] = std::make_shared<PlayerReference>(playerIndex);

		//
//		if (playerIndex < MAX_PLAYERS)
//		{
//			playerVotes[playerIndex] = 0;
//		}
	}

	// Swap the player multistats / identity info
	swapPlayerMultiStatsLocal(playerIndexA, playerIndexB);

	// Swap the NetPlay PLAYER entries
	NetPlay.players[playerIndexB] = std::move(playersData[0]);
	NetPlay.players[playerIndexA] = std::move(playersData[1]);
	// Just like changePosition(), we should *preserve* the team and "position" from the original index
	std::swap(NetPlay.players[playerIndexA].position, NetPlay.players[playerIndexB].position);
	std::swap(NetPlay.players[playerIndexA].team, NetPlay.players[playerIndexB].team);
	// And also swap spectator flag!
	std::swap(NetPlay.players[playerIndexA].isSpectator, NetPlay.players[playerIndexB].isSpectator);
	std::swap(NetPlay.players[playerIndexA].colour, NetPlay.players[playerIndexB].colour); // And the color!
	// (Essentially all of the above are "slot-associated" more than "player-associated" properties, and so should stay with the slot)

	// Swap certain ingame player-associated entries
	std::swap(ingame.PingTimes[playerIndexA], ingame.PingTimes[playerIndexB]);
	std::swap(ingame.LagCounter[playerIndexA], ingame.LagCounter[playerIndexB]);
	std::swap(ingame.DesyncCounter[playerIndexA], ingame.DesyncCounter[playerIndexB]);
	std::swap(ingame.VerifiedIdentity[playerIndexA], ingame.VerifiedIdentity[playerIndexB]);
	std::swap(ingame.JoiningInProgress[playerIndexA], ingame.JoiningInProgress[playerIndexB]);
	std::swap(ingame.PendingDisconnect[playerIndexA], ingame.PendingDisconnect[playerIndexB]);
	std::swap(ingame.DataIntegrity[playerIndexA], ingame.DataIntegrity[playerIndexB]);
	std::swap(ingame.hostChatPermissions[playerIndexA], ingame.hostChatPermissions[playerIndexB]);

	std::swap(ingame.joinTimes[playerIndexA], ingame.joinTimes[playerIndexB]);
	std::swap(ingame.lastReadyTimes[playerIndexA], ingame.lastReadyTimes[playerIndexB]);
	std::swap(ingame.lastNotReadyTimes[playerIndexA], ingame.lastNotReadyTimes[playerIndexB]);
	std::swap(ingame.secondsNotReady[playerIndexA], ingame.secondsNotReady[playerIndexB]);
	std::swap(ingame.playerLeftGameTime[playerIndexA], ingame.playerLeftGameTime[playerIndexB]);

	std::swap(ingame.lastSentPlayerDataCheck2[playerIndexA], ingame.lastSentPlayerDataCheck2[playerIndexB]);
	std::swap(ingame.muteChat[playerIndexA], ingame.muteChat[playerIndexB]);
	playerSpamMuteNotifyIndexSwap(playerIndexA, playerIndexB);
	multiSyncPlayerSwap(playerIndexA, playerIndexB);

	// Ensure we filter messages appropriately waiting for the client ack *at each new index*
	if (NetPlay.players[playerIndexA].allocated)
	{
		NET_waitingForIndexChangeAckSince.at(playerIndexA) = realTime;
	}
	if (NetPlay.players[playerIndexB].allocated)
	{
		NET_waitingForIndexChangeAckSince.at(playerIndexB) = realTime;
	}

	// Fix up any AI players - if they get moved to a spectator slot, get rid of the AI
	for (auto playerIndex : playerIndexes)
	{
		if (!NetPlay.players[playerIndex].allocated
			&& NetPlay.players[playerIndex].ai >= 0
			&& (NetPlay.players[playerIndex].isSpectator || playerIndex > MAX_PLAYERS))
		{
			// remove the AI
			ASSERT(playerIndex != PLAYER_FEATURE, "Not expecting to see PLAYER_FEATURE here!");
			NetPlay.players[playerIndex].difficulty =  AIDifficulty::DISABLED;
			NetPlay.players[playerIndex].ai = AI_OPEN;
			clearPlayerName(playerIndex);
		}
		if (!NetPlay.players[playerIndex].allocated && NetPlay.players[playerIndex].ai < 0)
		{
			ASSERT(NetPlay.players[playerIndex].difficulty == AIDifficulty::DISABLED, "Unexpected difficulty (%d) for player (%d)", (int)NetPlay.players[playerIndex].difficulty, playerIndex);
		}

		if (NetPlay.players[playerIndex].allocated
			&& playerIndex < MAX_PLAYERS)
		{
			if (NetPlay.players[playerIndex].difficulty != AIDifficulty::HUMAN)
			{
				debug(LOG_INFO, "Fixing up human difficulty for player: %d", playerIndex);
				NetPlay.players[playerIndex].difficulty = AIDifficulty::HUMAN;
			}
		}
	}

	if (!NetPlay.players[playerIndexA].allocated || !NetPlay.players[playerIndexB].allocated)
	{
		// Recalculate NetPlay.playercount (etc), as it may have changed
		NETfixPlayerCount();
	}

	return true;
}

static inline bool _NET_isSpectatorOnlySlot(UDWORD playerIdx)
{
	ASSERT_OR_RETURN(false, playerIdx < NetPlay.players.size(), "Invalid playerIdx: %" PRIu32 "", playerIdx);
	return playerIdx >= MAX_PLAYERS || NetPlay.players[playerIdx].position >= game.maxPlayers;
}

static optional<uint32_t> _NET_findSpectatorSlotToOpen()
{
	for (uint32_t i = MAX_PLAYER_SLOTS; i < MAX_CONNECTED_PLAYERS; ++i)
	{
		if (!_NET_isSpectatorOnlySlot(i))
		{
			continue;
		}
		if (NetPlay.players[i].allocated || NetPlay.players[i].isSpectator)
		{
			continue;
		}
		if (game.mapHasScavengers && NetPlay.players[i].position == scavengerSlot())
		{
			continue; // skip it
		}
		if (i == PLAYER_FEATURE)
		{
			continue; // skip it
		}

		return i;
	}
	return nullopt;
}

bool NETcanOpenNewSpectatorSlot()
{
	return _NET_findSpectatorSlotToOpen().has_value();
}

static optional<uint32_t> _NET_openNewSpectatorSlot_internal(bool broadcastUpdate)
{
	ASSERT_HOST_ONLY(return false);
	auto newSpecSlot = _NET_findSpectatorSlotToOpen();
	if (!newSpecSlot.has_value())
	{
		return nullopt;
	}

	uint32_t i = newSpecSlot.value();
	NetPlay.players[i].ai = AI_OPEN;
	NetPlay.players[i].isSpectator = true;
	// common code
	NetPlay.players[i].difficulty = AIDifficulty::DISABLED; // disable AI for this slot
	if (broadcastUpdate)
	{
		NETBroadcastPlayerInfo(i);
		netPlayersUpdated = true;
	}
	return i;
}

bool NETopenNewSpectatorSlot()
{
	ASSERT_HOST_ONLY(return false);
	return _NET_openNewSpectatorSlot_internal(true).has_value();
}

bool NETmovePlayerToSpectatorOnlySlot(uint32_t playerIdx, bool hostOverride /*= false*/)
{
	ASSERT_HOST_ONLY(return false);
	ASSERT_OR_RETURN(false, playerIdx < MAX_CONNECTED_PLAYERS, "playerIdx out of bounds: %" PRIu32 "", playerIdx);
	// Verify it's a human player
	ASSERT_OR_RETURN(false, isHumanPlayer(playerIdx) && !NetPlay.players[playerIdx].isSpectator, "playerIdx is not a currently-connected human player: %" PRIu32 "", playerIdx);

	// Try to grab a new spectator-only slot index
	optional<uint32_t> availableSpectatorIndex = NET_FindOpenSlotForPlayer(false, true);
	if (!availableSpectatorIndex.has_value() && hostOverride)
	{
		// Attempt to open a new spectator slot just for this player
		availableSpectatorIndex = _NET_openNewSpectatorSlot_internal(false);
	}
	if (!availableSpectatorIndex.has_value())
	{
		debug(LOG_ERROR, "No available spectator slots to move player %" PRIu32 " to", playerIdx);
		return false;
	}

	// Backup the player's identity for later recording
	auto playerPublicKeyIdentity = getTruePlayerIdentity(playerIdx).identity.toBytes(EcKey::Privacy::Public);

	// Swap the player indexes
	if (!swapPlayerIndexes(playerIdx, availableSpectatorIndex.value()))
	{
		debug(LOG_ERROR, "Failed to swap player indexes: %" PRIu32 ", %" PRIu32 "", playerIdx, availableSpectatorIndex.value());
		return false;
	}
	ASSERT(NetPlay.players[availableSpectatorIndex.value()].isSpectator, "New slot doesn't have spectator set??");

	playerManagementRecord.movedPlayerToSpectators(NetPlay.players[availableSpectatorIndex.value()], playerPublicKeyIdentity, hostOverride);

	if (wz_command_interface_enabled())
	{
		uint32_t newSpecIdx = availableSpectatorIndex.value();
		const auto& outputIdentity = getOutputPlayerIdentity(newSpecIdx);
		std::string playerPublicKeyB64 = base64Encode(outputIdentity.toBytes(EcKey::Public));
		std::string playerIdentityHash = outputIdentity.publicHashString();
		std::string playerVerifiedStatus = (ingame.VerifiedIdentity[newSpecIdx]) ? "V" : "?";
		std::string playerName = getPlayerName(newSpecIdx);
		std::string playerNameB64 = base64Encode(std::vector<unsigned char>(playerName.begin(), playerName.end()));
		wz_command_interface_output("WZEVENT: movedPlayerToSpec: %" PRIu32 " -> %" PRIu32 " %s %s %s %s %s %s\n", playerIdx, newSpecIdx, playerPublicKeyB64.c_str(), playerIdentityHash.c_str(), playerVerifiedStatus.c_str(), playerNameB64.c_str(), NetPlay.players[newSpecIdx].IPtextAddress, hostOverride?"host":"user");
	}

	// Broadcast the swapped player info
	NETBroadcastTwoPlayerInfo(playerIdx, availableSpectatorIndex.value());

	return true;
}

static bool wasAlreadyMovedToSpectatorsByHost(uint32_t playerIdx)
{
	return playerManagementRecord.hostMovedPlayerToSpectators(NetPlay.players[playerIdx].IPtextAddress)
		|| playerManagementRecord.hostMovedPlayerToSpectators(getTruePlayerIdentity(playerIdx).identity.toBytes(EcKey::Privacy::Public));
}

SpectatorToPlayerMoveResult NETmoveSpectatorToPlayerSlot(uint32_t playerIdx, optional<uint32_t> newPlayerIdx, bool hostOverride /*= false*/)
{
	ASSERT_HOST_ONLY(return SpectatorToPlayerMoveResult::FAILED);
	ASSERT_OR_RETURN(SpectatorToPlayerMoveResult::FAILED, playerIdx < MAX_CONNECTED_PLAYERS, "playerIdx out of bounds: %" PRIu32 "", playerIdx);
	ASSERT_OR_RETURN(SpectatorToPlayerMoveResult::FAILED, newPlayerIdx.value_or(0) < MAX_CONNECTED_PLAYERS, "newPlayerIdx out of bounds: %" PRIu32 "", newPlayerIdx.value_or(0));
	ASSERT_OR_RETURN(SpectatorToPlayerMoveResult::FAILED, !newPlayerIdx.has_value() || newPlayerIdx.value() != NetPlay.hostPlayer, "newPlayerIdx cannot be host player: %" PRIu32 "", newPlayerIdx.value_or(0));
	// Verify it's a human player
	ASSERT_OR_RETURN(SpectatorToPlayerMoveResult::FAILED, isHumanPlayer(playerIdx) && NetPlay.players[playerIdx].isSpectator, "playerIdx is not a currently-connected spectator: %" PRIu32 "", playerIdx);

	bool previousPlayersShouldCheckReadyValue = multiplayPlayersShouldCheckReady();

	// Check if the host has moved this player to a spectator before, if so deny (unless the *host* is the one triggering the move)
	if (!hostOverride && wasAlreadyMovedToSpectatorsByHost(playerIdx))
	{
		return SpectatorToPlayerMoveResult::FAILED;
	}

	if (!newPlayerIdx.has_value())
	{
		// Attempt to find an open slot
		newPlayerIdx = NET_FindOpenSlotForPlayer(false, false);
		if (!newPlayerIdx.has_value())
		{
			return SpectatorToPlayerMoveResult::NEEDS_SLOT_SELECTION;
		}
	}

	// Backup the spectator's identity for later recording
	auto spectatorPublicKeyIdentity = getTruePlayerIdentity(playerIdx).identity.toBytes(EcKey::Privacy::Public);

	// Swap the player indexes
	if (!swapPlayerIndexes(playerIdx, newPlayerIdx.value()))
	{
		debug(LOG_ERROR, "Failed to swap player indexes: %" PRIu32 ", %" PRIu32 "", playerIdx, newPlayerIdx.value());
		return SpectatorToPlayerMoveResult::FAILED;
	}
	ASSERT(!NetPlay.players[newPlayerIdx.value()].isSpectator, "New slot should not be a spectator??");

	playerManagementRecord.movedSpectatorToPlayers(NetPlay.players[newPlayerIdx.value()], spectatorPublicKeyIdentity, hostOverride);

	if (wz_command_interface_enabled())
	{
		const auto& identity = getOutputPlayerIdentity(newPlayerIdx.value());
		std::string playerPublicKeyB64 = base64Encode(identity.toBytes(EcKey::Public));
		std::string playerIdentityHash = identity.publicHashString();
		std::string playerVerifiedStatus = (ingame.VerifiedIdentity[newPlayerIdx.value()]) ? "V" : "?";
		std::string playerName = getPlayerName(newPlayerIdx.value());
		std::string playerNameB64 = base64Encode(std::vector<unsigned char>(playerName.begin(), playerName.end()));
		wz_command_interface_output("WZEVENT: movedSpecToPlayer: %" PRIu32 " -> %" PRIu32 " %s %s %s %s %s\n", playerIdx, newPlayerIdx.value(), playerPublicKeyB64.c_str(), playerIdentityHash.c_str(), playerVerifiedStatus.c_str(), playerNameB64.c_str(), NetPlay.players[newPlayerIdx.value()].IPtextAddress);
	}

	// Broadcast the swapped player info
	NETBroadcastTwoPlayerInfo(playerIdx, newPlayerIdx.value());

	handlePossiblePlayersShouldCheckReadyChange(previousPlayersShouldCheckReadyValue);

	return SpectatorToPlayerMoveResult::SUCCESS;
}

static inline bool NETFilterMessageWhileSwappingPlayer(uint8_t sender, uint8_t type)
{
	if (!NetPlay.isHost)
	{
		return false; // only host filters these messages
	}

	if (sender == NetPlay.hostPlayer)
	{
		return false; // never filter host messages
	}

	if (static_cast<size_t>(sender) >= NET_waitingForIndexChangeAckSince.size() || !NET_waitingForIndexChangeAckSince.at(sender).has_value())
	{
		return false; // no filtering - not waiting for player to acknowledge index change
	}

	#define INDEX_CHANGE_ACK_TIMEOUT (5 * GAME_TICKS_PER_SEC)
	if ((realTime - NET_waitingForIndexChangeAckSince.at(sender).value_or(realTime)) > INDEX_CHANGE_ACK_TIMEOUT)
	{
		// this client did not acknowledge the player index change before the timeout - kick them
		char msg[256] = {'\0'};
		if (NETplayerHasConnection(sender) || NetPlay.players[sender].allocated)
		{
			ssprintf(msg, "Auto-kicking player %u, did not ack player index change within required timeframe.", (unsigned int)sender);
			sendInGameSystemMessage(msg);
			debug(LOG_INFO, "Client (player: %u) failed to ack player index swap (ignoring message type: %" PRIu8 ")", sender, type);
			kickPlayer(sender, _("Client failed to ack player index swap"), ERROR_INVALID, false);
		}
		return true; // filter original message, of course
	}

	// Filter certain net messages if player index swap is in progress (until player acknowledges swap)

	switch (type)
	{
	case NET_TEXTMSG:
	case NET_QUICK_CHAT_MSG:
		// Just send a message to the player that this text message was undelivered and to try again - it's easier and this should be quite rare
		{
			WzQuickChatTargeting targeting;
			targeting.specificPlayers.insert(sender);
			sendQuickChat(WzQuickChatMessage::INTERNAL_MSG_DELIVERY_FAILURE_TRY_AGAIN, selectedPlayer, targeting);
			return true; // filter / ignore
		}
	case NET_VOTE:
		// POSSIBLE TODO: Send the player a new VOTE_REQUEST so they can send a new vote? (after they ack the swap)
		return true; // filter / ignore
	case NET_PLAYERNAME_CHANGEREQUEST:	///< non-host human player is changing their name.
		// We can ignore if we force the player to re-send their name when they change slots
		return true; // filter / ignore

	// Client messages to ignore while waiting for a swap player ACK
	// (because they may contain the old player index, and also the necessary messages will be resent after the ack)
	case NET_PING:                       // For now, just drop it - until the player responds with the ack
	case NET_PLAYER_STATS:
	case NET_COLOURREQUEST:              ///< player requests a colour change.
	case NET_FACTIONREQUEST:             ///< player requests a colour change.
	case NET_TEAMREQUEST:                ///< request team membership
	case NET_READY_REQUEST:              ///< player ready to start an mp game
	case NET_POSITIONREQUEST:            ///< position in GUI player list
	case NET_DATA_CHECK:                 ///< Data integrity check
	case NET_DATA_CHECK2:
		return true; // filter / ignore

	// one slot / index change at a time...
	case NET_PLAYER_SLOTTYPE_REQUEST:
		return true; // filter / ignore

	// client messages to be processed normally
	case NET_FILE_REQUESTED:             ///< Player has requested a file (map/mod/?)
	case NET_FILE_CANCELLED:             ///< Player cancelled a file request
		return false; // process normally (do *not* filter)

	// host-only messages
	case NET_OPTIONS:                    ///< welcome a player to a game.
	case NET_KICK:                       ///< kick a player .
	case NET_FIREUP:                     ///< campaign game has started, we can go too.. Shortcut message, not to be used in dmatch.
	case NET_PLAYER_INFO:                ///< basic player info
	case NET_PLAYER_JOINED:              ///< notice about player joining
	case NET_PLAYER_LEAVING:             ///< A player is leaving, (nicely)
	case NET_PLAYER_DROPPED:             ///< notice about player dropped / disconnected
	case NET_GAME_FLAGS:                 ///< game flags
	case NET_HOST_DROPPED:               ///< Host has dropped
	case NET_FILE_PAYLOAD:               ///< sending file to the player that needs it
	case NET_VOTE_REQUEST:               ///< Setup a vote popup
	case NET_PLAYER_SWAP_INDEX:
	case NET_HOST_CONFIG:
		ASSERT(false, "Received unexpected host-only message (%" PRIu8 ") from sender: %" PRIu8 "", type, sender);
		break;

	// only possible with initial join
	case NET_JOIN:                       ///< join a game
	case NET_ACCEPTED:                   ///< accepted into game
	case NET_REJECTED:                   ///< nope, you can't join
		ASSERT(false, "Received unexpected initial-join message (%" PRIu8 ") from sender: %" PRIu8 "", type, sender);
		break;

	// should only be possible once game has started
	case NET_PLAYERRESPONDING:           ///< computer that sent this is now playing warzone!
	case NET_AITEXTMSG:                  ///< chat between AIs
	case NET_BEACONMSG:                  ///< place beacon
	case NET_SHARE_GAME_QUEUE:           ///< Message contains a game message, which should be inserted into a queue.
	case NET_DEBUG_SYNC:                 ///< Synch error messages, so people don't have to use pastebin.
	case NET_SPECTEXTMSG:                ///< chat between spectators
	case NET_TEAM_STRATEGY:              ///< Player is sending an updated strategy notice to team members
		break;

	// just process normally
	case NET_SEND_TO_PLAYER:             ///< Non-host clients aren't directly connected to each other, so they talk via the host using these messages.
		return false; // process normally (do *not* filter)

	case NET_SECURED_NET_MESSAGE:        ///< This just wraps another message, so permit this wrapper message
		return false; // process normally (do *not* filter)

	case NET_PLAYER_SWAP_INDEX_ACK:
		// **MUST** be permitted
		return false; // process normally (do *not* filter)

	default:
		// just process normally
		break;
	}

	return false;
}

static void cmdInterfaceLogChatMsgInternal(const NetworkTextMessage& message, const char* log_prefix, optional<std::string> _senderPublicKeyB64 = nullopt)
{
	if (!NetPlay.isHost || !wz_command_interface_enabled() || (NetPlay.hostPlayer < MAX_PLAYER_SLOTS))
	{
		return;
	}

	if (message.sender < 0)
	{
		// for now, skip system messages
		return;
	}

	ASSERT_OR_RETURN(, message.sender < MAX_CONNECTED_PLAYERS, "Invalid message.sender (%d)", message.sender);

	const auto& identity = getOutputPlayerIdentity(message.sender);
	std::string senderPublicKeyB64 = _senderPublicKeyB64.value_or(base64Encode(identity.toBytes(EcKey::Public)));
	std::string senderVerifiedStatus = (ingame.VerifiedIdentity[message.sender]) ? "V" : "?";
	std::string sendername = getPlayerName(message.sender);
	std::string sendername64 = base64Encode(std::vector<unsigned char>(sendername.begin(), sendername.end()));
	std::string messagetext = message.text;
	std::string messagetext64 = base64Encode(std::vector<unsigned char>(messagetext.begin(), messagetext.end()));
	wz_command_interface_output("%s: %i %s %s %s %s %s\n", log_prefix, message.sender, senderPublicKeyB64.c_str(), sendername64.c_str(), messagetext64.c_str(), senderVerifiedStatus.c_str(), NetPlay.players[message.sender].IPtextAddress);
}

// receiver may be a player index or NET_ALL_PLAYERS
static void LogChatMsg(uint8_t msgType, const NetMessage& message, uint8_t senderIdx, uint8_t receiver)
{
	if (!wz_command_interface_enabled())
	{
		return;
	}

	switch (msgType)
	{
		case NET_TEXTMSG:
		{
			NetworkTextMessage textMsg;
			if (textMsg.decode(message, senderIdx))
			{
				// Process & log
				cmdInterfaceLogChatMsgInternal(textMsg, "WZCHAT");
			}
			break;
		}
		case NET_SPECTEXTMSG:
		{
			auto r = MessageReader(message);
			if (auto specMsg = decodeSpecInGameTextMessage(r, senderIdx))
			{
				// Process & log
				cmdInterfaceLogChatMsgInternal(specMsg.value(), "WZCHAT");
			}
			break;
		}
	}
}

///////////////////////////////////////////////////////////////////////////
// Check if a message is a system message
static bool NETprocessSystemMessage(NETQUEUE playerQueue, uint8_t *type)
{
	if (*type == NET_SECURED_NET_MESSAGE)
	{
		if (!NETdecryptSecuredNetMessage(playerQueue, *type) || *type == NET_SECURED_NET_MESSAGE) // nested secured messages are not supported
		{
			// remove the invalid secured message, and return true to say we "handled it"
			debug(LOG_INFO, "Ignoring invalid secured message allegedly from player: %u", static_cast<unsigned>(playerQueue.index));
			NETpop(playerQueue);
			return true;
		}
	}

	if (NETFilterMessageWhileSwappingPlayer(playerQueue.index, *type))
	{
		NETpop(playerQueue);
		return true;
	}

	switch (*type)
	{
	case NET_SEND_TO_PLAYER:
		{
			uint8_t sender;
			uint8_t receiver;
			NetMessage* message = nullptr;
			auto r = NETbeginDecode(playerQueue, NET_SEND_TO_PLAYER);
			NETuint8_t(r, sender);
			NETuint8_t(r, receiver);
			NETnetMessage(r, &message);  // Must delete message later.
			std::unique_ptr<NetMessage> deleteLater(message);
			if (!NETend(r))
			{
				debug(LOG_ERROR, "Incomplete NET_SEND_TO_PLAYER.");
				break;
			}
			if (sender >= MAX_CONNECTED_PLAYERS || (receiver >= MAX_CONNECTED_PLAYERS && receiver != NET_ALL_PLAYERS))
			{
				debug(LOG_ERROR, "Bad NET_SEND_TO_PLAYER.");
				break;
			}
			if ((receiver == selectedPlayer || receiver == NET_ALL_PLAYERS) && playerQueue.index == NetPlay.hostPlayer)
			{
				// Message was sent to us via the host.
				if (sender != selectedPlayer)  // Make sure host didn't send us our own broadcast messages, which shouldn't happen anyway.
				{
					NETlogPacket(message->type(), static_cast<uint32_t>(message->rawData().size()), true);
					NETinsertMessageFromNet(NETnetQueue(sender), std::move(*message));
				}
			}
			else if (NetPlay.isHost && sender == playerQueue.index)
			{
				const auto msgType = message->type();
				if (((msgType == NET_OPTIONS
					  || msgType == NET_FIREUP
				      || msgType == NET_KICK
				      || msgType == NET_PLAYER_LEAVING
				      || msgType == NET_PLAYER_DROPPED
				      || msgType == NET_REJECTED
					  || msgType == NET_GAME_FLAGS
				      || msgType == NET_PLAYER_JOINED
					  || msgType == NET_PLAYER_INFO
					  || msgType == NET_FILE_PAYLOAD
					  || msgType == NET_PLAYER_SWAP_INDEX
					  || msgType == NET_HOST_CONFIG) && sender != NetPlay.hostPlayer)
				    ||
				    ((msgType == NET_HOST_DROPPED
				      || msgType == NET_FILE_REQUESTED
				      || msgType == NET_READY_REQUEST
				      || msgType == NET_TEAMREQUEST
				      || msgType == NET_COLOURREQUEST
				      || msgType == NET_POSITIONREQUEST
					  || msgType == NET_FACTIONREQUEST
				      || msgType == NET_FILE_CANCELLED
					  || msgType == NET_DATA_CHECK
				      || msgType == NET_JOIN
				      || msgType == NET_PLAYERNAME_CHANGEREQUEST
					  || msgType == NET_PLAYER_SWAP_INDEX_ACK) && receiver != NetPlay.hostPlayer)
					||
					((msgType == NET_PLAYER_SLOTTYPE_REQUEST
					  || msgType == NET_DATA_CHECK2) && (sender != NetPlay.hostPlayer && receiver != NetPlay.hostPlayer)))
				{
					char msg[256] = {'\0'};

					ssprintf(msg, "Auto-kicking player %u, lacked the required access level for command(%d).", (unsigned int)sender, (int)message->type());
					NETlogEntry(msg, SYNC_FLAG, sender);

					if (NETplayerHasConnection(sender))
					{
						sendRoomSystemMessage(msg);
						debug(LOG_ERROR, "%s", msg);
						kickPlayer(sender, "Invalid command attempted", ERROR_INVALID, true);
					}
					break;
				}

				// Certain messages should be filtered while we're waiting for the ack of a player index switch
				if (NETFilterMessageWhileSwappingPlayer(sender, msgType))
				{
					break;
				}

				if ((msgType == NET_SHARE_GAME_QUEUE) && (receiver != NET_ALL_PLAYERS))
				{
					debug(LOG_NET, "Ignoring non-broadcast message type (%d) from Player %d", (int)message->type(), (int)playerQueue.index);
					break;
				}

				// Certain messages should be filtered due to hostChatPermissions
				if (msgType == NET_TEXTMSG || msgType == NET_SPECTEXTMSG || msgType == NET_AITEXTMSG)
				{
					if (!ingame.hostChatPermissions[sender])
					{
						// Only allow messages direct to host in this case! (Carve-out to allow /hostmsg commands...)
						if (receiver != NetPlay.hostPlayer)
						{
							break;
						}
					}

					LogChatMsg(msgType, *message, sender, receiver);
				}

				size_t rawLen = message->rawData().size();

				// We are the host, and player is asking us to send the message to receiver.
				auto w = NETbeginEncode(NETnetQueue(receiver, sender), NET_SEND_TO_PLAYER);
				NETuint8_t(w, sender);
				NETuint8_t(w, receiver);
				NETnetMessage(w, *message);
				NETend(w);

				if (receiver == NET_ALL_PLAYERS)
				{
					NETlogPacket(msgType, static_cast<uint32_t>(rawLen), true);
					NETinsertMessageFromNet(NETnetQueue(sender), std::move(*message));  // Message is also for the host.
					// Not sure if flushing here can make a difference, maybe it can:
					//NETflush();  // Send the message to everyone as fast as possible.
				}
			}
			else
			{
				if (NetPlay.isHost && NETFilterMessageWhileSwappingPlayer(playerQueue.index, message->type()))
				{
					debug(LOG_NET, "Ignoring message type (%d) from Player %d while swapping player index", (int)message->type(), (int)playerQueue.index);
					break;
				}

				debug(LOG_INFO, "Report this: Player %d sent us message type (%d) addressed to %d from %d. We are %d.", (int)playerQueue.index, (int)message->type(), (int)receiver, (int)sender, selectedPlayer);
			}

			break;
		}
	case NET_SHARE_GAME_QUEUE:
		{
			if (ingame.localJoiningInProgress)
			{
				// NET_SHARE_GAME_QUEUE should only be processed after the game has started - the game queues probably aren't yet created!
				debug(LOG_ERROR, "Ignoring NET_SHARE_GAME_QUEUE message from %" PRIu8 " (only permitted in-game).", playerQueue.index);
				break;
			}

			uint8_t player = 0;
			uint32_t num = 0, n;
			NetMessage* message = nullptr;

			// Encoded in NETprocessSystemMessage in nettypes.cpp.
			auto r = NETbeginDecode(playerQueue, NET_SHARE_GAME_QUEUE);
			NETuint8_t(r, player);
			NETuint32_t(r, num);
			bool isSentByCorrectClient = responsibleFor(playerQueue.index, player);
			isSentByCorrectClient = isSentByCorrectClient || (playerQueue.index == NetPlay.hostPlayer && playerQueue.index != selectedPlayer);  // Let host spoof other people's NET_SHARE_GAME_QUEUE messages, but not our own. This allows the host to spoof a GAME_PLAYER_LEFT message (but spoofing any message when the player is still there will fail with desynch).
			if (!isSentByCorrectClient || player >= MAX_CONNECTED_PLAYERS)
			{
				NETend(r);
				break;
			}
			for (n = 0; n < num; ++n)
			{
				NETnetMessage(r, &message);

				NETlogPacket(message->type(), static_cast<uint32_t>(message->rawData().size()), true);
				NETinsertMessageFromNet(NETgameQueue(player), std::move(*message));

				delete message;
				message = nullptr;
			}
			if (!NETend(r))
			{
				debug(LOG_ERROR, "Bad NET_SHARE_GAME_QUEUE message.");
				break;
			}
			break;
		}
	case NET_PLAYERNAME_CHANGEREQUEST:
		{
			if (!ingame.localJoiningInProgress)
			{
				// player name change only permitted in the lobby
				debug(LOG_ERROR, "Ignoring NET_PLAYERNAME_CHANGEREQUEST message (only permitted in the lobby).");
				break;
			}
			if (!NetPlay.isHost)
			{
				// Only the host should receive and process these messages
				debug(LOG_ERROR, "Ignoring NET_PLAYERNAME_CHANGEREQUEST message (should only be sent to the host).");
				break;
			}

			uint8_t player = 0;
			WzString oldName;
			WzString newName;

			// Encoded in NETchangePlayerName() in netplay.cpp.
			auto r = NETbeginDecode(playerQueue, NET_PLAYERNAME_CHANGEREQUEST);
			NETuint8_t(r, player);
			NETwzstring(r, newName);
			NETend(r);

			// Bail out if the given ID number is out of range
			if (player >= MAX_CONNECTED_PLAYERS || (playerQueue.index != NetPlay.hostPlayer && (playerQueue.index != player || !NetPlay.players[player].allocated)))
			{
				debug(LOG_ERROR, "NET_PLAYERNAME_CHANGEREQUEST from %u: Player ID (%u) out of range (max %u)", playerQueue.index, player, (unsigned int)MAX_CONNECTED_PLAYERS);
				break;
			}

			if (NetPlay.isHost && (!ingame.hostChatPermissions[player] || getLockedOptions().name))
			{
				// Name changes are denied when the host has muted a player (or name changes are locked)
				// Inform the player that their name is still what it was (resets their local display)
				if (NetPlay.players[player].allocated)
				{
					NETSendPlayerInfoTo(player, player);
				}
				break;
			}

			oldName = NetPlay.players[player].name;
			setPlayerName(player, newName.toUtf8().c_str());

			if (NetPlay.players[player].allocated && strncmp(oldName.toUtf8().c_str(), NetPlay.players[player].name, sizeof(NetPlay.players[player].name)) != 0)
			{
				printConsoleNameChange(oldName.toUtf8().c_str(), NetPlay.players[player].name);
				// Send the updated data to all other clients as well.
				NETBroadcastPlayerInfo(player); // ultimately triggers updateMultiplayGameData inside NETSendNPlayerInfoTo
				NETfixDuplicatePlayerNames();
				netPlayersUpdated = true;
			}

			break;
		}
	case NET_PLAYER_STATS:
		{
			recvMultiStats(playerQueue);
			netPlayersUpdated = true;
			break;
		}
	case NET_PLAYER_INFO:
		{
			uint32_t indexLen = 0, n;
			uint32_t index = MAX_CONNECTED_PLAYERS;
			int32_t colour = 0;
			int32_t position = 0;
			int32_t team = 0;
			int8_t ai = 0;
			int8_t difficulty = 0;
			uint8_t faction = FACTION_NORMAL;
			bool isSpectator = false;
			bool isAdmin = false;
			bool error = false;

			auto r = NETbeginDecode(playerQueue, NET_PLAYER_INFO);
			NETuint32_t(r, indexLen);
			if (indexLen > MAX_CONNECTED_PLAYERS || (playerQueue.index != NetPlay.hostPlayer))
			{
				debug(LOG_ERROR, "MSG_PLAYER_INFO: Bad number of players updated: %u", indexLen);
				NETend(r);
				break;
			}

			for (n = 0; n < indexLen; ++n)
			{
				bool wasAllocated = false;
				std::string oldName;

				// Retrieve the player's ID
				NETuint32_t(r, index);

				// Bail out if the given ID number is out of range
				if (index >= MAX_CONNECTED_PLAYERS || (playerQueue.index != NetPlay.hostPlayer && (playerQueue.index != index || !NetPlay.players[index].allocated)))
				{
					debug(LOG_ERROR, "MSG_PLAYER_INFO from %u: Player ID (%u) out of range (max %u)", playerQueue.index, index, (unsigned int)MAX_CONNECTED_PLAYERS);
					error = true;
					break;
				}

				// Retrieve the rest of the data
				wasAllocated = NetPlay.players[index].allocated;
				NETbool(r, NetPlay.players[index].allocated);
				NETbool(r, NetPlay.players[index].heartbeat);
				bool tmpDiscard = false;
				NETbool(r, tmpDiscard); // to maintain message format, discard old "kick" variable // FUTURE TODO: Remove
				oldName.clear();
				oldName = NetPlay.players[index].name;
				NETstring(r, NetPlay.players[index].name, sizeof(NetPlay.players[index].name));
				NETuint32_t(r, NetPlay.players[index].heartattacktime);
				NETint32_t(r, colour);
				NETint32_t(r, position);
				NETint32_t(r, team);
				NETbool(r, NetPlay.players[index].ready);
				NETint8_t(r, ai);
				NETint8_t(r, difficulty);
				NETuint8_t(r, faction);
				NETbool(r, isSpectator);
				NETbool(r, isAdmin);

				auto newFactionId = uintToFactionID(faction);
				if (!newFactionId.has_value())
				{
					debug(LOG_ERROR, "MSG_PLAYER_INFO from %u: Faction ID (%u) out of range (max %u)", playerQueue.index, (unsigned int)faction, (unsigned int)MAX_FACTION_ID);
					error = true;
					break;
				}

				// Don't let anyone except the host change these, otherwise it will end up inconsistent at some point, and the game gets really messed up.
				if (playerQueue.index == NetPlay.hostPlayer)
				{
					setPlayerColour(index, colour);
					NetPlay.players[index].position = position;
					NetPlay.players[index].team = team;
					NetPlay.players[index].ai = ai;
					NetPlay.players[index].difficulty = static_cast<AIDifficulty>(difficulty);
					NetPlay.players[index].faction = newFactionId.value();
					NetPlay.players[index].isSpectator = isSpectator;
					NetPlay.players[index].isAdmin = isAdmin;
				}

				debug(LOG_NET, "%s for player %u (%s)", n == 0 ? "Receiving MSG_PLAYER_INFO" : "                      and", (unsigned int)index, NetPlay.players[index].allocated ? "human" : "AI");

				if (wasAllocated && NetPlay.players[index].allocated && strncmp(oldName.c_str(), NetPlay.players[index].name, sizeof(NetPlay.players[index].name)) != 0)
				{
					printConsoleNameChange(oldName.c_str(), NetPlay.players[index].name);
				}
			}
			NETend(r);
			// If we're the game host make sure to send the updated
			// data to all other clients as well.
			if (NetPlay.isHost && !error)
			{
				NETBroadcastPlayerInfo(index); // ultimately triggers updateMultiplayGameData inside NETSendNPlayerInfoTo
				NETfixDuplicatePlayerNames();
			}
			else if (!error)
			{
				if (index == selectedPlayer)
				{
					handleAutoReadyRequest();
				}
				ActivityManager::instance().updateMultiplayGameData(game, ingame, NETGameIsLocked());
			}
			netPlayersUpdated = true;
			break;
		}
	case NET_PLAYER_JOINED:
		{
			uint8_t index;

			auto r = NETbeginDecode(playerQueue, NET_PLAYER_JOINED);
			NETuint8_t(r, index);
			NETend(r);

			debug(LOG_NET, "Receiving NET_PLAYER_JOINED for player %u using socket %p",
			      (unsigned int)index, static_cast<void *>(bsocket));

			MultiPlayerJoin(index, nullopt);
			netPlayersUpdated = true;
			break;
		}
	// This message type is when player is leaving 'nicely', and socket is still valid.
	case NET_PLAYER_LEAVING:
		{
			uint32_t index;

			auto r = NETbeginDecode(playerQueue, NET_PLAYER_LEAVING);
			NETuint32_t(r, index);
			NETend(r);

			if (playerQueue.index != NetPlay.hostPlayer && index != playerQueue.index)
			{
				debug(LOG_ERROR, "Player %d left, but accidentally set player %d as leaving.", playerQueue.index, index);
				index = playerQueue.index;
			}

			if (connected_bsocket[index])
			{
				debug(LOG_NET, "Receiving NET_PLAYER_LEAVING for player %u on socket %p", (unsigned int)index, static_cast<void *>(connected_bsocket[index]));
			}
			else
			{
				// dropped from join screen most likely
				debug(LOG_NET, "Receiving NET_PLAYER_LEAVING for player %u (no socket?)", (unsigned int)index);
			}

			if (NetPlay.isHost)
			{
				debug(LOG_NET, "Broadcast leaving message to everyone else");
				auto w = NETbeginEncode(NETbroadcastQueue(), NET_PLAYER_LEAVING);
				NETuint32_t(w, index);
				NETend(w);
			}

			debug(LOG_INFO, "Player %u has left the game.", index);
			NETplayerLeaving(index);		// need to close socket for the player that left.
			NETsetPlayerConnectionStatus(CONNECTIONSTATUS_PLAYER_LEAVING, index);
			break;
		}
	case NET_GAME_FLAGS:
		{
			debug(LOG_NET, "Receiving game flags");

			auto r = NETbeginDecode(playerQueue, NET_GAME_FLAGS);

			if (playerQueue.index != NetPlay.hostPlayer)
			{
				debug(LOG_ERROR, "NET_GAME_FLAGS sent by wrong player: %" PRIu32 "", playerQueue.index);
				NETend(r);
				break;
			}

			{
				static unsigned int max_flags = ARRAY_SIZE(NetGameFlags);
				// Retrieve the amount of game flags that we should receive
				uint8_t i, count;
				NETuint8_t(r, count);

				// Make sure that we won't get buffer overflows by checking that we
				// have enough space to store the given amount of game flags.
				if (count > max_flags)
				{
					debug(LOG_NET, "NET_GAME_FLAGS: More game flags sent (%u) than our buffer can hold (%u)", (unsigned int)count, max_flags);
					count = max_flags;
				}

				// Retrieve all game flags
				for (i = 0; i < count; ++i)
				{
					NETint32_t(r, NetGameFlags[i]);
				}
			}
			NETend(r);

			if (NetPlay.isHost)
			{
				NETsendGameFlags();
			}
			break;
		}
	case NET_DEBUG_SYNC:
		{
			recvDebugSync(playerQueue);
			break;
		}
	case NET_PLAYER_SWAP_INDEX_ACK:
		{
			ASSERT_HOST_ONLY(break);

			uint32_t oldPlayerIndex;
			uint32_t newPlayerIndex;

			auto r = NETbeginDecode(playerQueue, NET_PLAYER_SWAP_INDEX_ACK);
			NETuint32_t(r, oldPlayerIndex);
			NETuint32_t(r, newPlayerIndex);
			NETend(r);

			bool isSentByCorrectClient = responsibleFor(playerQueue.index, newPlayerIndex);
			if (!isSentByCorrectClient)
			{
				debug(LOG_ERROR, "NET_PLAYER_SWAP_INDEX_ACK sent by wrong player: %" PRIu32 "", playerQueue.index);
				break;
			}

			if (newPlayerIndex >= NET_waitingForIndexChangeAckSince.size() || !NET_waitingForIndexChangeAckSince[newPlayerIndex].has_value())
			{
				debug(LOG_ERROR, "NET_PLAYER_SWAP_INDEX_ACK sent despite us not waiting for it (for player: %" PRIu32 ")", newPlayerIndex);
				break;
			}

			NET_waitingForIndexChangeAckSince[newPlayerIndex] = nullopt;

			break;
		}

	default:
		return false;
	}

	NETpop(playerQueue);
	return true;
}

/*
*	Checks to see if a human player is still with us.
*	@note: resuscitation isn't possible with current code, so once we lose
*	the socket, then we have no way to connect with them again. Future
*	item to enhance.
*/
static void NETcheckPlayers()
{
	if (!NetPlay.isHost)
	{
		ASSERT(false, "Host only routine detected for client or not hosting yet!");
		return;
	}

	for (int i = 0; i < MAX_CONNECTED_PLAYERS ; i++)
	{
		if (NetPlay.players[i].allocated == 0)
		{
			continue;    // not allocated means that it most likely it is a AI player
		}
		if (!NetPlay.players[i].heartbeat && NetPlay.players[i].heartattacktime == 0)	// looks like they are dead
		{
			NetPlay.players[i].heartattacktime = realTime;		// mark when this occurred
		}
	}
}

// ////////////////////////////////////////////////////////////////////////
// Receive a message over the current connection. We return true if there
// is a message for the higher level code to process, and false otherwise.
// We should not block here.
bool NETrecvNet(NETQUEUE *queue, uint8_t *type)
{
	if (!NetPlay.bComms)
	{
		return false;
	}

	if (activeConnProvider)
	{
		activeConnProvider->processConnectionStateChanges();
	}

	if (NetPlay.isHost)
	{
		NETfixPlayerCount();
		NETacceptIncomingConnections();
		NETallowJoining();
		lobbyConnectionHandler.run();
		NETcheckPlayers();		// make sure players are still alive & well
	}

	IConnectionPollGroup* pollGroup = NetPlay.isHost ? server_socket_set : client_socket_set;
	if (pollGroup == nullptr || pollGroup->checkConnectionsReadable(NET_READ_TIMEOUT).value_or(0) <= 0)
	{
		goto checkMessages;
	}

	uint32_t current;
	uint8_t buffer[NET_BUFFER_SIZE];
	for (current = 0; current < MAX_CONNECTED_PLAYERS; ++current)
	{
		IClientConnection** pSocket = NetPlay.isHost ? &connected_bsocket[current] : &bsocket;

		if (!NetPlay.isHost && current != NetPlay.hostPlayer)
		{
			continue;  // Don't have a socket open to this player.
		}

		if (*pSocket == nullptr)
		{
			continue;
		}

		size_t dataLen = NET_fillBuffer(pSocket, pollGroup, buffer, sizeof(buffer));
		if (dataLen > 0)
		{
			// we received some data, add to buffer
			NETinsertRawData(NETnetQueue(current), buffer, dataLen);
		}
		else if (*pSocket == nullptr)
		{
			// If there is a error in NET_fillBuffer() then socket is already invalid.
			// This means that the player dropped / disconnected for whatever reason.
			debug(LOG_INFO, "Player, (player %u) seems to have dropped/disconnected.", (unsigned)current);

			if (NetPlay.isHost)
			{
				// Send message type specifically for dropped / disconnects
				NETplayerDropped(current);
				connected_bsocket[current] = nullptr;		// clear their socket
			}
		}
	}

checkMessages:
	for (current = 0; current < MAX_CONNECTED_PLAYERS; ++current)
	{
		*queue = NETnetQueue(current);
		while (NETisMessageReady(*queue))
		{
			*type = NETgetMessage(*queue)->type();
			if (!NETprocessSystemMessage(*queue, type))
			{
				return true;  // We couldn't process the message, let the caller deal with it..
			}
		}
	}

	return false;
}

bool NETrecvGame(NETQUEUE *queue, uint8_t *type)
{
	for (unsigned current = 0; current < MAX_GAMEQUEUE_SLOTS; ++current)
	{
		*queue = NETgameQueue(current);
		if (queue->queue == nullptr)
		{
			continue;
		}
		while (!checkPlayerGameTime(current))  // Check for any messages that are scheduled to be read now.
		{
			if (!NETisMessageReady(*queue))
			{
				return false;  // Still waiting for messages from this player, and all players should process messages in the same order. Will have to freeze the game while waiting.
			}

			NETreplaySaveNetMessage(NETgetMessage(*queue), queue->index);
			*type = NETgetMessage(*queue)->type();

			if (*type == GAME_GAME_TIME)
			{
				recvPlayerGameTime(*queue);
				NETpop(*queue);
				continue;
			}

			return true;  // Have a message ready to read now.
		}
	}

	return false;  // No messages sceduled to be read yet. Game can continue.
}

// ////////////////////////////////////////////////////////////////////////
// File Transfer programs.
/** Send file. It returns % of file sent when 100 it's complete. Call until it returns 100.
*  @TODO: more error checking (?) different file types (?)
*          Maybe should close file handle, and seek each time?
*
*  @NOTE: MAX_FILE_TRANSFER_PACKET is set to 4k per packet since 7*4 = 28K which is pretty
*         much our limit.  Don't screw with that without having a bigger buffer!
*         NET_BUFFER_SIZE is at 256k.  (also remember text chat, plus all the other cruff)
*/
#define MAX_FILE_TRANSFER_PACKET 4096
int NETsendFile(WZFile &file, unsigned player)
{
	ASSERT_OR_RETURN(100, NetPlay.isHost, "Trying to send a file and we are not the host!");
	ASSERT_OR_RETURN(100, file.handle() != nullptr, "Null file handle");

	uint8_t inBuff[MAX_FILE_TRANSFER_PACKET];
	memset(inBuff, 0x0, sizeof(inBuff));

	// read some bytes.
	PHYSFS_sint64 readBytesResult = WZ_PHYSFS_readBytes(file.handle(), inBuff, MAX_FILE_TRANSFER_PACKET);
	if (readBytesResult < 0)
	{
		ASSERT(readBytesResult >= 0, "Error reading file.");
		file.closeFile();
		return 100;
	}
	uint32_t bytesToRead = static_cast<uint32_t>(readBytesResult);

	auto w = NETbeginEncode(NETnetQueue(player), NET_FILE_PAYLOAD);
	NETbin(w, file.hash.bytes, file.hash.Bytes);
	NETuint32_t(w, file.size);  // total bytes in this file. (we don't support 64bit yet)
	NETuint32_t(w, file.pos);  // start byte
	NETuint32_t(w, bytesToRead);  // bytes in this packet
	NETbin(w, inBuff, bytesToRead);
	NETend(w);

	file.pos += bytesToRead;  // update position!
	if (file.pos == file.size)
	{
		file.closeFile(); // We are done sending to this client.
	}

	return static_cast<int>((uint64_t)file.pos * 100 / file.size);
}

bool validateReceivedFile(const WZFile& file)
{
	PHYSFS_file *fileHandle = PHYSFS_openRead(file.filename.c_str());
	ASSERT_OR_RETURN(false, fileHandle != nullptr, "Could not open downloaded file %s for reading: %s", file.filename.c_str(), WZ_PHYSFS_getLastError());

	PHYSFS_sint64 actualFileSize64 = PHYSFS_fileLength(fileHandle);
	if (actualFileSize64 < 0)
	{
		debug(LOG_ERROR, "Failed to determine file size of the downloaded file!");
		PHYSFS_close(fileHandle);
		return false;
	}
	if(actualFileSize64 > std::numeric_limits<int32_t>::max())
	{
		debug(LOG_ERROR, "Downloaded file is too large!");
		PHYSFS_close(fileHandle);
		return false;
	}

	uint32_t actualFileSize = static_cast<uint32_t>(actualFileSize64);
	if (actualFileSize != file.size)
	{
		debug(LOG_ERROR, "Downloaded map unexpected size! Got %" PRIu32", expected %" PRIu32"!", actualFileSize, file.size);
		PHYSFS_close(fileHandle);
		return false;
	}

	// verify actual downloaded file hash matches expected hash

	Sha256 actualFileHash;
	crypto_hash_sha256_state state;
	crypto_hash_sha256_init(&state);
	size_t bufferSize = std::min<size_t>(actualFileSize, 4 * 1024 * 1024);
	std::vector<unsigned char> fileChunkBuffer(bufferSize, '\0');
	PHYSFS_sint64 length_read = 0;
	do {
		length_read = WZ_PHYSFS_readBytes(fileHandle, fileChunkBuffer.data(), static_cast<PHYSFS_uint32>(bufferSize));
		if (length_read != bufferSize)
		{
			if (length_read < 0 || !PHYSFS_eof(fileHandle))
			{
				// did not read expected amount, but did not reach end of file - some other error reading the file occurred
				debug(LOG_ERROR, "Failed to read downloaded file: %s", WZ_PHYSFS_getLastError());
				PHYSFS_close(fileHandle);
				return false;
			}
		}
		crypto_hash_sha256_update(&state, fileChunkBuffer.data(), static_cast<unsigned long long>(length_read));
	} while (length_read == bufferSize);
	crypto_hash_sha256_final(&state, actualFileHash.bytes);
	fileChunkBuffer.clear();

	if (actualFileHash != file.hash)
	{
		debug(LOG_ERROR, "Downloaded file hash (%s) does not match requested file hash (%s)", actualFileHash.toString().c_str(), file.hash.toString().c_str());
		PHYSFS_close(fileHandle);
		return false;
	}

	PHYSFS_close(fileHandle);
	return true;
}

bool markAsDownloadedFile(const std::string &filename)
{
	// Files are written to the PhysFS writeDir
	const char * current_writeDir = PHYSFS_getWriteDir();
	ASSERT(current_writeDir != nullptr, "Failed to get PhysFS writeDir: %s", WZ_PHYSFS_getLastError());
	std::string fullFilePath = std::string(current_writeDir) + PHYSFS_getDirSeparator() + filename;

#if defined(WZ_OS_WIN)
	// On Windows:
	//	- Create the Alternate Data Stream required to set the Internet Zone identifier
	const wchar_t kWindowsZoneIdentifierADSSuffix[] = L":Zone.Identifier";

	// Convert fullFilePath to UTF-16 wchar_t
	int wstr_len = MultiByteToWideChar(CP_UTF8, 0, fullFilePath.c_str(), -1, NULL, 0);
	if (wstr_len <= 0)
	{
		debug(LOG_ERROR, "Could not convert string from UTF-8; MultiByteToWideChar failed with error %lu: %s\n", GetLastError(), fullFilePath.c_str());
		return false;
	}
	std::vector<wchar_t> wstr_filename(wstr_len, 0);
	if (MultiByteToWideChar(CP_UTF8, 0, fullFilePath.c_str(), -1, &wstr_filename[0], wstr_len) == 0)
	{
		debug(LOG_ERROR, "Could not convert string from UTF-8; MultiByteToWideChar[2] failed with error %lu: %s\n", GetLastError(), fullFilePath.c_str());
		return false;
	}
	std::wstring fullFilePathUTF16(wstr_filename.data());
	fullFilePathUTF16 += kWindowsZoneIdentifierADSSuffix;

	HANDLE hStream = CreateFileW(fullFilePathUTF16.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	if(hStream == INVALID_HANDLE_VALUE)
	{
		// Failed to open stream
		debug(LOG_ERROR, "Could not open stream; failed with error %lu: %s\n", GetLastError(), fullFilePath.c_str());
		return false;
	}

	// Set it to "downloaded from the Internet Zone" (ZoneId 3)
	const char kWindowsZoneIdentifierADSDataInternetZone[] = "[ZoneTransfer]\r\nZoneId=3\r\n";
	DWORD dwNumberOfBytesWritten;
	if (WriteFile(hStream, kWindowsZoneIdentifierADSDataInternetZone, static_cast<DWORD>(strlen(kWindowsZoneIdentifierADSDataInternetZone)), &dwNumberOfBytesWritten, NULL) == 0)
	{
		debug(LOG_ERROR, "Failed to write to stream with error %lu: %s\n", GetLastError(), fullFilePath.c_str());
		CloseHandle(hStream);
		return false;
	}

	FlushFileBuffers(hStream);
	CloseHandle(hStream);

	return true;
#elif defined (WZ_OS_MAC)
	// On macOS:
	//	- Set the quarantine attribute on the file
	return cocoaSetFileQuarantineAttribute(fullFilePath.c_str());
#else
	// Not currently implemented
#endif
	return false;
}

// recv file. it returns % of the file so far recvd.
int NETrecvFile(NETQUEUE queue)
{
	Sha256 hash;
	hash.setZero();
	uint32_t size = 0;
	uint32_t pos = 0;
	uint32_t bytesToRead = 0;
	uint8_t buf[MAX_FILE_TRANSFER_PACKET];
	memset(buf, 0x0, sizeof(buf));

	//read incoming bytes.
	auto r = NETbeginDecode(queue, NET_FILE_PAYLOAD);
	NETbin(r, hash.bytes, hash.Bytes);
	NETuint32_t(r, size);  // total bytes in this file. (we don't support 64bit yet)
	NETuint32_t(r, pos);  // start byte
	NETuint32_t(r, bytesToRead);  // bytes in this packet
	ASSERT_OR_RETURN(100, bytesToRead <= sizeof(buf), "Bad value.");
	NETbin(r, buf, bytesToRead);
	NETend(r);

	debug(LOG_NET, "New file position is %u", pos);

	auto file = std::find_if(DownloadingWzFiles.begin(), DownloadingWzFiles.end(), [&](WZFile const &file) { return file.hash == hash; });

	auto sendCancelFileDownload = [](Sha256 &hash) {
		auto w = NETbeginEncode(NETnetQueue(NetPlay.hostPlayer), NET_FILE_CANCELLED);
		NETbin(w, hash.bytes, hash.Bytes);
		NETend(w);
	};

	if (file == DownloadingWzFiles.end())
	{
		debug(LOG_WARNING, "Receiving file data we didn't request.");
		sendCancelFileDownload(hash);
		return 100;
	}

	auto terminateFileDownload = [sendCancelFileDownload](std::vector<WZFile>::iterator &file) {
		if (!file->closeFile())
		{
			debug(LOG_ERROR, "Could not close file handle after trying to terminate download: %s", WZ_PHYSFS_getLastError());
		}
		PHYSFS_delete(file->filename.c_str());
		sendCancelFileDownload(file->hash);
		DownloadingWzFiles.erase(file);
	};

	//sanity checks
	if (file->size != size)
	{
		if (file->size == 0)
		{
			// host does not send the file size until the first recvFile packet
			file->size = size;
		}
		else
		{
			// host sent a different file size for this file with this chunk (vs the first chunk)
			// this should not happen!
			debug(LOG_ERROR, "Host sent a different file size for this file; (original size: %u, new size: %u)", file->size, size);
			terminateFileDownload(file); // 'file' is now an invalidated iterator.
			return 100;
		}
	}

	if (size > MAX_NET_TRANSFERRABLE_FILE_SIZE)
	{
		// file size is too large
		debug(LOG_ERROR, "Downloaded filesize is too large; (size: %" PRIu32")", size);
		terminateFileDownload(file); // 'file' is now an invalidated iterator.
		return 100;
	}

	if (PHYSFS_tell(file->handle()) != static_cast<PHYSFS_sint64>(pos))
	{
		// actual position in file does not equal the expected position in the file (sent by the host)
		debug(LOG_ERROR, "Invalid file position in downloaded file; (desired: %" PRIu32")", pos);
		terminateFileDownload(file); // 'file' is now an invalidated iterator.
		return 100;
	}

	// Write packet to the file.
	WZ_PHYSFS_writeBytes(file->handle(), buf, bytesToRead);

	uint32_t newPos = pos + bytesToRead;
	file->pos = newPos;

	if (newPos >= size)  // last packet
	{
		if (!file->closeFile())
		{
			debug(LOG_ERROR, "Could not close file handle after trying to save map: %s", WZ_PHYSFS_getLastError());
		}

		if(!validateReceivedFile(*file))
		{
			// Delete the (invalid) downloaded file
			PHYSFS_delete(file->filename.c_str());
		}
		else
		{
			// Attach Quarantine / "downloaded" file attribute to file
			markAsDownloadedFile(file->filename.c_str());
		}

		DownloadingWzFiles.erase(file);
	}
	// 'file' may now be an invalidated iterator.

	//return the percentage count
	if (size)
	{
		return (newPos * 100) / size;
	}
	debug(LOG_ERROR, "Received 0 byte file from host?");
	return 100;		// file is nullbyte, so we are done.
}

unsigned NETgetDownloadProgress(unsigned player)
{
	std::vector<WZFile> const *files = player == selectedPlayer ?
		&DownloadingWzFiles :  // Check our own download progress.
		NetPlay.players[player].wzFiles.get();  // Check their download progress (currently only works if we are the host).

	ASSERT_OR_RETURN(100, files != nullptr, "Uninitialized wzFiles? (Player %u)", player);

	uint32_t progress = 100;
	for (WZFile const &file : *files)
	{
		progress = std::min<uint32_t>(progress, (uint32_t)((uint64_t)file.pos * 100 / (uint64_t)std::max<uint32_t>(file.size, 1)));
	}
	return static_cast<unsigned>(progress);
}

#define MAX_LOBBY_MOTD_LENGTH (2*1024)

static net::result<ssize_t> readLobbyResponseInternal(IClientConnection& sock, unsigned int timeout, uint32_t& output_lobbyStatusCode, std::string& output_MOTD)
{
	uint32_t buffer[2];
	ssize_t received = 0;

	// Get status and message length
	auto readResult = sock.readAll(&buffer, sizeof(buffer), timeout);
	if (!readResult.has_value())
	{
		return readResult;
	}
	received += readResult.value();
	output_lobbyStatusCode = wz_ntohl(buffer[0]);
	uint32_t MOTDLength = wz_ntohl(buffer[1]);

	// Get status message
	if (MOTDLength > MAX_LOBBY_MOTD_LENGTH)
	{
		return tl::make_unexpected(std::make_error_code(std::errc::bad_message));
	}
	std::vector<char> tmpMOTDBuffer;
	tmpMOTDBuffer.resize(MOTDLength);
	readResult = sock.readAll(tmpMOTDBuffer.data(), MOTDLength, timeout);
	if (!readResult.has_value())
	{
		return readResult;
	}
	received += readResult.value();

	// truncate at first null byte in MOTD (or the end)
	auto endIt = std::find(tmpMOTDBuffer.begin(), tmpMOTDBuffer.end(), 0);
	output_MOTD.assign(tmpMOTDBuffer.begin(), endIt);

	return received;
}

static ssize_t readLobbyResponse(IClientConnection& sock, unsigned int timeout)
{
	ssize_t received = 0;
	uint32_t lobbyStatusCode = 0;
	auto readResult = readLobbyResponseInternal(sock, timeout, lobbyStatusCode, NetPlay.MOTD);
	if (!readResult.has_value())
	{
		goto error;
	}
	received = readResult.value();

	switch (lobbyStatusCode)
	{
	case 200:
		debug(LOG_NET, "Lobby success (%u): %s", (unsigned int)lobbyStatusCode, NetPlay.MOTD.c_str());
		NetPlay.HaveUpgrade = false;
		break;

	case 400:
		debug(LOG_NET, "**Upgrade available! Lobby success (%u): %s", (unsigned int)lobbyStatusCode, NetPlay.MOTD.c_str());
		NetPlay.HaveUpgrade = true;
		break;

	default:
		debug(LOG_ERROR, "Lobby error (%u): %s", (unsigned int)lobbyStatusCode, NetPlay.MOTD.c_str());
		// ensure if the lobby returns an error, we are prepared to display it (once)
		NetPlay.ShowedMOTD = false;
		// this is horrible but MOTD can have 0x0a and other junk in it
		wz_command_interface_output("WZEVENT: lobbyerror (%u): %s\n", (unsigned int)lobbyStatusCode, base64Encode(std::vector<unsigned char>(NetPlay.MOTD.begin(), NetPlay.MOTD.end())).c_str());
		break;
	}

	return received;

error:
	const auto readErrMsg = readResult.error().message();
	NetPlay.MOTD = astringf("Error while connecting to the lobby server: %s\nMake sure port %d can receive incoming connections.", readErrMsg.c_str(), gameserver_port);
	NetPlay.ShowedMOTD = false;
	debug(LOG_ERROR, "%s", NetPlay.MOTD.c_str());

	wz_command_interface_output("WZEVENT: lobbysocketerror: %s\n", (!NetPlay.MOTD.empty()) ? base64Encode(std::vector<unsigned char>(NetPlay.MOTD.begin(), NetPlay.MOTD.end())).c_str() : "");

	return SOCKET_ERROR;
}

bool readGameStructsList(IClientConnection& sock, unsigned int timeout, const std::function<bool (const GAMESTRUCT& game)>& handleEnumerateGameFunc)
{
	unsigned int gamecount = 0;
	uint32_t gamesavailable = 0;
	const auto readResult = sock.readAll(&gamesavailable, sizeof(gamesavailable), NET_TIMEOUT_DELAY);

	if (readResult.has_value())
	{
		gamesavailable = wz_ntohl(gamesavailable);
	}
	else
	{
		if (readResult.error() == std::errc::timed_out || readResult.error() == std::errc::connection_reset)
		{
			debug(LOG_NET, "Server didn't respond (timeout)");
		}
		else
		{
			const auto readErrMsg = readResult.error().message();
			debug(LOG_NET, "Server socket encountered error: %s", readErrMsg.c_str());
		}
		return false;
	}

	debug(LOG_NET, "receiving info on %u game(s)", (unsigned int)gamesavailable);

	while (gamecount < gamesavailable)
	{
		// Attempt to receive a game description structure
		GAMESTRUCT tmpGame;
		memset(&tmpGame, 0x00, sizeof(tmpGame));
		if (!NETrecvGAMESTRUCT(sock, &tmpGame))
		{
			debug(LOG_NET, "only %u game(s) received", (unsigned int)gamecount);
			return false;
		}

		if (tmpGame.desc.host[0] == '\0')
		{
			memset(tmpGame.desc.host, 0, sizeof(tmpGame.desc.host));
			const auto textAddr = sock.textAddress();
			strncpy(tmpGame.desc.host, textAddr.data(), sizeof(tmpGame.desc.host) - 1);
		}

		if (tmpGame.desc.dwSize != 0)
		{
			if (!handleEnumerateGameFunc(tmpGame))
			{
				// stop enumerating
				break;
			}
		}

		++gamecount;
	}

	return true;
}

template <typename T>
static net::result<void> ignoreExpectedResultValue(const net::result<T>& res)
{
	return res.has_value() ? net::result<void>{} : tl::make_unexpected(res.error());
}

std::shared_ptr<WzConnectionProvider> NET_getLobbyConnectionProvider()
{
	// The only supported backend type for talking with lobby server at the moment.
	constexpr auto PROVIDER_TYPE = ConnectionProviderType::TCP_DIRECT;

	auto& cpr = ConnectionProviderRegistry::Instance();
	if (!cpr.IsRegistered(PROVIDER_TYPE))
	{
		cpr.Register(PROVIDER_TYPE);
	}
	auto connProvider = cpr.Get(ConnectionProviderType::TCP_DIRECT);
	ASSERT_OR_RETURN(nullptr, connProvider != nullptr, "Null connectionProvider");
	connProvider->initialize();

	PendingWritesManagerMap::instance().get(*connProvider).initialize(*connProvider);

	return connProvider;
}

void LobbyServerConnectionHandler::ensureInitialized()
{
	connProvider = NET_getLobbyConnectionProvider();
}

bool LobbyServerConnectionHandler::connect()
{
	if (server_not_there)
	{
		return false;
	}
	if (lobby_disabled)
	{
		debug(LOG_ERROR, "Multiplayer lobby support unavailable. Please update your client.");
		wz_command_interface_output("WZEVENT: lobbyerror: Client support disabled / unavailable\n");
		gamestruct.gameId = 0;
		server_not_there = true;
		return true; // return true once, so that NETallowJoining processes the "first time connect" branch
	}
	if (currentState == LobbyConnectionState::Connecting_WaitingForResponse || currentState == LobbyConnectionState::Connected)
	{
		return false; // already connecting or connected
	}

	ensureInitialized();

	bool bProcessingConnectOrDisconnectThisCall = true;
	uint32_t gameId = 0;
	const auto hostsResult = connProvider->resolveHost(masterserver_name, masterserver_port);

	if (!hostsResult.has_value())
	{
		const auto hostsErrMsg = hostsResult.error().message();
		debug(LOG_ERROR, "Cannot resolve masterserver \"%s\": %s", masterserver_name, hostsErrMsg.c_str());
		NetPlay.MOTD = astringf(_("Could not resolve masterserver name (%s)!"), masterserver_name);
		wz_command_interface_output("WZEVENT: lobbyerror (%u): Cannot resolve lobby server: %s\n", 0, hostsErrMsg.c_str());
		server_not_there = true;
		return bProcessingConnectOrDisconnectThisCall;
	}

	const auto& hosts = hostsResult.value();

	// Close an existing socket.
	if (rs_socket != nullptr)
	{
		rs_socket->close();
		rs_socket = nullptr;
	}

	// try each address from resolveHost until we successfully connect.
	auto sockResult = connProvider->openClientConnectionAny(*hosts, 1500);

	rs_socket = sockResult.value_or(nullptr);

	// No address succeeded.
	if (rs_socket == nullptr)
	{
		const auto errMsg = sockResult.error().message();
		debug(LOG_ERROR, "Cannot connect to masterserver \"%s:%d\": %s", masterserver_name, masterserver_port, errMsg.c_str());
		NetPlay.MOTD = astringf(_("Error connecting to the lobby server: %s.\nMake sure port %d can receive incoming connections.\nIf you're using a router configure it to enable UPnP/NAT-PMP/PCP\n or to forward the port to your system."),
								errMsg.c_str(), masterserver_port);
		server_not_there = true;
		return bProcessingConnectOrDisconnectThisCall;
	}

	// Get a game ID
	auto gameIdResult = rs_socket->writeAll("gaId", sizeof("gaId"), nullptr);
	if (gameIdResult.has_value())
	{
		gameIdResult = rs_socket->readAll(&gameId, sizeof(gameId), 10000);
	}
	if (!gameIdResult.has_value())
	{
		const auto gameIdErrMsg = gameIdResult.error().message();
		NetPlay.MOTD = astringf("Failed to retrieve a game ID: %s", gameIdErrMsg.c_str());
		debug(LOG_ERROR, "%s", NetPlay.MOTD.c_str());

		// The socket has been invalidated, so get rid of it. (using them now may cause SIGPIPE).
		disconnect();
		return bProcessingConnectOrDisconnectThisCall;
	}

	gamestruct.gameId = wz_ntohl(gameId);
	debug(LOG_NET, "Using game ID: %u", (unsigned int)gamestruct.gameId);

	wz_command_interface_output("WZEVENT: lobbyid: %" PRIu32 "\n", gamestruct.gameId);

	// Register our game with the server
	const auto writeAddGameRes = rs_socket->writeAll("addg", sizeof("addg"), nullptr);

	auto sendGamestructRes = ignoreExpectedResultValue(writeAddGameRes);
	if (sendGamestructRes.has_value())
	{
		// and now send what the server wants
		sendGamestructRes = NETsendGAMESTRUCT(rs_socket, &gamestruct);
	}
	if (!sendGamestructRes.has_value())
	{
		const auto sendGameErrMsg = sendGamestructRes.error().message();
		debug(LOG_ERROR, "Failed to register game with server: %s", sendGameErrMsg.c_str());
		disconnect();
		return bProcessingConnectOrDisconnectThisCall;
	}

	lastServerUpdate = realTime;
	queuedServerUpdate = false;

	lastConnectionTime = realTime;
	waitingForConnectionFinalize = connProvider->newConnectionPollGroup();
	waitingForConnectionFinalize->add(rs_socket);

	currentState = LobbyConnectionState::Connecting_WaitingForResponse;
	return bProcessingConnectOrDisconnectThisCall;
}

bool LobbyServerConnectionHandler::disconnect()
{
	if (currentState == LobbyConnectionState::Disconnected)
	{
		return false; // already disconnected
	}

	if (rs_socket != nullptr)
	{
		// we don't need this anymore, so clean up
		rs_socket->close();
		rs_socket = nullptr;
		server_not_there = true;
	}

	if (waitingForConnectionFinalize != nullptr)
	{
		delete waitingForConnectionFinalize;
		waitingForConnectionFinalize = nullptr;
	}

	connProvider = nullptr;

	queuedServerUpdate = false;

	ActivityManager::instance().hostGameLobbyServerDisconnect();
	wz_command_interface_output_str("WZEVENT: lobbyerror: Disconnected\n");

	currentState = LobbyConnectionState::Disconnected;
	return true;
}

void LobbyServerConnectionHandler::sendUpdate()
{
	if (lobby_disabled || server_not_there)
	{
		if (currentState != LobbyConnectionState::Disconnected)
		{
			disconnect();
		}
		return;
	}

	if (canSendServerUpdateNow())
	{
		sendUpdateNow();
	}
	else
	{
		// queue future update
		debug(LOG_NET, "Queueing server update");
		queuedServerUpdate = true;
	}
}

void LobbyServerConnectionHandler::sendUpdateNow()
{
	ASSERT_OR_RETURN(, rs_socket != nullptr, "Null socket");
	if (lobby_disabled)
	{
		if (currentState != LobbyConnectionState::Disconnected)
		{
			disconnect();
		}
		return;
	}

	if (!NETsendGAMESTRUCT(rs_socket, &gamestruct).has_value())
	{
		disconnect();
	}
	lastServerUpdate = realTime;
	queuedServerUpdate = false;
	// newer lobby server will return a lobby response / status after each update call
	if (rs_socket && readLobbyResponse(*rs_socket, NET_TIMEOUT_DELAY) == SOCKET_ERROR)
	{
		disconnect();
	}
}

void LobbyServerConnectionHandler::sendKeepAlive()
{
	ASSERT_OR_RETURN(, rs_socket != nullptr, "Null socket");
	if (!rs_socket->writeAll("keep", sizeof("keep"), nullptr).has_value())
	{
		// The socket has been invalidated, so get rid of it. (using them now may cause SIGPIPE).
		disconnect();
	}
	lastServerUpdate = realTime;
}

void LobbyServerConnectionHandler::run()
{
	switch (currentState)
	{
		case LobbyConnectionState::Disconnected:
			return;
			break;
		case LobbyConnectionState::Connecting_WaitingForResponse:
		{
			// check if response has been received
			ASSERT_OR_RETURN(, waitingForConnectionFinalize != nullptr, "Null socket set");
			ASSERT_OR_RETURN(, rs_socket != nullptr, "Null socket");
			bool exceededTimeout = (realTime - lastConnectionTime >= 10000);
			// We use readLobbyResponse to display error messages and handle state changes if there's no response
			// So if exceededTimeout, just call it with a low timeout
			auto checkSocketRet = waitingForConnectionFinalize->checkConnectionsReadable(NET_READ_TIMEOUT);
			if (!checkSocketRet.has_value())
			{
				const auto msg = checkSocketRet.error().message();
				debug(LOG_ERROR, "Lost connection to lobby server: %s", msg.c_str());
				disconnect();
				break;
			}
			if (exceededTimeout || (checkSocketRet.value() > 0 && rs_socket->readReady()))
			{
				if (readLobbyResponse(*rs_socket, NET_TIMEOUT_DELAY) == SOCKET_ERROR)
				{
					disconnect();
					break;
				}
				delete waitingForConnectionFinalize;
				waitingForConnectionFinalize = nullptr;
				currentState = LobbyConnectionState::Connected;
			}
			break;
		}
		case LobbyConnectionState::Connected:
		{
			// handle sending keep alive or queued updates
			if (!queuedServerUpdate)
			{
				if (allow_joining && shouldSendServerKeepAliveNow())
				{
					// ensure that the lobby server knows we're still alive by sending a no-op "keep-alive"
					sendKeepAlive();
				}
				break;
			}
			if (!canSendServerUpdateNow())
			{
				break;
			}
			queuedServerUpdate = false;
			sendUpdateNow();
			break;
		}
	}
}

bool NETregisterServer(int state)
{
	switch (state)
	{
		case WZ_SERVER_UPDATE:
			lobbyConnectionHandler.sendUpdate();
			break;
		case WZ_SERVER_CONNECT:
			return lobbyConnectionHandler.connect();
			break;
		case WZ_SERVER_DISCONNECT:
			return lobbyConnectionHandler.disconnect();
			break;
	}

	return false;
}

// ////////////////////////////////////////////////////////////////////////
//  Check player "slots" & update player count if needed.
void NETfixPlayerCount()
{
	ASSERT_HOST_ONLY(return);
	if (!allow_joining)
	{
		return;
	}

	int maxPlayers = game.maxPlayers;
	unsigned playercount = 0;
	for (int index = 0; index < game.maxPlayers; ++index)
	{
		if (NetPlay.players[index].ai == AI_CLOSED)
		{
			--maxPlayers;
		}
		else if (NetPlay.players[index].isSpectator)
		{
			--maxPlayers;
		}
		else if (NetPlay.players[index].ai != AI_OPEN || NetPlay.players[index].allocated)
		{
			++playercount;
		}
	}

	SpectatorInfo latestSpecInfo = SpectatorInfo::currentNetPlayState();

	if (NetPlay.playercount != playercount || gamestruct.desc.dwMaxPlayers != maxPlayers || SpectatorInfo::fromUint32(gamestruct.desc.dwUserFlags[1]) != latestSpecInfo)
	{
		debug(LOG_NET, "Updating player count from %d/%d to %d/%d", (int)NetPlay.playercount, gamestruct.desc.dwMaxPlayers, playercount, maxPlayers);
		gamestruct.desc.dwCurrentPlayers = NetPlay.playercount = playercount;
		gamestruct.desc.dwMaxPlayers = maxPlayers;
		gamestruct.desc.dwUserFlags[1] = latestSpecInfo.toUint32();
		NETregisterServer(WZ_SERVER_UPDATE);
	}

}

void NETsetLobbyConfigFlagsFields(uint8_t alliancesType, uint8_t techLevel, uint8_t powerLevel, uint8_t basesLevel)
{
	gamestruct.desc.alliances = alliancesType;
	gamestruct.desc.techLevel = techLevel;
	gamestruct.desc.powerLevel = powerLevel;
	gamestruct.desc.basesLevel = basesLevel;
}

static void NETaddSessionBanBadIP(const std::string& badIP)
{
	if (isLoopbackIP(badIP.c_str()))
	{
		return;
	}
	auto now = std::chrono::steady_clock::now();
	auto *pBadIpInfo = tmp_badIPs.tryGetPt(badIP);
	if (pBadIpInfo != nullptr)
	{
		if (now < pBadIpInfo->expiry)
		{
			if (pBadIpInfo->attempts < std::numeric_limits<size_t>::max())
			{
				pBadIpInfo->attempts++;
			}
		}
		else
		{
			pBadIpInfo->attempts = 1;
		}

		pBadIpInfo->expiry = now + std::chrono::minutes(30);

		if (pBadIpInfo->attempts == 100)
		{
			// add to permanent ban list
			addIPToBanList(badIP.c_str(), "BAD_USER");
		}
	}
	else
	{
		tmp_badIPs.insert(badIP, TmpBadIPInfo{now + std::chrono::minutes(30), 1});
	}
}

static bool quickRejectConnection(const std::string& ip)
{
	if (isLoopbackIP(ip.c_str()))
	{
		return false;
	}
	auto it = tmp_pendingIPs.find(ip);
	if (it != tmp_pendingIPs.end())
	{
		if (it->second > 1)
		{
			return true;
		}
	}
	auto *pBadIpInfo = tmp_badIPs.tryGetPt(ip);
	if (pBadIpInfo != nullptr)
	{
		if (std::chrono::steady_clock::now() < pBadIpInfo->expiry)
		{
			NETaddSessionBanBadIP(ip);
			return true;
		}
		else
		{
			// clean up expired bad entry
			tmp_badIPs.remove(ip);
			pBadIpInfo = nullptr;
		}
	}

	return false;
}

static void NEThostPromoteTempSocketToPermanentPlayerConnection(unsigned int tempSocketIdx, uint8_t index)
{
	std::string rIP = tmp_socket[tempSocketIdx]->textAddress();

	debug(LOG_NET, "freeing temp socket %p (%d), creating permanent socket.", static_cast<void *>(tmp_socket[tempSocketIdx]), __LINE__);
	tmp_socket_set->remove(tmp_socket[tempSocketIdx]);
	connected_bsocket[index] = tmp_socket[tempSocketIdx];
	tmp_socket[tempSocketIdx] = nullptr;
	NET_waitingForIndexChangeAckSince[index] = nullopt;
	server_socket_set->add(connected_bsocket[index]);
	NETmoveQueue(NETnetTmpQueue(tempSocketIdx), NETnetQueue(index));

	// Copy player's IP address
	sstrcpy(NetPlay.players[index].IPtextAddress, rIP.c_str());

	// Decrement pending IP counter
	auto it = tmp_pendingIPs.find(rIP);
	if (it != tmp_pendingIPs.end())
	{
		if (it->second > 1)
		{
			it->second--;
		}
		else
		{
			tmp_pendingIPs.erase(it);
		}
	}
}

static void NETrejectTempSocketClient(unsigned int i, uint8_t rejectedReason, bool sessionBan = false)
{
	auto w = NETbeginEncode(NETnetTmpQueue(i), NET_REJECTED);
	NETuint8_t(w, rejectedReason);
	NETstring(w, "", 0);
	NETend(w);
	NETflush();

	if (sessionBan)
	{
		NETaddSessionBanBadIP(tmp_connectState[i].ip);
	}
	NETcloseTempSocket(i);
	sync_counter.cantjoin++;
}

// ////////////////////////////////////////////////////////////////////////
// Host a game with a given name and player name. & 4 user game flags
static void NETallowJoining()
{
	ASSERT_HOST_ONLY(return);

	unsigned int i;
	int32_t result;
	bool connectFailed = true;
	uint32_t major, minor;

	if (allow_joining == false)
	{
		return;
	}

	bool bFirstTimeConnect = NETregisterServer(WZ_SERVER_CONNECT);
	if (bFirstTimeConnect)
	{
		ActivityManager::instance().updateMultiplayGameData(game, ingame, NETGameIsLocked());
		ActivitySink::ListeningInterfaces listeningInterfaces;
		if (server_listen_socket != nullptr)
		{
			const auto supportedProtocols = server_listen_socket->supportedIpVersions();
			listeningInterfaces.IPv4 = supportedProtocols & static_cast<IListenSocket::IPVersionsMask>(IListenSocket::IPVersions::IPV4);
			if (listeningInterfaces.IPv4)
			{
				listeningInterfaces.ipv4_port = NETgetGameserverPort();
			}
			listeningInterfaces.IPv6 = supportedProtocols & static_cast<IListenSocket::IPVersionsMask>(IListenSocket::IPVersions::IPV6);
			if (listeningInterfaces.IPv6)
			{
				listeningInterfaces.ipv6_port = NETgetGameserverPort();
			}
		}
		if (gamestruct.desc.host[0] != '\0')
		{
			listeningInterfaces.knownExternalAddresses = {{gamestruct.desc.host, gamestruct.hostPort, ActivitySink::ListeningInterfaces::IPType::IPv4}};
		}
		ActivityManager::instance().hostGame(gamestruct.name, NetPlay.players[NetPlay.hostPlayer].name, NETgetMasterserverName(), NETgetMasterserverPort(), listeningInterfaces, gamestruct.gameId);
	}

	// This is here since we need to get the status, before we can show the info.
	// FIXME: find better location to stick this?
	if ((!NetPlay.ShowedMOTD) && (!NetPlay.MOTD.empty()))
	{
		ShowMOTD();
		NetPlay.MOTD.clear();
		NetPlay.ShowedMOTD = true;
	}

	ASSERT(tmp_socket_set != nullptr, "Null tmp_socket_set");
	if (tmp_socket_set->checkConnectionsReadable(NET_READ_TIMEOUT).value_or(0) > 0)
	{
		for (i = 0; i < MAX_TMP_SOCKETS; ++i)
		{
			if (tmp_socket[i] == nullptr)
			{
				continue;
			}

			if (!tmp_socket[i]->readReady())
			{
				continue;
			}

			if (tmp_connectState[i].connectState == TmpSocketInfo::TmpConnectState::PendingInitialConnect)
			{
				char *p_buffer = tmp_connectState[i].buffer;

				const auto sizeReadResult = tmp_socket[i]->readNoInt(p_buffer + tmp_connectState[i].usedBuffer, 8 - tmp_connectState[i].usedBuffer, nullptr);
				if (sizeReadResult.has_value())
				{
					tmp_connectState[i].usedBuffer += sizeReadResult.value();
				}

				// A 2.3.7 client sends a "list" command first, just drop the connection.
				if (tmp_connectState[i].usedBuffer >= 5 && (strcmp(tmp_connectState[i].buffer, "list") == 0))
				{
					debug(LOG_INFO, "An old client tried to connect, closing the socket.");
					NETlogEntry("Dropping old client.", SYNC_FLAG, i);
					NETlogEntry("Invalid (old)game version", SYNC_FLAG, i);
					NETaddSessionBanBadIP(tmp_connectState[i].ip);
					connectFailed = true;
				}
				else if (tmp_connectState[i].usedBuffer >= 8)
				{
					// New clients send NETCODE_VERSION_MAJOR and NETCODE_VERSION_MINOR
					// Check these numbers with our own.

					memcpy(&major, p_buffer, sizeof(uint32_t));
					major = wz_ntohl(major);
					p_buffer += sizeof(int32_t);
					memcpy(&minor, p_buffer, sizeof(uint32_t));
					minor = wz_ntohl(minor);

					if (major == 0 && minor == 0)
					{
						// special case for lobby server "alive" check
						// expects a special response that includes the gameId
						const char ResponseStart[] = "WZLR";
						char buf[(sizeof(char) * 4) + sizeof(uint32_t) + sizeof(uint32_t)] = { 0 };
						char *pLobbyRespBuffer = buf;
						auto push32 = [&pLobbyRespBuffer](uint32_t value) {
							uint32_t swapped = wz_htonl(value);
							memcpy(pLobbyRespBuffer, &swapped, sizeof(swapped));
							pLobbyRespBuffer += sizeof(swapped);
						};

						// Copy response prefix chars ("WZLR")
						memcpy(pLobbyRespBuffer, ResponseStart, sizeof(char) * strlen(ResponseStart));
						pLobbyRespBuffer += sizeof(char) * strlen(ResponseStart);

						// Copy version of response
						const uint32_t response_version = 1;
						push32(response_version);

						// Copy gameId (as 32bit large big endian number)
						push32(gamestruct.gameId);

						const auto writeResult = tmp_socket[i]->writeAll(buf, sizeof(buf), nullptr);
						if (!writeResult.has_value())
						{
							debug(LOG_NET, "writeAll to tmpSocket[%u] failed with error?: %d", i, writeResult.error().value());
						}
						connectFailed = true;
					}
					else if (NETisCorrectVersion(major, minor))
					{
						result = wz_htonl(ERROR_NOERROR);
						memcpy(&tmp_connectState[i].buffer, &result, sizeof(result));
						const auto writeResult = tmp_socket[i]->writeAll(&tmp_connectState[i].buffer, sizeof(result), nullptr);
						if (!writeResult.has_value())
						{
							debug(LOG_NET, "writeAll to tmpSocket[%u] failed with error?: %d", i, writeResult.error().value());
						}
						tmp_socket[i]->enableCompression();

						// Connection is successful.
						connectFailed = false;

						// Give client a challenge to solve before connecting
						tmp_connectState[i].connectChallenge.resize(NETgetJoinConnectionNETPINGChallengeFromHostSize());
						genSecRandomBytes(tmp_connectState[i].connectChallenge.data(), tmp_connectState[i].connectChallenge.size());
						auto w = NETbeginEncode(NETnetTmpQueue(i), NET_PING);
						NETbytes(w, tmp_connectState[i].connectChallenge);
						// Send the server's public identity
						// - As long as host is a spectator host, or this is a regular (non-blind) game, this is always the host's actual public identity
						// - If host is a player-host *and* this is a blind game, it's the blind identity
						EcKey::Key serverPublicKey = getLocalSharedIdentity().toBytes(EcKey::Public);
						NETbytes(w, serverPublicKey);
						NETend(w);
					}
					else
					{
						debug(LOG_INFO, "Received an invalid version \"%" PRIu32 ".%" PRIu32 "\".", major, minor);
						result = wz_htonl(ERROR_WRONGVERSION);
						memcpy(&tmp_connectState[i].buffer, &result, sizeof(result));
						const auto writeResult = tmp_socket[i]->writeAll(&tmp_connectState[i].buffer, sizeof(result), nullptr);
						if (!writeResult.has_value())
						{
							debug(LOG_NET, "writeAll to tmpSocket[%u] failed with error?: %d", i, writeResult.error().value());
						}
						NETlogEntry("Invalid game version", SYNC_FLAG, i);
						NETaddSessionBanBadIP(tmp_connectState[i].ip);
						connectFailed = true;
					}
					if ((!connectFailed) && (!NET_HasAnyOpenSlots()))
					{
						// early player count test, in case they happen to get in before updates.
						// Tell the player that we are completely full.
						uint8_t rejected = ERROR_FULL;
						auto w = NETbeginEncode(NETnetTmpQueue(i), NET_REJECTED);
						NETuint8_t(w, rejected);
						NETend(w);
						NETflush();
						connectFailed = true;
					}
				}
				else
				{
					// Continue to wait (until timeout) for the full initial connect message
					continue;
				}

				// Remove a failed connection.
				if (connectFailed)
				{
					debug(LOG_NET, "freeing temp socket %p (%d)", static_cast<void *>(tmp_socket[i]), __LINE__);
					NETcloseTempSocket(i);
				}
				else
				{
					// on initial connect success...
					tmp_connectState[i].connectState = TmpSocketInfo::TmpConnectState::PendingJoinRequest;
					tmp_connectState[i].connectTime = std::chrono::steady_clock::now(); // reset connect time
				}
				continue;
			}
			else if (tmp_connectState[i].connectState == TmpSocketInfo::TmpConnectState::PendingJoinRequest)
			{
				uint8_t buffer[MaxMsgSize];
				const auto readResult = tmp_socket[i]->readNoInt(buffer, sizeof(buffer), nullptr);
				uint8_t rejected = 0;

				if (!readResult.has_value())
				{
					// disconnect or programmer error
					if (readResult.error() == std::errc::timed_out || readResult.error() == std::errc::connection_reset)
					{
						debug(LOG_NET, "Client socket disconnected.");
					}
					else
					{
						const auto readErrMsg = readResult.error().message();
						debug(LOG_NET, "Client socket encountered error: %s", readErrMsg.c_str());
					}
					NETlogEntry("Client socket disconnected (allowJoining)", SYNC_FLAG, i);
					debug(LOG_NET, "freeing temp socket %p (%d)", static_cast<void *>(tmp_socket[i]), __LINE__);
					NETcloseTempSocket(i);
					continue;
				}
				const auto size = readResult.value();
				NETinsertRawData(NETnetTmpQueue(i), buffer, static_cast<size_t>(size));

				if (!NETisMessageReady(NETnetTmpQueue(i)))
				{
					// need to wait for a full and complete join message
					// sanity check
					if (NETincompleteMessageDataBuffered(NETnetTmpQueue(i)) > (MaxMsgSize * 8))	// something definitely big enough to encompass the expected message(s) at this point
					{
						// client is sending data that doesn't appear to be a properly formatted message - cut it off
						NETpop(NETnetTmpQueue(i));
						NETrejectTempSocketClient(i, ERROR_WRONGDATA, true);
					}
					continue;
				}

				if (NETgetMessage(NETnetTmpQueue(i))->type() == NET_JOIN)
				{
					char name[StringSize] = { '\0' };
					char ModList[modlist_string_size] = { '\0' };
					char GamePassword[password_string_size] = { '\0' };
					uint8_t playerType = 0;
					EcKey::Key pkey;
					EcKey identity;
					std::vector<uint8_t> encryptedChallengeResponse;

					auto r = NETbeginDecode(NETnetTmpQueue(i), NET_JOIN);
					{
						NETstring(r, name, sizeof(name));
						NETstring(r, ModList, sizeof(ModList));
						NETstring(r, GamePassword, sizeof(GamePassword));
						NETuint8_t(r, playerType);
						NETbytes(r, pkey);
						NETbytes(r, encryptedChallengeResponse);
					}
					NETend(r);
					NETpop(NETnetTmpQueue(i));

					// Determine if it's a valid public identity
					if (!identity.fromBytes(pkey, EcKey::Public))
					{
						// Invalid public identity provided - just reject
						auto rejectMsg = astringf("**Rejecting player(%s), invalid player identity.", tmp_connectState[i].ip.c_str());
						debug(LOG_INFO, "%s", rejectMsg.c_str());
						debug(LOG_NET, "freeing temp socket %p, invalid player identity", static_cast<void *>(tmp_socket[i]));

						NETrejectTempSocketClient(i, ERROR_WRONGDATA, true);
						continue;
					}

					// Do an initial pass of blacklist checks (even though we haven't verified the identity yet)
					auto connectPermissions = netPermissionsCheck_Connect(identity);
					if ((connectPermissions.has_value() && connectPermissions.value() == ConnectPermissions::Blocked)
						|| (!connectPermissions.has_value() && onBanList(tmp_connectState[i].ip.c_str())))
					{
						char buf[256] = {'\0'};
						ssprintf(buf, "** A player that you have kicked tried to rejoin the game, and was rejected. IP: %s", tmp_connectState[i].ip.c_str());
						debug(LOG_INFO, "%s", buf);
						NETlogEntry(buf, SYNC_FLAG, i);

						NETrejectTempSocketClient(i, ERROR_KICKED, false);
						continue;
					}

					// Save join info in the tmp_connectState
					sstrcpy(tmp_connectState[i].receivedJoinInfo.name, name);
					tmp_connectState[i].receivedJoinInfo.playerType = playerType;
					tmp_connectState[i].receivedJoinInfo.identity = identity;

					auto& joinRequestInfo = tmp_connectState[i].receivedJoinInfo;

					// Construct the auth session keys
					try {
						tmp_connectState[i].receivedJoinInfo.connectionAuthSessionKeys = std::make_unique<SessionKeys>(getLocalSharedIdentity(), 0, identity, 1);
					}
					catch (const std::invalid_argument& e) {
						auto rejectMsg = astringf("**Rejecting player(%s), failed to establish session keys, error: %s", tmp_connectState[i].ip.c_str(), e.what());
						debug(LOG_INFO, "%s", rejectMsg.c_str());
						debug(LOG_NET, "freeing temp socket %p, couldn't establish session keys", static_cast<void *>(tmp_socket[i]));
						NETrejectTempSocketClient(i, ERROR_WRONGDATA, false);
						continue;
					}

					// Decrypt the encryptedChallengeResponse
					std::vector<uint8_t> decryptedMessageRawData;
					if (!tmp_connectState[i].receivedJoinInfo.connectionAuthSessionKeys->decryptMessageFromOther(&(encryptedChallengeResponse[0]), encryptedChallengeResponse.size(), decryptedMessageRawData))
					{
						auto rejectMsg = astringf("**Rejecting player(%s), failed to decrypt player auth data", tmp_connectState[i].ip.c_str());
						debug(LOG_INFO, "%s", rejectMsg.c_str());
						debug(LOG_NET, "freeing temp socket %p, couldn't verify player identity", static_cast<void *>(tmp_socket[i]));
						NETrejectTempSocketClient(i, ERROR_WRONGDATA, true);
						continue;
					}
					NetMessageBuilder tmpMessageBuilder(NET_JOIN, decryptedMessageRawData.size()); // dummy message for parsing
					tmpMessageBuilder.append(decryptedMessageRawData.data(), decryptedMessageRawData.size());
					NETinsertMessageFromNet(NETnetTmpQueue(i), tmpMessageBuilder.build()); // insert virtual message into temp queue for parsing

					// Parse the decrypted response
					EcKey::Sig challengeResponse;
					std::vector<uint8_t> connectionDescriptionSerializedBytes;
					std::vector<uint8_t> challengeForHost(NETgetJoinConnectionNETPINGChallengeFromClientSize(), 0);
					auto r2 = NETbeginDecode(NETnetTmpQueue(i), NET_JOIN);
					{
						NETbytes(r2, challengeResponse);
						NETbytes(r2, connectionDescriptionSerializedBytes);
						NETbytes(r2, challengeForHost);
					}
					NETend(r2);
					NETpop(NETnetTmpQueue(i));

					// Verify signature that player is joining with - reject on failure
					if (!identity.verify(challengeResponse, tmp_connectState[i].connectChallenge.data(), tmp_connectState[i].connectChallenge.size()))
					{
						auto rejectMsg = astringf("**Rejecting player(%s), failed to verify player identity.", tmp_connectState[i].ip.c_str());
						debug(LOG_INFO, "%s", rejectMsg.c_str());
						debug(LOG_NET, "freeing temp socket %p, couldn't verify player identity", static_cast<void *>(tmp_socket[i]));
						NETrejectTempSocketClient(i, ERROR_WRONGDATA, true);
						continue;
					}

					// Verify that the challengeForHost is expected length
					if (!challengeForHost.empty() && challengeForHost.size() != NETgetJoinConnectionNETPINGChallengeFromClientSize())
					{
						auto rejectMsg = astringf("**Rejecting player(%s), invalid host challenge length.", tmp_connectState[i].ip.c_str());
						debug(LOG_INFO, "%s", rejectMsg.c_str());
						debug(LOG_NET, "freeing temp socket %p, invalid host challenge length", static_cast<void *>(tmp_socket[i]));
						NETrejectTempSocketClient(i, ERROR_WRONGDATA, true);
						continue;
					}
					tmp_connectState[i].receivedJoinInfo.challengeForHost = std::move(challengeForHost);
					challengeForHost.clear();

					// Additional rejection checks
					if (joinRequestInfo.playerType != NET_JOIN_SPECTATOR && !bAsyncJoinApprovalEnabled && playerManagementRecord.hostMovedPlayerToSpectators(tmp_connectState[i].ip))
					{
						// The host previously relegated a player from this IP address to Spectators (this game), and it seems they are trying to rejoin as a Player - deny this
						char buf[256] = {'\0'};
						ssprintf(buf, "** A player that you moved to Spectators tried to rejoin the game (as a Player), and was rejected. IP: %s", tmp_connectState[i].ip.c_str());
						debug(LOG_INFO, "%s", buf);
						NETlogEntry(buf, SYNC_FLAG, i);

						// Player has been kicked before, kick again.
						rejected = (uint8_t)ERROR_KICKED;
					}
					else if (NetPlay.GamePassworded && strcmp(NetPlay.gamePassword, GamePassword) != 0)
					{
						// Wrong password. Reject.
						rejected = (uint8_t)ERROR_WRONGPASSWORD;
					}
					else if ((int)NetPlay.playercount > gamestruct.desc.dwMaxPlayers)
					{
						// Game full. Reject.
						rejected = (uint8_t)ERROR_FULL;
					}

					if (rejected)
					{
						char buf[256] = {'\0'};
						ssprintf(buf, "**Rejecting player(%s), reason (%u).", tmp_connectState[i].ip.c_str(), (unsigned int) rejected);
						debug(LOG_INFO, "%s", buf);
						NETlogEntry(buf, SYNC_FLAG, i);
						auto w = NETbeginEncode(NETnetTmpQueue(i), NET_REJECTED);
						NETuint8_t(w, rejected);
						NETstring(w, "", 0);
						NETend(w);
						NETflush();

						NETcloseTempSocket(i);
						sync_counter.cantjoin++;
						continue;
					}

					// on passing all built-in checks for connect...
					if (bAsyncJoinApprovalEnabled)
					{
						tmp_connectState[i].connectState = TmpSocketInfo::TmpConnectState::PendingAsyncApproval;

						// use the connectChallenge as a unique, random join ID
						tmp_connectState[i].uniqueJoinID = base64Encode(tmp_connectState[i].connectChallenge);

						std::string joinerPublicKeyB64 = base64Encode(joinRequestInfo.identity.toBytes(EcKey::Public));
						std::string joinerIdentityHash = joinRequestInfo.identity.publicHashString();
						std::string joinerName = joinRequestInfo.name;
						std::string joinerNameB64 = base64Encode(std::vector<unsigned char>(joinerName.begin(), joinerName.end()));
						wz_command_interface_output("WZEVENT: join approval needed: %s %s %s %s %s %s\n", tmp_connectState[i].uniqueJoinID.c_str(), tmp_connectState[i].ip.c_str(), joinerIdentityHash.c_str(), joinerPublicKeyB64.c_str(), joinerNameB64.c_str(), (joinRequestInfo.playerType == NET_JOIN_SPECTATOR) ? "spec" : "play");
					}
					else
					{
						// if async join approval is not enabled, go directly to pending success
						tmp_connectState[i].connectState = TmpSocketInfo::TmpConnectState::ProcessJoin;
					}
					tmp_connectState[i].connectTime = std::chrono::steady_clock::now(); // reset connect time
				}
				else
				{
					// unexpected message type at this time
					// reject the bad client
					NETpop(NETnetTmpQueue(i));
					NETrejectTempSocketClient(i, ERROR_WRONGDATA, true);
				}
				continue;
			}
		}
	}

	auto currentSteadTime = std::chrono::steady_clock::now();

	for (i = 0; i < MAX_TMP_SOCKETS; ++i)
	{
		if (tmp_socket[i] == nullptr)
		{
			continue;
		}

		if (tmp_connectState[i].connectState == TmpSocketInfo::TmpConnectState::PendingAsyncApproval)
		{
			// check if async approval result has been set
			if (tmp_connectState[i].asyncJoinApprovalResult.has_value())
			{
				if (tmp_connectState[i].asyncJoinApprovalResult.value() != AsyncJoinApprovalAction::Reject)
				{
					// async join approved - process the join
					tmp_connectState[i].connectState = TmpSocketInfo::TmpConnectState::ProcessJoin;
					tmp_connectState[i].connectTime = std::chrono::steady_clock::now(); // reset connect time
					if (tmp_connectState[i].asyncJoinApprovalResult.value() == AsyncJoinApprovalAction::ApproveSpectators)
					{
						// change the player join request to spectators
						tmp_connectState[i].receivedJoinInfo.playerType = NET_JOIN_SPECTATOR;
						// enforce spectator state for this player
						playerManagementRecord.movedPlayerToSpectators(tmp_connectState[i].ip, tmp_connectState[i].receivedJoinInfo.identity.toBytes(EcKey::Privacy::Public), true);
					}
					else if (tmp_connectState[i].asyncJoinApprovalResult.value() == AsyncJoinApprovalAction::Approve)
					{
						// clear any enforced spectator state for this player
						playerManagementRecord.movedSpectatorToPlayers(tmp_connectState[i].ip, tmp_connectState[i].receivedJoinInfo.identity.toBytes(EcKey::Privacy::Public), true);
					}
					// deliberately fall-through to the TmpSocketInfo::TmpConnectState::ProcessJoin condition further below
				}
				else
				{
					// async join rejected
					uint8_t rejected = static_cast<uint8_t>(tmp_connectState[i].asyncJoinRejectCode);
					char buf[256] = {'\0'};
					ssprintf(buf, "**Rejecting player(%s), due to async approval rejection, reason (%u).", tmp_connectState[i].ip.c_str(), static_cast<unsigned int>(rejected));
					debug(LOG_INFO, "%s", buf);
					NETlogEntry(buf, SYNC_FLAG, i);
					auto w = NETbeginEncode(NETnetTmpQueue(i), NET_REJECTED);
					NETuint8_t(w, rejected);
					uint16_t maxrejectlen = std::min<uint16_t>(MAX_JOIN_REJECT_REASON, tmp_connectState[i].asyncJoinRejectCustomMessage.size() + 1);
					NETstring(w, tmp_connectState[i].asyncJoinRejectCustomMessage.c_str(), maxrejectlen);

					if (rejected == ERROR_REDIRECT)
					{
						// construct + send encrypted client challenge response
						const TmpSocketInfo::ReceivedJoinInfo& joinRequestInfo = tmp_connectState[i].receivedJoinInfo;
						std::vector<uint8_t> encryptedHostChallengeResponse;
						if (!joinRequestInfo.challengeForHost.empty())
						{
							EcKey::Sig hostChallengeResponse = getLocalSharedIdentity().sign(joinRequestInfo.challengeForHost.data(), joinRequestInfo.challengeForHost.size());
							encryptedHostChallengeResponse = joinRequestInfo.connectionAuthSessionKeys->encryptMessageForOther(&hostChallengeResponse[0], hostChallengeResponse.size());
							if (encryptedHostChallengeResponse.empty())
							{
								debug(LOG_INFO, "Failed to encrypt response?");
							}
						}
						NETbytes(w, encryptedHostChallengeResponse);
					}

					NETend(w);
					NETflush();
					auto tmpQueue = NETnetTmpQueue(i);
					if (NETisMessageReady(tmpQueue))
					{
						NETpop(tmpQueue);
					}

					NETcloseTempSocket(i);
					sync_counter.cantjoin++;
					continue; // continue to next tmp_socket
				}
			}
			else
			{
				// if no async approval, do a timeout check
				std::chrono::milliseconds::rep timeout = 8000; // although the client no longer blocks on join, a response should still be relatively prompt (the client has its own timeout)
				if (std::chrono::duration_cast<std::chrono::milliseconds>(currentSteadTime - tmp_connectState[i].connectTime).count() > timeout)
				{
					debug(LOG_INFO, "Freeing temp socket %p due to async connection approval timeout (IP: %s)", static_cast<void *>(tmp_socket[i]), tmp_connectState[i].ip.c_str());

					uint8_t rejected = ERROR_HOSTDROPPED;
					auto w = NETbeginEncode(NETnetTmpQueue(i), NET_REJECTED);
					NETuint8_t(w, rejected);
					NETstring(w, "", 0);
					NETend(w);
					NETflush();
					auto tmpQueue = NETnetTmpQueue(i);
					if (NETisMessageReady(tmpQueue))
					{
						NETpop(tmpQueue);
					}
					NETcloseTempSocket(i);
				}
				continue; // continue to next tmp_socket
			}
		}
		// note: *not* an "else if" because the condition above may transition the state to ProcessJoin!
		if (tmp_connectState[i].connectState == TmpSocketInfo::TmpConnectState::ProcessJoin)
		{
			bool previousPlayersShouldCheckReadyValue = multiplayPlayersShouldCheckReady();
			optional<uint32_t> tmp = nullopt;

			if (tmp_connectState[i].asyncJoinApprovalExplicitPlayerIdx.has_value())
			{
				// Try to allocate the new player at the explicit index
				if (NET_IsSlotOpenForPlayerJoin(tmp_connectState[i].asyncJoinApprovalExplicitPlayerIdx.value())
					&& NET_CreatePlayerAtIdx(tmp_connectState[i].asyncJoinApprovalExplicitPlayerIdx.value(), tmp_connectState[i].receivedJoinInfo.name))
				{
					tmp = tmp_connectState[i].asyncJoinApprovalExplicitPlayerIdx.value();
				}
				else
				{
					debug(LOG_INFO, "Async join approval provided explicit player index (%" PRIu32 "), but it's occupied", tmp_connectState[i].asyncJoinApprovalExplicitPlayerIdx.value());
				}
			}
			else
			{
				// Try to allocate the new player an open slot
				if ((tmp_connectState[i].receivedJoinInfo.playerType == NET_JOIN_SPECTATOR) || (int)NetPlay.playercount <= gamestruct.desc.dwMaxPlayers)
				{
					tmp = NET_CreatePlayer(tmp_connectState[i].receivedJoinInfo.name, false, (tmp_connectState[i].receivedJoinInfo.playerType == NET_JOIN_SPECTATOR));
				}
			}

			if (!tmp.has_value() || tmp.value() > static_cast<uint32_t>(std::numeric_limits<uint8_t>::max()))
			{
				ASSERT(tmp.value_or(0) <= static_cast<uint32_t>(std::numeric_limits<uint8_t>::max()), "Currently limited to uint8_t");
				debug(LOG_INFO, "freeing temp socket %p, couldn't create slot", static_cast<void *>(tmp_socket[i]));

				// Tell the player that we are full.
				NETrejectTempSocketClient(i, ERROR_FULL, false);
				continue; // continue to next tmp_socket
			}

			uint8_t index = static_cast<uint8_t>(tmp.value());

			TmpSocketInfo::ReceivedJoinInfo joinRequestInfo = std::move(tmp_connectState[i].receivedJoinInfo); // keep the join info
			tmp_connectState[i].reset();

			NEThostPromoteTempSocketToPermanentPlayerConnection(i, index);

			// construct encrypted client challenge response
			std::vector<uint8_t> encryptedHostChallengeResponse;
			if (!joinRequestInfo.challengeForHost.empty())
			{
				EcKey::Sig hostChallengeResponse = getLocalSharedIdentity().sign(joinRequestInfo.challengeForHost.data(), joinRequestInfo.challengeForHost.size());
				encryptedHostChallengeResponse = joinRequestInfo.connectionAuthSessionKeys->encryptMessageForOther(&hostChallengeResponse[0], hostChallengeResponse.size());
				if (encryptedHostChallengeResponse.empty())
				{
					debug(LOG_INFO, "Failed to encrypt response?");
				}
			}

			// Send NET_ACCEPTED
			{
				auto w = NETbeginEncode(NETnetQueue(index), NET_ACCEPTED);
				NETuint8_t(w, index);
				NETuint32_t(w, NetPlay.hostPlayer);
				uint8_t blindModeVal = static_cast<uint8_t>(game.blindMode);
				NETuint8_t(w, blindModeVal);
				NETbytes(w, encryptedHostChallengeResponse);
				NETend(w);
			}

			// First send info about players to newcomer.
			NETSendAllPlayerInfoTo(index);
			// then send info about newcomer to all players.
			NETBroadcastPlayerInfo(index);

			char buf[250] = {'\0'};
			const char* pPlayerType = (NetPlay.players[index].isSpectator) ? "Spectator" : "Player";
			snprintf(buf, sizeof(buf), "%s[%" PRIu8 "] %s has joined, IP is: %s", pPlayerType, index, getPlayerName(index), NetPlay.players[index].IPtextAddress);
			debug(LOG_INFO, "%s", buf);
			NETlogEntry(buf, SYNC_FLAG, index);

			debug(LOG_NET, "%s, %s, with index of %u has joined using socket %p", pPlayerType, getPlayerName(index), (unsigned int)index, static_cast<void *>(connected_bsocket[index]));

			// Increment player count
			gamestruct.desc.dwCurrentPlayers++;

			MultiPlayerJoin(index, joinRequestInfo.identity.toBytes(EcKey::Public));

			handlePossiblePlayersShouldCheckReadyChange(previousPlayersShouldCheckReadyValue);

			if (wz_command_interface_enabled())
			{
				std::string joinerPublicKeyB64 = base64Encode(joinRequestInfo.identity.toBytes(EcKey::Public));
				std::string joinerIdentityHash = joinRequestInfo.identity.publicHashString();
				std::string joinerName = joinRequestInfo.name;
				std::string joinerNameB64 = base64Encode(std::vector<unsigned char>(joinerName.begin(), joinerName.end()));
				wz_command_interface_output("WZEVENT: player join: %u %s %s %s %s\n", index, joinerPublicKeyB64.c_str(), joinerIdentityHash.c_str(), NetPlay.players[index].IPtextAddress, joinerNameB64.c_str());
			}

			// Broadcast to everyone that a new player has joined
			{
				auto w = NETbeginEncode(NETbroadcastQueue(), NET_PLAYER_JOINED);
				NETuint8_t(w, index);
				NETend(w);
			}

			for (uint8_t j = 0; j < MAX_CONNECTED_PLAYERS; ++j)
			{
				NETBroadcastPlayerInfo(j);
			}
			NETfixDuplicatePlayerNames();

			// Send the updated GAMESTRUCT to the masterserver
			NETregisterServer(WZ_SERVER_UPDATE);

			// reset flags for new players
			if (NetPlay.players[index].wzFiles)
			{
				NetPlay.players[index].wzFiles->clear();
			}
			else
			{
				ASSERT(false, "wzFiles is uninitialized?? (Player: %" PRIu8 ")", index);
			}

			wz_command_interface_output_room_status_json();

			continue; // continue to next tmp_socket
		}

		// in all other cases, do a timeout check
		std::chrono::milliseconds::rep timeout = (tmp_connectState[i].connectState == TmpSocketInfo::TmpConnectState::PendingInitialConnect) ? 2500 : 3000;

		if (std::chrono::duration_cast<std::chrono::milliseconds>(currentSteadTime - tmp_connectState[i].connectTime).count() > timeout)
		{
			debug(LOG_INFO, "Freeing temp socket %p due to initial connection timeout (IP: %s)", static_cast<void *>(tmp_socket[i]), tmp_connectState[i].ip.c_str());

			uint8_t rejected = 0;
			rejected = ERROR_WRONGDATA;
			auto w = NETbeginEncode(NETnetTmpQueue(i), NET_REJECTED);
			NETuint8_t(w, rejected);
			NETstring(w, "", 0);
			NETend(w);
			NETflush();
			auto tmpQueue = NETnetTmpQueue(i);
			if (NETisMessageReady(tmpQueue))
			{
				NETpop(tmpQueue);
			}

			std::string rIP = tmp_socket[i]->textAddress();
			NETaddSessionBanBadIP(rIP);

			NETcloseTempSocket(i);
			sync_counter.cantjoin++;
		}
	}
}

namespace
{

// Set the fields for GAMESTRUCT structure to announce it to the lobby server and other players.
//
// `gamestruct.desc.host` will be filled with `externalIp` contents if it's not empty.
//
// If `extPort == 0`, then `gamestruct.hostPort` will be filled with the default value from the configuration file,
// otherwise, it will be set to `extPort`.
void SetupGameStructInfo(const char* SessionName, const char* PlayerName, const std::string& externalIp, uint16_t extPort, bool spectatorHost, uint32_t plyrs, uint32_t gameType, uint32_t two, uint32_t blindMode, uint32_t four, uint8_t alliancesType, uint8_t techLevel, uint8_t powerLevel, uint8_t basesLevel)
{
	sstrcpy(gamestruct.name, SessionName);
	memset(&gamestruct.desc, 0, sizeof(gamestruct.desc));
	gamestruct.desc.dwSize = sizeof(gamestruct.desc);
	//gamestruct.desc.guidApplication = GAME_GUID;
	if (!externalIp.empty())
	{
		sstrcpy(gamestruct.desc.host, externalIp.c_str());
		gamestruct.desc.host[externalIp.length()] = '\0';
	}
	else
	{
		memset(gamestruct.desc.host, 0, sizeof(gamestruct.desc.host));
	}
	gamestruct.desc.dwCurrentPlayers = (!spectatorHost) ? 1 : 0;
	gamestruct.desc.dwMaxPlayers = plyrs;
	gamestruct.desc.alliances = alliancesType;
	gamestruct.desc.techLevel = techLevel;
	gamestruct.desc.powerLevel = powerLevel;
	gamestruct.desc.basesLevel = basesLevel;
	gamestruct.desc.dwUserFlags[0] = gameType;
	gamestruct.desc.dwUserFlags[1] = two;
	gamestruct.desc.dwUserFlags[2] = blindMode;
	gamestruct.desc.dwUserFlags[3] = four;
	memset(gamestruct.secondaryHosts, 0, sizeof(gamestruct.secondaryHosts));
	sstrcpy(gamestruct.extra, "Extra");						// extra string (future use)
	if (extPort == 0)
	{
		gamestruct.hostPort = gameserver_port;
	}
	else
	{
		gamestruct.hostPort = extPort;
	}
	sstrcpy(gamestruct.mapname, game.map);					// map we are hosting
	sstrcpy(gamestruct.hostname, PlayerName);
	sstrcpy(gamestruct.versionstring, versionString);		// version (string)
	sstrcpy(gamestruct.modlist, getModList().c_str());      // List of mods
	gamestruct.GAMESTRUCT_VERSION = 4;						// version of this structure
	gamestruct.game_version_major = NETCODE_VERSION_MAJOR;	// Netcode Major version
	gamestruct.game_version_minor = NETCODE_VERSION_MINOR;	// NetCode Minor version
	//	gamestruct.privateGame = 0;								// if true, it is a private game
	gamestruct.pureMap = game.isMapMod;								// If map-mod...
	gamestruct.Mods = 0;										// number of concatenated mods?
	gamestruct.gameId = 0;
	gamestruct.limits = 0x0;									// used for limits
#if defined(WZ_OS_WIN)
	gamestruct.future3 = 0x77696e;								// for future use
#elif defined (WZ_OS_MAC)
	gamestruct.future3 = 0x6d6163;								// for future use
#else
	gamestruct.future3 = 0x6c696e;								// for future use
#endif
	gamestruct.future4 = NETCODE_VERSION_MAJOR << 16 | NETCODE_VERSION_MINOR;	// for future use
}

} // anonymous namespace

static void NETEnableAllowJoining(const std::string& externalIp, uint16_t extPort)
{
	ASSERT_HOST_ONLY(return);
	ASSERT_OR_RETURN(, !allow_joining, "allow_joining already true!");

	// Once this is true, we are able to connect to the lobby server and announce to other players that
	// this game session is available to join to.
	allow_joining = true;

	std::string connType = (activeConnProvider) ? to_string(activeConnProvider->type()) : std::string();
	std::string outputExternalIP = (!externalIp.empty()) ? externalIp : "unknown";
	std::string outputGamePassword = (NETGameIsLocked()) ? NetPlay.gamePassword : "";
	wz_command_interface_output("WZEVENT: readyForJoins: %s %" PRIu16 " %s %s\n", connType.c_str(), extPort, outputExternalIP.c_str(), outputGamePassword.c_str());

	debug(LOG_NET, "Hosting a server. We are player %d.", selectedPlayer);
}

bool NEThostGame(const char *SessionName, const char *PlayerName, bool spectatorHost,
                 uint32_t gameType, uint32_t two, uint32_t blindMode, uint32_t four,
                 UDWORD plyrs,	// # of players
                 uint8_t alliancesType, uint8_t techLevel, uint8_t powerLevel, uint8_t basesLevel)
{
	debug(LOG_NET, "NEThostGame(%s, %s, %" PRIu32 ", %" PRIu32 ", %" PRIu32 ", %" PRIu32 ", %u)", SessionName, PlayerName,
		  gameType, two, blindMode, four, plyrs);

	netPlayersUpdated = true;

	for (unsigned playerIndex = 0; playerIndex < MAX_CONNECTED_PLAYERS; ++playerIndex)
	{
		initPlayerNetworkProps(playerIndex);
	}
	if (!NetPlay.bComms)
	{
		ASSERT(!spectatorHost, "spectatorHost flag will be ignored");
		selectedPlayer			= 0;
		NetPlay.isHost			= true;
		NetPlay.hostPlayer 		= selectedPlayer;
		NetPlay.players[0].allocated	= true;
		NetPlay.players[0].difficulty	= AIDifficulty::HUMAN;
		NetPlay.playercount		= 1;
		debug(LOG_NET, "Hosting but no comms");
		// Now switch player color of the host to what they normally use for MP games
		if (war_getMPcolour() >= 0)
		{
			changeColour(NetPlay.hostPlayer, war_getMPcolour(), realSelectedPlayer);
		}
		return true;
	}

	ASSERT_OR_RETURN(false, activeConnProvider != nullptr, "Active connection provider is not set!");

	// Start listening for client connections on `gameserver_port`.
	// These will initially be assigned to `tmp_socket[i]` until accepted in the game session,
	// in which case `tmp_socket[i]` will be assigned to `connected_bsocket[i]` and `tmp_socket[i]`
	// will become nullptr.
	net::result<IListenSocket*> serverListenResult = {};
	if (!server_listen_socket)
	{
		debug(LOG_INFO, "Opening listening socket (backend: %s)", to_string(activeConnProvider->type()).c_str());
		serverListenResult = activeConnProvider->openListenSocket(gameserver_port);
		server_listen_socket = serverListenResult.value_or(nullptr);
	}
	if (server_listen_socket == nullptr)
	{
		const auto sockErrMsg = serverListenResult.error().message();
		debug(LOG_ERROR, "Cannot open listening connection: %s", sockErrMsg.c_str());
		if (wz_command_interface_enabled())
		{
			std::string sockErrMsgB64 = base64Encode(std::vector<unsigned char>(sockErrMsg.begin(), sockErrMsg.end()));
			wz_command_interface_output("WZEVENT: serverListenSocketFailed: %d %s\n", serverListenResult.error().value(), sockErrMsgB64.c_str());
		}
		return false;
	}
	debug(LOG_NET, "New server_listen_socket = %p", static_cast<void *>(server_listen_socket));
	// Host needs to create a socket set for MAX_PLAYERS
	if (!server_socket_set)
	{
		server_socket_set = activeConnProvider->newConnectionPollGroup();
	}
	// allocate socket storage for all possible players
	for (unsigned i = 0; i < MAX_CONNECTED_PLAYERS; ++i)
	{
		connected_bsocket[i] = nullptr;
		NETinitQueue(NETnetQueue(i));
	}

	NetPlay.isHost = true;
	NETlogEntry("Hosting game, resetting ban list.", SYNC_FLAG, 0);
	NETpermissionsInit();
	playerManagementRecord.clear();

	if (spectatorHost)
	{
		// open one spectator slot for the host
		ASSERT(_NET_openNewSpectatorSlot_internal(false).has_value(), "Unable to open spectator slot for host??");
	}
	optional<uint32_t> newHostPlayerIdx = NET_CreatePlayer(PlayerName, (getHostLaunch() == HostLaunch::Autohost), spectatorHost);
	ASSERT_OR_RETURN(false, newHostPlayerIdx.has_value() && (newHostPlayerIdx.value() < MAX_PLAYERS || (spectatorHost && newHostPlayerIdx.value() < MAX_CONNECTED_PLAYERS)), "Failed to create player");
	selectedPlayer = newHostPlayerIdx.value();
	realSelectedPlayer = selectedPlayer;
	NetPlay.isHost	= true;
	NetPlay.isHostAlive = true;
	NetPlay.HaveUpgrade = false;
	NetPlay.hostPlayer	= selectedPlayer;

	MultiPlayerJoin(selectedPlayer, nullopt);

	// Now switch player color of the host to what they normally use for SP games
	if (NetPlay.hostPlayer < MAX_PLAYERS && war_getMPcolour() >= 0)
	{
		changeColour(NetPlay.hostPlayer, war_getMPcolour(), realSelectedPlayer);
	}

	NETregisterServer(WZ_SERVER_DISCONNECT);

	if (ipv4MappingRequest)
	{
		// Do not allow others to join and delay announcing the game session to the lobby server
		// until we manage to setup (successfully or not) the port mapping rule for the `gameserver_port`.
		PortMappingManager::instance().attach_callback(ipv4MappingRequest,
			[SessionName, spectatorHost, plyrs, gameType, two, blindMode, four, PlayerName, alliancesType, techLevel, powerLevel, basesLevel](std::string externalIp, uint16_t extPort) // success callback
		{
			// Setup gamestruct with the external ip + port combination received from the LibPlum.
			SetupGameStructInfo(SessionName, PlayerName, externalIp, extPort, spectatorHost, plyrs, gameType, two, blindMode, four, alliancesType, techLevel, powerLevel, basesLevel);
			// Only allow joining the game once the server has successfully discovered it's external IP + port combination.
			//
			// Once this is true, we are able to connect to the lobby server and announce to other players that
			// this game session is available to join to.
			NETEnableAllowJoining(externalIp, extPort);
		}, [SessionName, PlayerName, spectatorHost, plyrs, gameType, two, blindMode, four, alliancesType, techLevel, powerLevel, basesLevel](PortMappingDiscoveryStatus /*status*/) // failure callback
		{
			// Allow joining with the default gameserver host + port combination and proceed as usual in the hope
			// that others will still be able to connect to us.
			SetupGameStructInfo(SessionName, PlayerName, std::string(), 0, spectatorHost, plyrs, gameType, two, blindMode, four, alliancesType, techLevel, powerLevel, basesLevel);
			NETEnableAllowJoining("", gameserver_port);
		});
	}
	else
	{
		ASSERT(!NetPlay.isPortMappingEnabled, "Expected to have an in-flight port mapping request to attach to");

		// Allow joining with the default gameserver host + port combination and proceed as usual in the hope
		// that others will still be able to connect to us.
		SetupGameStructInfo(SessionName, PlayerName, std::string(), 0, spectatorHost, plyrs, gameType, two, blindMode, four, alliancesType, techLevel, powerLevel, basesLevel);
		NETEnableAllowJoining("", gameserver_port);
	}

	return true;
}

// ////////////////////////////////////////////////////////////////////////
// Stop the dplay interface from accepting more players.
bool NEThaltJoining()
{
	debug(LOG_NET, "temporarily locking game to prevent more players");

	allow_joining = false;
	// disconnect from the master server
	NETregisterServer(WZ_SERVER_DISCONNECT);
	return true;
}

// ////////////////////////////////////////////////////////////////////////
// find games on open connection
bool NETenumerateGames(const std::shared_ptr<WzConnectionProvider>& connProvider, const std::function<bool (const GAMESTRUCT& game)>& handleEnumerateGameFunc, const std::function<void(std::string&& lobbyMOTD)>& lobbyMotdFunc)
{
	debug(LOG_NET, "Looking for games...");

	ASSERT_OR_RETURN(false, connProvider != nullptr, "Lobby-specific connection provider is null!");
	const auto hostsResult = connProvider->resolveHost(masterserver_name, masterserver_port);
	if (!hostsResult.has_value())
	{
		const auto hostsErrMsg = hostsResult.error().message();
		debug(LOG_ERROR, "Cannot resolve hostname \"%s\": %s", masterserver_name, hostsErrMsg.c_str());
		return false;
	}
	const auto& hosts = hostsResult.value();
	auto sockResult = connProvider->openClientConnectionAny(*hosts, 15000);

	if (!sockResult.has_value()) {
		const auto sockErrMsg = sockResult.error().message();
		debug(LOG_ERROR, "Cannot connect to \"%s:%d\": %s", masterserver_name, masterserver_port, sockErrMsg.c_str());
		return false;
	}
	IClientConnection* sock = sockResult.value();

	debug(LOG_NET, "New socket = %p", static_cast<void *>(sock));
	debug(LOG_NET, "Sending list cmd");

	const auto writeResult = sock->writeAll("list", sizeof("list"), nullptr);
	if (!writeResult.has_value())
	{
		const auto writeErrMsg = writeResult.error().message();
		debug(LOG_NET, "Server socket encountered error: %s", writeErrMsg.c_str());
		// mark it invalid
		sock->close();

		// when we fail to receive a game count, bail out
		return false;
	}

	// Retrieve the first batch of game structs
	// Earlier versions (and earlier lobby servers) restricted this to no more than 11
	std::vector<GAMESTRUCT> initialBatchOfGameStructs;

	if (!readGameStructsList(*sock, NET_TIMEOUT_DELAY, [&initialBatchOfGameStructs](const GAMESTRUCT &lobbyGame) -> bool {
		initialBatchOfGameStructs.push_back(lobbyGame);
		return true; // continue enumerating
	}))
	{
		// mark it invalid
		sock->close();

		return false;
	}

	// read the lobby response
	uint32_t lobbyStatusCode = 0;
	std::string lobbyMOTD;
	if (!readLobbyResponseInternal(*sock, NET_TIMEOUT_DELAY, lobbyStatusCode, lobbyMOTD).has_value())
	{
		// mark it invalid
		sock->close();
		debug(LOG_INFO, "Failed to get a lobby response!");

		// treat as fatal error
		return false;
	}
	if (lobbyMotdFunc)
	{
		lobbyMotdFunc(std::move(lobbyMOTD));
	}

	// Backwards-compatible protocol enhancement, to raise game limit
	// Expects a uint32_t to determine whether to ignore the first batch of game structs
	// Earlier lobby servers will not provide anything, or may null-pad the lobby response / MOTD string
	// Hence as long as we don't treat "0" as signifying any change in behavior, this should be safe + backwards-compatible
	#define IGNORE_FIRST_BATCH 1
	uint32_t responseParameters = 0;
	const auto readResult = sock->readAll(&responseParameters, sizeof(responseParameters), NET_TIMEOUT_DELAY);
	if (readResult.has_value())
	{
		responseParameters = wz_ntohl(responseParameters);

		bool requestSecondBatch = true;
		bool ignoreFirstBatch = ((responseParameters & IGNORE_FIRST_BATCH) == IGNORE_FIRST_BATCH);
		if (!ignoreFirstBatch)
		{
			// pass the first batch to the handleEnumerateGameFunc
			for (const auto& lobbyGame : initialBatchOfGameStructs)
			{
				if (!handleEnumerateGameFunc(lobbyGame))
				{
					// stop enumerating
					requestSecondBatch = false;
					break;
				}
			}
		}

		if (requestSecondBatch)
		{
			if (!readGameStructsList(*sock, NET_TIMEOUT_DELAY, handleEnumerateGameFunc))
			{
				// we failed to read a second list of game structs

				if (!ignoreFirstBatch)
				{
					// just log and treat the error as non-fatal
					debug(LOG_NET, "Second readGameStructsList call failed - ignoring");
				}
				else
				{
					// if ignoring the first batch, treat this as a fatal error
					debug(LOG_NET, "Second readGameStructsList call failed");

					// mark it invalid
					sock->close();

					// when we fail to receive a game count, bail out
					return false;
				}
			}
		}
	}
	else
	{
		// to support earlier lobby servers that don't provide this additional second batch (and optional parameter), just process the first batch
		for (const auto& lobbyGame : initialBatchOfGameStructs)
		{
			if (!handleEnumerateGameFunc(lobbyGame))
			{
				// stop enumerating
				break;
			}
		}
	}

	// mark it invalid (we are done with it)
	sock->close();

	return true;
}

bool NETfindGames(std::vector<GAMESTRUCT>& results, std::string& lobbyMOTD, size_t startingIndex, size_t resultsLimit, bool onlyMatchingLocalVersion /*= false*/)
{
	size_t gamecount = 0;
	results.clear();
	lobbyMOTD.clear();

	auto connProvider = NET_getLobbyConnectionProvider();
	bool success = NETenumerateGames(connProvider, [&results, &gamecount, startingIndex, resultsLimit, onlyMatchingLocalVersion](const GAMESTRUCT &lobbyGame) -> bool {
		if (gamecount++ < startingIndex)
		{
			// skip this item, continue
			return true;
		}
		if ((resultsLimit > 0) && (results.size() >= resultsLimit))
		{
			// stop processing games
			return false;
		}
		if (onlyMatchingLocalVersion && !NETisCorrectVersion(lobbyGame.game_version_major, lobbyGame.game_version_minor))
		{
			// skip this non-matching version, continue
			return true;
		}
		results.push_back(lobbyGame);
		return true;
	},
	[&lobbyMOTD](std::string&& lobbyMOTDResult) {
		lobbyMOTD = std::move(lobbyMOTDResult);
	});

	return success;
}

bool NETfindGame(uint32_t gameId, GAMESTRUCT& output)
{
	bool foundMatch = false;
	memset(&output, 0x00, sizeof(output));
	auto connProvider = NET_getLobbyConnectionProvider();
	NETenumerateGames(connProvider, [&foundMatch, &output, gameId](const GAMESTRUCT &lobbyGame) -> bool {
		if (lobbyGame.gameId != gameId)
		{
			// not a match - continue enumerating
			return true;
		}
		output = lobbyGame;
		foundMatch = true;
		return false; // stop searching
	});
	return foundMatch;
}

// "consumes" the sockets and related info
bool NETpromoteJoinAttemptToEstablishedConnectionToHost(uint32_t hostPlayer, uint8_t index, const char *playername, NETQUEUE joiningQUEUEInfo, IClientConnection** client_joining_socket, IConnectionPollGroup** client_joining_socket_set)
{
	if (hostPlayer >= MAX_CONNECTED_PLAYERS)
	{
		debug(LOG_ERROR, "Bad host player number (%" PRIu32 ") received from host!", hostPlayer);
		return false;
	}

	if (index >= MAX_CONNECTED_PLAYERS)
	{
		debug(LOG_ERROR, "Bad player number (%u) received from host!", index);
		return false;
	}

	NetPlay.hostPlayer = hostPlayer;

	// On success, promote the temporary socket / socketset / queuepair to their permanent (stable) locations
	NETinitQueue(NETnetQueue(NetPlay.hostPlayer));
	NETmoveQueue(joiningQUEUEInfo, NETnetQueue(NetPlay.hostPlayer));

	// Promote transient socket to stable client connection.
	// bsocket = client_joining_socket, client_joining_socket = nullptr now!
	bsocket = *client_joining_socket;
	*client_joining_socket = nullptr;
	client_socket_set = *client_joining_socket_set;
	*client_joining_socket_set = nullptr;

	debug(LOG_NET, "NET_ACCEPTED received. Accepted into the game - I'm player %u using bsocket %p", (unsigned int)index, static_cast<void *>(bsocket));

	selectedPlayer = index;
	realSelectedPlayer = selectedPlayer;
	NetPlay.isHost = false;
	NetPlay.isHostAlive = true;

	NetPlay.players[index].allocated = true;
	setPlayerName(index, playername);
	NetPlay.players[index].heartbeat = true;

	// Store the host's address
	lastHostAddress = bsocket->textAddress();

	return true;
}

/*!
 * Set the masterserver name
 * \param hostname The hostname of the masterserver to connect to
 */
void NETsetMasterserverName(const char *hostname)
{
	sstrcpy(masterserver_name, hostname);
}

/**
 * @return The hostname of the masterserver we will connect to.
 */
const char *NETgetMasterserverName()
{
	return masterserver_name;
}

/*!
 * Set the masterserver port
 * \param port The port of the masterserver to connect to
 */
void NETsetMasterserverPort(unsigned int port)
{
	const unsigned int MAX_PORT = 65535;
	if (port > MAX_PORT || port == 0)
	{
		debug(LOG_ERROR, "Invalid port number: %u", port);
		return;
	}
	masterserver_port = port;
}

/**
 * @return The port of the masterserver we will connect to.
 */
unsigned int NETgetMasterserverPort()
{
	return masterserver_port;
}

/*!
 * Set the port we shall host games on
 * \param port The port to listen to
 */
void NETsetGameserverPort(unsigned int port)
{
	gameserver_port = port;
}

/**
 * @return The port we will host games on.
 */
unsigned int NETgetGameserverPort()
{
	return gameserver_port;
}

/**
 * @return The size of the join connection challenge (see: NET_PING in NETallowJoining())
 */
uint32_t NETgetJoinConnectionNETPINGChallengeFromHostSize()
{
	return NET_PING_TMP_PING_CHALLENGE_SIZE;
}

uint32_t NETgetJoinConnectionNETPINGChallengeFromClientSize()
{
	return NET_PING_TMP_PING_CHALLENGE_SIZE / 2;
}

/*!
* Set the join preference for IPv6
* \param bTryIPv6First Whether to attempt IPv6 first when joining, before IPv4.
*/
void NETsetJoinPreferenceIPv6(bool bTryIPv6First)
{
	bJoinPrefTryIPv6First = bTryIPv6First;
}

/**
* @return Whether joining a game that advertises both IPv6 and IPv4 should attempt IPv6 first.
*/
bool NETgetJoinPreferenceIPv6()
{
	return bJoinPrefTryIPv6First;
}

void NETsetDefaultMPHostFreeChatPreference(bool enabled)
{
	bDefaultHostFreeChatEnabled = enabled;
}

bool NETgetDefaultMPHostFreeChatPreference()
{
	return bDefaultHostFreeChatEnabled;
}

void NETsetEnableTCPNoDelay(bool enabled)
{
	bEnableTCPNoDelay = enabled;
}

bool NETgetEnableTCPNoDelay()
{
	return bEnableTCPNoDelay;
}

void NETsetPlayerConnectionStatus(CONNECTION_STATUS status, unsigned player)
{
	unsigned n;
	const int timeouts[] = {GAME_TICKS_PER_SEC * 10, GAME_TICKS_PER_SEC * 10, GAME_TICKS_PER_SEC, GAME_TICKS_PER_SEC / 6};
	ASSERT(ARRAY_SIZE(timeouts) == CONNECTIONSTATUS_NORMAL, "Connection status timeout array too small.");

	if (player == NET_ALL_PLAYERS)
	{
		for (n = 0; n < MAX_CONNECTED_PLAYERS; ++n)
		{
			NETsetPlayerConnectionStatus(status, n);
		}
		return;
	}
	if (status == CONNECTIONSTATUS_NORMAL)
	{
		for (n = 0; n < CONNECTIONSTATUS_NORMAL; ++n)
		{
			NET_PlayerConnectionStatus[n][player] = 0;
		}
		return;
	}

	NET_PlayerConnectionStatus[status][player] = realTime + timeouts[status];
}

bool NETcheckPlayerConnectionStatus(CONNECTION_STATUS status, unsigned player)
{
	unsigned n;

	if (player == NET_ALL_PLAYERS)
	{
		for (n = 0; n < MAX_CONNECTED_PLAYERS; ++n)
		{
			if (NETcheckPlayerConnectionStatus(status, n))
			{
				return true;
			}
		}
		return false;
	}
	if (status == CONNECTIONSTATUS_NORMAL)
	{
		for (n = 0; n < CONNECTIONSTATUS_NORMAL; ++n)
		{
			if (NETcheckPlayerConnectionStatus((CONNECTION_STATUS)n, player))
			{
				return true;
			}
		}
		return false;
	}

	return realTime < NET_PlayerConnectionStatus[status][player];
}

const char *messageTypeToString(unsigned messageType_)
{
	MESSAGE_TYPES messageType = (MESSAGE_TYPES)messageType_;  // Cast to enum, so switch gives a warning if new message types are added without updating the switch.

	switch (messageType)
	{
	// Search:  ^\s*([\w_]+).*
	// Replace: case \1:                             return "\1";
	// Search:  (case ...............................) *(return "[\w_]+";)
	// Replace: \t\t\1\2

	// Net-related messages.
	case NET_MIN_TYPE:                  return "NET_MIN_TYPE";
	case NET_PING:                      return "NET_PING";
	case NET_PLAYER_STATS:              return "NET_PLAYER_STATS";
	case NET_TEXTMSG:                   return "NET_TEXTMSG";
	case NET_PLAYERRESPONDING:          return "NET_PLAYERRESPONDING";
	case NET_OPTIONS:                   return "NET_OPTIONS";
	case NET_KICK:                      return "NET_KICK";
	case NET_FIREUP:                    return "NET_FIREUP";
	case NET_COLOURREQUEST:             return "NET_COLOURREQUEST";
	case NET_FACTIONREQUEST:            return "NET_FACTIONREQUEST";
	case NET_AITEXTMSG:                 return "NET_AITEXTMSG";
	case NET_BEACONMSG:                 return "NET_BEACONMSG";
	case NET_TEAMREQUEST:               return "NET_TEAMREQUEST";
	case NET_JOIN:                      return "NET_JOIN";
	case NET_ACCEPTED:                  return "NET_ACCEPTED";
	case NET_PLAYER_INFO:               return "NET_PLAYER_INFO";
	case NET_PLAYER_JOINED:             return "NET_PLAYER_JOINED";
	case NET_PLAYER_LEAVING:            return "NET_PLAYER_LEAVING";
	case NET_PLAYER_DROPPED:            return "NET_PLAYER_DROPPED";
	case NET_GAME_FLAGS:                return "NET_GAME_FLAGS";
	case NET_READY_REQUEST:             return "NET_READY_REQUEST";
	case NET_REJECTED:                  return "NET_REJECTED";
	case NET_POSITIONREQUEST:           return "NET_POSITIONREQUEST";
	case NET_DATA_CHECK:                return "NET_DATA_CHECK";
	case NET_HOST_DROPPED:              return "NET_HOST_DROPPED";
	case NET_SEND_TO_PLAYER:            return "NET_SEND_TO_PLAYER";
	case NET_SHARE_GAME_QUEUE:          return "NET_SHARE_GAME_QUEUE";
	case NET_FILE_REQUESTED:            return "NET_FILE_REQUESTED";
	case NET_FILE_CANCELLED:            return "NET_FILE_CANCELLED";
	case NET_FILE_PAYLOAD:              return "NET_FILE_PAYLOAD";
	case NET_DEBUG_SYNC:                return "NET_DEBUG_SYNC";
	case NET_VOTE:                      return "NET_VOTE";
	case NET_VOTE_REQUEST:              return "NET_VOTE_REQUEST";
	case NET_SPECTEXTMSG:				return "NET_SPECTEXTMSG";
	case NET_PLAYERNAME_CHANGEREQUEST:  return "NET_PLAYERNAME_CHANGEREQUEST";
	case NET_PLAYER_SLOTTYPE_REQUEST:   return "NET_PLAYER_SLOTTYPE_REQUEST";
	case NET_PLAYER_SWAP_INDEX:         return "NET_PLAYER_SWAP_INDEX";
	case NET_PLAYER_SWAP_INDEX_ACK:     return "NET_PLAYER_SWAP_INDEX_ACK";
	case NET_DATA_CHECK2:               return "NET_DATA_CHECK2";
	case NET_SECURED_NET_MESSAGE:		return "NET_SECURED_NET_MESSAGE";
	case NET_TEAM_STRATEGY:				return "NET_TEAM_STRATEGY";
	case NET_QUICK_CHAT_MSG:			return "NET_QUICK_CHAT_MSG";
	case NET_HOST_CONFIG:				return "NET_HOST_CONFIG";
	case NET_MAX_TYPE:                  return "NET_MAX_TYPE";

	// Game-state-related messages, must be processed by all clients at the same game time.
	case GAME_MIN_TYPE:                 return "GAME_MIN_TYPE";
	case GAME_DROIDINFO:                return "GAME_DROIDINFO";
	case GAME_STRUCTUREINFO:            return "GAME_STRUCTUREINFO";
	case GAME_RESEARCHSTATUS:           return "GAME_RESEARCHSTATUS";
	case GAME_TEMPLATE:                 return "GAME_TEMPLATE";
	case GAME_TEMPLATEDEST:             return "GAME_TEMPLATEDEST";
	case GAME_ALLIANCE:                 return "GAME_ALLIANCE";
	case GAME_GIFT:                     return "GAME_GIFT";
	case GAME_LASSAT:                   return "GAME_LASSAT";
	case GAME_GAME_TIME:                return "GAME_GAME_TIME";
	case GAME_PLAYER_LEFT:              return "GAME_PLAYER_LEFT";
	case GAME_DROIDDISEMBARK:           return "GAME_DROIDDISEMBARK";
	case GAME_SYNC_REQUEST:             return "GAME_SYNC_REQUEST";

	// The following messages are used for debug mode.
	case GAME_DEBUG_MODE:               return "GAME_DEBUG_MODE";
	case GAME_DEBUG_ADD_DROID:          return "GAME_DEBUG_ADD_DROID";
	case GAME_DEBUG_ADD_STRUCTURE:      return "GAME_DEBUG_ADD_STRUCTURE";
	case GAME_DEBUG_ADD_FEATURE:        return "GAME_DEBUG_ADD_FEATURE";
	case GAME_DEBUG_REMOVE_DROID:       return "GAME_DEBUG_REMOVE_DROID";
	case GAME_DEBUG_REMOVE_STRUCTURE:   return "GAME_DEBUG_REMOVE_STRUCTURE";
	case GAME_DEBUG_REMOVE_FEATURE:     return "GAME_DEBUG_REMOVE_FEATURE";
	case GAME_DEBUG_FINISH_RESEARCH:    return "GAME_DEBUG_FINISH_RESEARCH";
	// End of redundant messages.
	case GAME_SYNC_OPT_CHANGE:			return "GAME_SYNC_OPT_CHANGE";
	case GAME_MAX_TYPE:                 return "GAME_MAX_TYPE";

	// The following messages are used for playing back replays.
	case REPLAY_ENDED:                  return "REPLAY_ENDED";
	// End of replay messages.
	}
	return "(UNUSED)";
}


void NETacceptIncomingConnections()
{
	ASSERT_HOST_ONLY(return);
	if (!allow_joining)
	{
		return;
	}

	// First-time initialize `tmp_socket_set` if needed.
	if (tmp_socket_set == nullptr)
	{
		// initialize temporary server socket set
		// FIXME: why is this not done in NETinit()?? - Per
		ASSERT_OR_RETURN(, activeConnProvider != nullptr, "Active connection provider is not set!");
		tmp_socket_set = activeConnProvider->newConnectionPollGroup();
		// FIXME: I guess initialization of allowjoining is here now... - FlexCoral
		for (auto& tmpState : tmp_connectState)
		{
			tmpState.reset();
		}
		tmp_pendingIPs.clear();
		// NOTE: Do *NOT* call tmp_badIPs.clear() here - we want to preserve it until quit
	}

	size_t i = 0;
	// Find the first empty socket slot
	for (; i < MAX_TMP_SOCKETS; ++i)
	{
		if (tmp_socket[i] == nullptr)
		{
			break;
		}
	}
	if (i == MAX_TMP_SOCKETS)
	{
		debug(LOG_NET, "all temp sockets are currently used up!");
		return;
	}

	// See if there's an incoming connection
	tmp_socket[i] = server_listen_socket->accept();
	if (!tmp_socket[i])
	{
		return;
	}
	const std::string rIP = tmp_socket[i]->textAddress();
	if (quickRejectConnection(rIP))
	{
		debug(LOG_NET, "freeing temp socket %p (%d)", static_cast<void*>(tmp_socket[i]), __LINE__);
		NETcloseTempSocket(i);
		return;
	}

	NETinitQueue(NETnetTmpQueue(i));
	tmp_socket_set->add(tmp_socket[i]);

	tmp_pendingIPs[rIP]++;

	std::string rIPLogEntry = "Incoming connection from:";
	rIPLogEntry.append(rIP);
	NETlogEntry(rIPLogEntry.c_str(), SYNC_FLAG, i);

	tmp_connectState[i].ip = rIP;
	tmp_connectState[i].connectTime = std::chrono::steady_clock::now();
	tmp_connectState[i].connectState = TmpSocketInfo::TmpConnectState::PendingInitialConnect;

	if (bEnableTCPNoDelay)
	{
		// Disable use of Nagle Algorithm for the TCP socket (i.e. enable TCP_NODELAY option in case of TCP connection)
		tmp_socket[i]->useNagleAlgorithm(false);
	}
}

void NETadjustConnectedTimeoutForClients()
{
	constexpr std::chrono::milliseconds IN_GAME_CONNECTED_TIMEOUT{ 60000 };

	if (NetPlay.isHost)
	{
		for (size_t i = 0; i < MAX_CONNECTED_PLAYERS; ++i)
		{
			if (connected_bsocket[i] != nullptr)
			{
				connected_bsocket[i]->setConnectedTimeout(IN_GAME_CONNECTED_TIMEOUT);
			}
		}
		return;
	}
	if (bsocket)
	{
		bsocket->setConnectedTimeout(IN_GAME_CONNECTED_TIMEOUT);
	}
}

optional<std::string> NET_getCurrentHostTextAddress()
{
	if (!bsocket)
	{
		return lastHostAddress.value();
	}
	return bsocket->textAddress();
}